-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
51 lines (43 loc) · 1.38 KB
/
proxy.ts
File metadata and controls
51 lines (43 loc) · 1.38 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
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
const PUBLIC_ROUTES = [
"/login",
"/signup",
"/forgot-password",
"/reset-password",
"/articles",
"/authors",
"/moderation-policy",
"/reporting",
"/terms",
"/privacy",
"/robots.txt",
"/sitemap.xml",
];
function matchesRoute(pathname: string, route: string) {
return pathname === route || pathname.startsWith(`${route}/`);
}
export async function proxy(request: NextRequest) {
const sessionCookie = getSessionCookie(request);
const { pathname } = request.nextUrl;
const isPublicRoute = PUBLIC_ROUTES.some((route) =>
matchesRoute(pathname, route),
);
const isApiRoute = pathname.startsWith("/api");
const isStaticRoute =
pathname.startsWith("/_next") || pathname.startsWith("/favicon");
// Public, static, and API routes are always allowed through. Auth pages
// validate sessions server-side to avoid cookie-only redirect loops.
if (isPublicRoute || isApiRoute || isStaticRoute || pathname === "/") {
return NextResponse.next();
}
if (!sessionCookie) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|public/).*)"],
};