-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
34 lines (27 loc) · 1.02 KB
/
middleware.ts
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 { NextResponse } from 'next/server'
import { getToken } from 'next-auth/jwt'
import { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname
// Define public paths that don't require authentication
const isPublicPath = path === '/auth/signin' ||
path === '/auth/signup' ||
path === '/auth/error'
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET
})
// Redirect unauthenticated users to login
if (!token && !isPublicPath) {
return NextResponse.redirect(new URL('/auth/signin', request.url))
}
// Redirect authenticated users away from auth pages
if (token && isPublicPath) {
return NextResponse.redirect(new URL('/', request.url))
}
return NextResponse.next()
}
// Configure which paths this middleware will run on
export const config = {
matcher: ['/', '/profile/:path*', '/settings/:path*', '/auth/:path*']
}