-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (41 loc) · 1.29 KB
/
Copy pathmiddleware.ts
File metadata and controls
50 lines (41 loc) · 1.29 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
import { NextRequest, NextResponse } from 'next/server'
import { getToken } from 'next-auth/jwt'
export async function middleware(request: NextRequest) {
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
const token = await getToken({
req: request,
secret
})
const { pathname } = request.nextUrl
const lowerPath = pathname.toLowerCase()
// Define page types
const isAuthPage = lowerPath === '/login' || lowerPath === '/register'
const isProtectedPage =
lowerPath.startsWith('/cart') ||
lowerPath.startsWith('/checkout') ||
lowerPath.startsWith('/allorders') ||
lowerPath.startsWith('/love')
if (token) {
if (isAuthPage) {
return NextResponse.redirect(new URL('/', request.url))
}
return NextResponse.next()
} else {
if (isProtectedPage) {
// Redirect to Login with callbackUrl if possible
const loginUrl = new URL('/Login', request.url)
return NextResponse.redirect(loginUrl)
}
return NextResponse.next()
}
}
export const config = {
matcher: [
'/Cart/:path*',
'/Checkout/:path*',
'/allorders/:path*',
'/Love/:path*',
'/Login',
'/register'
],
}