-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.ts
More file actions
53 lines (46 loc) Β· 2.34 KB
/
Copy pathproxy.ts
File metadata and controls
53 lines (46 loc) Β· 2.34 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
52
53
import { NextResponse, type NextRequest } from 'next/server';
import { updateSession } from '@/lib/supabase/middleware';
// Auth is OFF until the public Supabase env vars are present, so the app keeps working
// unauthenticated until Google sign-in is configured (no risk of locking yourself out).
const AUTH_ENABLED = !!(process.env.NEXT_PUBLIC_SUPABASE_URL && process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY);
// Paths reachable without a session. `/welcome` is the public marketing landing.
const PUBLIC_PREFIXES = ['/login', '/auth', '/welcome'];
// Next.js 16 "proxy" convention (formerly middleware).
export async function proxy(request: NextRequest) {
if (!AUTH_ENABLED) return NextResponse.next();
const { pathname } = request.nextUrl;
const { response, user } = await updateSession(request);
const isPublic = PUBLIC_PREFIXES.some(p => pathname === p || pathname.startsWith(p + '/'));
// A redirect that carries over any session cookies `updateSession` just refreshed β without
// this, a token rotation on a redirected request is lost and the user is silently signed out.
const redirectCarryingSession = (url: URL) => {
const redirect = NextResponse.redirect(url);
for (const cookie of response.cookies.getAll()) redirect.cookies.set(cookie);
return redirect;
};
if (!user && !isPublic) {
const url = request.nextUrl.clone();
// Bare domain β show the landing. Any deeper gated route β login, remembering where to return.
if (pathname === '/') {
url.pathname = '/welcome';
url.search = '';
} else {
url.pathname = '/login';
url.searchParams.set('next', pathname);
}
return redirectCarryingSession(url);
}
// A signed-in user has no use for the landing or the login form β send them into the app.
if (user && (pathname === '/login' || pathname === '/welcome')) {
const url = request.nextUrl.clone();
url.pathname = '/';
url.search = '';
return redirectCarryingSession(url);
}
return response;
}
// Run on everything except Next internals, static assets, and /api (cron uses a bearer secret,
// not a session β it must not be gated).
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|api|.*\\.(?:png|jpg|jpeg|svg|gif|webp|ico)$).*)'],
};