-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
35 lines (30 loc) · 985 Bytes
/
Copy pathmiddleware.ts
File metadata and controls
35 lines (30 loc) · 985 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
34
35
import { jwtVerify } from "jose";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const COOKIE_NAME = "gurbani_session";
function sessionSecret() {
const raw = process.env.SESSION_SECRET?.trim();
if (!raw || raw.length < 16) {
return new TextEncoder().encode("dev-insecure-session-secret");
}
return new TextEncoder().encode(raw);
}
export async function middleware(request: NextRequest) {
const token = request.cookies.get(COOKIE_NAME)?.value;
if (!token) {
const login = new URL("/login", request.url);
login.searchParams.set("next", request.nextUrl.pathname);
return NextResponse.redirect(login);
}
try {
await jwtVerify(token, sessionSecret());
return NextResponse.next();
} catch {
const login = new URL("/login", request.url);
login.searchParams.set("session", "expired");
return NextResponse.redirect(login);
}
}
export const config = {
matcher: ["/dashboard/:path*"]
};