-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
76 lines (63 loc) · 2.75 KB
/
Copy pathproxy.ts
File metadata and controls
76 lines (63 loc) · 2.75 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
73
74
75
76
/**
* Route guard middleware (middleware.ts — Next.js requires this exact filename)
*
* Protected routes → require a valid signed session cookie
* Auth routes → redirect to /home if already signed in
* Everything else → pass through (landing page, public assets, API)
*
* Runs on the Edge runtime — no Node APIs, no Prisma.
* Only the cookie signature is verified here; the DB is never hit.
*/
import { NextRequest, NextResponse } from "next/server";
import { getSessionUserIdFromCookies } from "@/lib/auth/session";
// ── Route classification ───────────────────────────────────────────────────────
/** Paths that require an authenticated session. */
const PROTECTED_PREFIXES = ["/home", "/settings", "/teams", "/invite"];
/** Auth pages — redirect away if the user is already signed in. */
const AUTH_PREFIXES = [
"/signIn",
"/signUp",
"/forgot-password",
"/reset-password",
];
function isProtected(pathname: string): boolean {
return PROTECTED_PREFIXES.some(
(p) => pathname === p || pathname.startsWith(p + "/"),
);
}
function isAuthPage(pathname: string): boolean {
return AUTH_PREFIXES.some(
(p) => pathname === p || pathname.startsWith(p + "/"),
);
}
// ── Middleware ─────────────────────────────────────────────────────────────────
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const cookieHeader = request.headers.get("cookie");
const userId = await getSessionUserIdFromCookies(cookieHeader);
if (isProtected(pathname)) {
if (!userId) {
// Preserve the destination so we can redirect back after sign-in
const signInUrl = new URL("/signIn", request.url);
signInUrl.searchParams.set("next", pathname);
return NextResponse.redirect(signInUrl);
}
// Valid session — let the request through
return NextResponse.next();
}
if (isAuthPage(pathname)) {
if (userId) {
// Already signed in — send to the app
return NextResponse.redirect(new URL("/home", request.url));
}
return NextResponse.next();
}
return NextResponse.next();
}
// ── Matcher ────────────────────────────────────────────────────────────────────
// Skip Next.js internals and static files; only run on actual page/API routes.
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};