-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
33 lines (27 loc) · 921 Bytes
/
Copy pathmiddleware.ts
File metadata and controls
33 lines (27 loc) · 921 Bytes
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 type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
interface JwtPayload {
userId: string;
discordId: string;
}
export async function middleware(request: NextRequest) {
const sessionToken = request.cookies.get("sessionToken")?.value;
const loginUrl = new URL("/login", request.url);
if (!sessionToken) {
return NextResponse.redirect(loginUrl);
}
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET!);
await jwtVerify<JwtPayload>(sessionToken, secret);
return NextResponse.next();
} catch (error) {
console.error("Invalid token:", error);
const response = NextResponse.redirect(loginUrl);
response.cookies.delete("sessionToken");
return response;
}
}
export const config = {
matcher: ["/dashboard/:path*", "/profile"],
};