-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
46 lines (38 loc) · 1.33 KB
/
proxy.ts
File metadata and controls
46 lines (38 loc) · 1.33 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
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";
/**
* Protected routes that require authentication.
* Users without a session cookie will be redirected to login with a `next` param.
*/
const protectedRoutes = ["/dashboard", "/profile"];
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if the current path is a protected route
const isProtectedRoute = protectedRoutes.some(
(route) => pathname === route || pathname.startsWith(`${route}/`),
);
if (!isProtectedRoute) {
return NextResponse.next();
}
// Check for session cookie (optimistic check - full validation happens in page)
const sessionCookie = getSessionCookie(request);
if (!sessionCookie) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("next", pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - api routes
* - _next/static (static files)
* - _next/image (image optimization)
* - favicon.ico, sitemap.xml, robots.txt
* - public files with extensions
*/
"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\..*).*)",
],
};