-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
65 lines (57 loc) · 1.8 KB
/
middleware.ts
File metadata and controls
65 lines (57 loc) · 1.8 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { withAuth } from "next-auth/middleware"
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
export default withAuth(
function middleware(req) {
// This function is called if the token exists
// You can access the token via req.nextauth.token
return NextResponse.next()
},
{
callbacks: {
authorized: ({ token, req }) => {
const pathname = req.nextUrl.pathname
// Allow access to public routes
const publicRoutes = ['/login', '/signup', '/api/auth', '/', '/demo', '/forgot-password']
const isPublicRoute = publicRoutes.some(route => pathname.startsWith(route))
if (isPublicRoute) {
return true
}
// Allow access to static files and Next.js internals
if (pathname.startsWith('/_next') || pathname.startsWith('/api/_next')) {
return true
}
// For API routes, check token and return false to trigger 403
if (pathname.startsWith('/api/')) {
if (!token) {
// This will trigger a 403 response for API routes
return false
}
return true
}
// For protected pages, check if token exists
if (!token) {
// For non-API routes, returning false will redirect to login
return false
}
return true
},
},
pages: {
signIn: '/login',
error: '/login',
},
}
)
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
'/((?!_next/static|_next/image|favicon.ico|public).*)',
],
}