-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
54 lines (49 loc) · 1.54 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
44
45
46
47
48
49
50
51
52
53
import { NextResponse, NextRequest } from 'next/server'
import { jwtVerify } from 'jose'
const secret = process.env.JWT_SIGNING_SECRET || ''
export async function verify(token: string, secret: string) {
const { payload } = await jwtVerify(token, new TextEncoder().encode(secret))
return payload
}
export default async function middleware(req: NextRequest) {
const jwt = req.cookies.get('token')
if (req.nextUrl.pathname === '/') {
if (jwt === undefined) {
return NextResponse.next()
} else {
try {
await verify(jwt, secret)
req.nextUrl.pathname = '/dashboard'
return NextResponse.redirect(req.nextUrl)
} catch (error) {
req.nextUrl.pathname = '/login'
return NextResponse.redirect(req.nextUrl)
}
}
} else {
if (jwt === undefined) {
req.nextUrl.pathname = '/login'
return NextResponse.redirect(req.nextUrl)
}
try {
await verify(jwt, secret)
return NextResponse.next()
} catch (error) {
console.log('middleware error: ', error)
req.nextUrl.pathname = '/login'
return NextResponse.redirect(req.nextUrl)
}
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/dashboard/:path*',
'/reports/:path*',
'/orders/:path*',
'/customers/:path*',
'/billing/:path*',
'/settings/:path*',
'/'
],
}