-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
34 lines (27 loc) · 938 Bytes
/
Copy pathmiddleware.ts
File metadata and controls
34 lines (27 loc) · 938 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { getToken } from 'next-auth/jwt'
import { NextRequest, NextResponse } from 'next/server'
// Public paths that don't require authentication
const PUBLIC_PATHS = ['/', '/auth/signin', '/auth/signup']
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl
// Always allow static files, NextAuth API, and public paths
if (
pathname.startsWith('/api/auth') ||
pathname.startsWith('/_next') ||
pathname.startsWith('/favicon') ||
PUBLIC_PATHS.includes(pathname)
) {
return NextResponse.next()
}
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET })
if (!token) {
const url = req.nextUrl.clone()
url.pathname = '/auth/signin'
url.searchParams.set('callbackUrl', pathname)
return NextResponse.redirect(url)
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}