-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
32 lines (25 loc) · 1.13 KB
/
Copy pathproxy.ts
File metadata and controls
32 lines (25 loc) · 1.13 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
import { getCookieCache } from "better-auth/cookies";
import { NextResponse, type NextRequest } from "next/server";
const publicPaths = ["/", "/auth/sign-in", "/auth/sign-up"];
export async function proxy(request: NextRequest) {
const path = request.nextUrl.pathname;
// Check if the path is public
if (publicPaths.includes(path)) {
return NextResponse.next();
}
// Optimistically check for session cookie
const session = await getCookieCache(request); // Requires session cookie caching to be enabled in Better Auth config
// If no session is found, redirect to the sign-in page
if (!session) {
const signInUrl = new URL("/auth/sign-in", request.url);
// Add a redirect parameter so the user can be sent back after signing in
signInUrl.searchParams.set("redirect", path);
return NextResponse.redirect(signInUrl);
}
// If authenticated, allow the request to proceed
return NextResponse.next();
}
// Configuration to specify which paths the proxy should run on
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // Match all paths except API routes, static files, etc.
};