-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
45 lines (36 loc) · 1.23 KB
/
middleware.js
File metadata and controls
45 lines (36 loc) · 1.23 KB
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
import { NextResponse } from "next/server";
import { verifyToken } from "@/lib/auth";
// Protected routes that require authentication
const protectedPaths = ["/dashboard"];
export async function middleware(request) {
const { pathname } = request.nextUrl;
// Check if path needs protection
const isProtected = protectedPaths.some((p) => pathname.startsWith(p));
if (isProtected) {
const token = request.cookies.get("nightbord_token")?.value;
if (!token) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("redirect", pathname);
return NextResponse.redirect(loginUrl);
}
const payload = await verifyToken(token);
if (!payload) {
const loginUrl = new URL("/login", request.url);
return NextResponse.redirect(loginUrl);
}
}
// If logged in and visiting login page, redirect to dashboard
if (pathname === "/login") {
const token = request.cookies.get("nightbord_token")?.value;
if (token) {
const payload = await verifyToken(token);
if (payload) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/login"],
};