-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
50 lines (43 loc) · 1.71 KB
/
proxy.ts
File metadata and controls
50 lines (43 loc) · 1.71 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export function proxy( request: NextRequest ) {
// Get the pathname of the request
const path=request.nextUrl.pathname
// Define public paths that don't require authentication
const publicPaths=[ '/','/auth/signin','/auth/signup' ]
const isPublicPath=publicPaths.some( publicPath => path.startsWith( publicPath ) )
// Check if user is authenticated (has NextAuth.js session cookie)
const hasSession=request.cookies.has( 'next-auth.session-token' )||
request.cookies.has( '__Secure-next-auth.session-token' )||
request.cookies.has( '__Host-next-auth.csrf-token' )
// If the path is public, allow access
if ( isPublicPath ) {
// If user is already authenticated and trying to access auth pages, redirect to dashboard
if ( hasSession&&( path.startsWith( '/auth/signin' )||path.startsWith( '/auth/signup' ) ) ) {
return NextResponse.redirect( new URL( '/dashboard',request.url ) )
}
return NextResponse.next()
}
// If the path requires authentication and user is not authenticated
if ( !hasSession ) {
// Redirect to signin page
const signinUrl=new URL( '/auth/signin',request.url )
signinUrl.searchParams.set( 'callbackUrl',path )
return NextResponse.redirect( signinUrl )
}
// If user is authenticated and accessing protected routes, allow access
return NextResponse.next()
}
export const config={
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
'/((?!api|_next/static|_next/image|favicon.ico|public).*)',
],
}