forked from Oluwaseyi-vibex/work_nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
25 lines (20 loc) · 877 Bytes
/
middleware.ts
File metadata and controls
25 lines (20 loc) · 877 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
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("accessToken")?.value;
const { pathname } = request.nextUrl;
// 🚀 RULE 1: If on login/register and has token, go to dashboard
if (token && (pathname === "/login" || pathname === "/register")) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
// 🚀 RULE 2: If trying to access dashboard WITHOUT token, go to login
if (!token && pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
// 🚀 CRITICAL: Exclude static files and the login page from the matcher if needed
export const config = {
matcher: ["/dashboard/:path*", "/login", "/register"],
};