-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
72 lines (61 loc) · 2.12 KB
/
middleware.ts
File metadata and controls
72 lines (61 loc) · 2.12 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const PUBLIC_ROUTES = ["/", "/auth", "/auth/login", "/auth/signup"];
const PROTECTED_ROUTES = ["/home", "/page", "/profile", "/settings"];
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const token = req.cookies.get("notex_session")?.value;
// Skip static files, API, and Next internals
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
pathname === "/favicon.ico" ||
pathname.startsWith("/static")
) {
return NextResponse.next();
}
// precise public check: exact "/" only for root, startsWith for others
const isPublic = PUBLIC_ROUTES.some((route) =>
route === "/" ? pathname === "/" : pathname.startsWith(route)
);
// protected: keep startsWith so /page/:id matches
const isProtected = PROTECTED_ROUTES.some((route) =>
pathname.startsWith(route)
);
let validToken = false;
let userName = "";
if (token) {
try {
const res = await fetch(`${req.nextUrl.origin}/api/auth/validate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
});
const data = await res.json();
validToken = !!data.valid;
userName = data.name ?? "";
} catch (err) {
console.error("Token validation failed:", err);
}
}
// 1️⃣ Unauthenticated → block protected routes
if (!validToken && isProtected) {
if (!pathname.startsWith("/auth/login")) {
return NextResponse.redirect(new URL("/auth/login", req.url));
}
return NextResponse.next();
}
// 2️⃣ Authenticated → prevent visiting auth pages (but not other routes)
if (validToken && isPublic) {
// If user is already at home with username, allow that
if (!pathname.startsWith("/home")) {
return NextResponse.redirect(new URL(`/home/${userName}`, req.url));
}
return NextResponse.next();
}
// 3️⃣ Otherwise, continue
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};