-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathproxy.ts
More file actions
48 lines (41 loc) · 1.35 KB
/
proxy.ts
File metadata and controls
48 lines (41 loc) · 1.35 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
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";
export async function proxy(request: NextRequest) {
const sessionCookie = getSessionCookie(request);
const { pathname } = request.nextUrl;
// Add pathname to headers for layouts
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-pathname", pathname);
// Admin route protection
if (pathname.startsWith("/admin")) {
if (!sessionCookie) {
return NextResponse.redirect(new URL("/", request.url));
}
// Mark as admin path for layout role verification
requestHeaders.set("x-requires-admin", "true");
requestHeaders.set("x-has-session", "true");
}
// User route protection
const userProtectedPaths = ["/contribute", "/my-contributions"];
if (userProtectedPaths.some((path) => pathname.startsWith(path))) {
if (!sessionCookie) {
return NextResponse.redirect(new URL("/auth", request.url));
}
requestHeaders.set("x-requires-auth", "true");
}
// Redirect authenticated users away from auth pages
if (sessionCookie && pathname === "/auth") {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next({
request: { headers: requestHeaders },
});
}
export const config = {
matcher: [
"/admin/:path*",
"/contribute/:path*",
"/my-contributions/:path*",
"/auth",
],
};