-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
39 lines (33 loc) · 1.06 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
import { NextRequest, NextResponse } from "next/server"
import { validateJWT } from "@/lib/jwt"
export default async function middleware(req: NextRequest, res: NextResponse) {
const { pathname } = req.nextUrl
const PUBLIC_FILE = /\.(.*)$/
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
pathname.startsWith("/static") ||
PUBLIC_FILE.test(pathname)
) {
return NextResponse.next()
}
const jwtCookie = req.cookies.get(process.env.COOKIE_NAME as string)
if (!jwtCookie) {
if (pathname.startsWith("/signin") || pathname.startsWith("/register")) {
return NextResponse.next()
}
req.nextUrl.pathname = "/signin"
return NextResponse.redirect(req.nextUrl)
}
try {
await validateJWT(jwtCookie.value)
if (pathname.startsWith("/signin") || pathname.startsWith("/register")) {
req.nextUrl.pathname = "/home"
return NextResponse.redirect(req.nextUrl)
}
return NextResponse.next()
} catch (error) {
req.nextUrl.pathname = "/signin"
return NextResponse.redirect(req.nextUrl)
}
}