-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
41 lines (34 loc) · 1.21 KB
/
Copy pathproxy.ts
File metadata and controls
41 lines (34 loc) · 1.21 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const SESSION_COOKIE = 'better-auth.session_token';
const SECURE_SESSION_COOKIE = `__Secure-${SESSION_COOKIE}`;
function hasSession(request: NextRequest): boolean {
return (
request.cookies.has(SESSION_COOKIE) ||
request.cookies.has(SECURE_SESSION_COOKIE)
);
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const authenticated = hasSession(request);
// Redirect authenticated users away from the homepage to the dashboard
if (pathname === '/' && authenticated) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
// Protect all non-homepage routes: unauthenticated → back to homepage
if (pathname !== '/' && !authenticated) {
return NextResponse.redirect(new URL('/', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all paths except:
* - /api/auth/* (better-auth endpoints must stay public)
* - /_next/* (Next.js internals)
* - /favicon.ico, /public assets
*/
'/((?!api/auth|_next/static|_next/image|favicon.ico|manifest\\.webmanifest|.*\\.svg$|.*\\.png$|.*\\.ico$|.*\\.jpg$|.*\\.webp$).*)',
],
};