-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmiddleware.ts
43 lines (35 loc) · 1.07 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
35
36
37
38
39
40
41
42
43
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { jwtVerify } from 'jose'
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const token = request.cookies.get('token')?.value
const protectedPaths = ['/home', '/manage', '/likes']
if (pathname === '/') {
return NextResponse.redirect(new URL('/login', request.url))
}
let isAuthenticated = false
if (token) {
try {
await jwtVerify(
token,
new TextEncoder().encode(process.env.JWT_SECRET)
)
isAuthenticated = true
} catch {
isAuthenticated = false
}
}
if (isAuthenticated && pathname === '/login') {
return NextResponse.redirect(new URL('/home', request.url))
}
if (!isAuthenticated && protectedPaths.includes(pathname)) {
const url = new URL('/login', request.url)
url.searchParams.set('from', pathname)
return NextResponse.redirect(url)
}
return NextResponse.next()
}
export const config = {
matcher: ['/', '/login', '/home', '/manage', '/likes']
}