-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
33 lines (26 loc) · 930 Bytes
/
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
import { env } from '@/env'
import { jwtVerify } from 'jose'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export async function middleware(request: NextRequest) {
let isAuthed = false
try {
const token = request.cookies.get('auth')?.value
if (!token) throw new Error()
const secret = new TextEncoder().encode(env.SECRET_TOKEN)
await jwtVerify(token, secret)
isAuthed = true
} catch (err: any) {
request.cookies.delete('auth')
}
if (isAuthed && request.nextUrl.pathname.startsWith('/auth'))
return NextResponse.redirect(new URL('/', request.url))
if (!isAuthed && !request.nextUrl.pathname.startsWith('/auth'))
return NextResponse.redirect(new URL('/auth', request.url))
return NextResponse.next()
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|cross.svg|site.webmanifest|icons/).*)'
]
}