-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
30 lines (27 loc) · 1.29 KB
/
Copy pathmiddleware.ts
File metadata and controls
30 lines (27 loc) · 1.29 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
/**
* Edge auth gate for the app shell. Sends unauthenticated visitors to /login
* while preserving where they were headed as `?next=` — so a deep link to a
* ticket (e.g. from a notification email) reopens that ticket right after
* sign-in instead of dumping the user in the inbox.
*
* Only the session cookie's PRESENCE is checked here (cheap and edge-safe); the
* server layout still validates it authoritatively. Cookie name mirrors
* SESSION_COOKIE in lib/auth.ts (can't import it — that module is server-only).
*/
const SESSION_COOKIE = 'trove_session';
export function middleware(req: NextRequest) {
if (req.cookies.has(SESSION_COOKIE)) return NextResponse.next();
const { pathname, search } = req.nextUrl;
const loginUrl = new URL('/login', req.nextUrl);
const next = `${pathname}${search}`;
if (next && next !== '/') loginUrl.searchParams.set('next', next);
return NextResponse.redirect(loginUrl);
}
// Run on app pages only — skip API routes (they return their own 401), Next
// internals, files with an extension (static assets), and the public pages
// (login, password reset, the public request form).
export const config = {
matcher: ['/((?!api|_next|.*\\..*|login|reset|form).*)'],
};