-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.ts
More file actions
51 lines (42 loc) · 1.55 KB
/
proxy.ts
File metadata and controls
51 lines (42 loc) · 1.55 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 type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
// Add any paths that should be protected
const protectedPaths = ["/dashboard", "/upload"];
// Add any paths that should redirect authenticated users (like auth pages)
const authPaths = ["/auth/signin", "/auth/signup"];
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if the path is protected
const isProtectedPath = protectedPaths.some((path) =>
pathname.startsWith(path),
);
const isAuthPath = authPaths.some((path) => pathname.startsWith(path));
// Get the session cookie
const sessionCookie = request.cookies.get(
"__Secure-better-auth.session_token",
);
// If it's a protected path and no session, redirect to signin
if (isProtectedPath && !sessionCookie) {
const signInUrl = new URL("/auth/signin", request.url);
signInUrl.searchParams.set("redirectTo", pathname);
return NextResponse.redirect(signInUrl);
}
// If it's an auth path and user is already signed in, redirect to dashboard
if (isAuthPath && sessionCookie) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
"/((?!api|_next/static|_next/image|favicon.ico|public).*)",
],
};