templates2.Base.Next/middleware.ts
w4c-templates 219be916cb
Some checks are pending
CI / quality (push) Waiting to run
chore(template): publish Base.Next
2026-10-11 23:23:30 +03:00

29 lines
1 KiB
TypeScript

import { NextResponse, type NextRequest } from 'next/server';
// Keep in sync with lib/server/auth.ts (middleware runs on the edge runtime and must not
// import the server-only auth module).
const SESSION_COOKIE = 'w4c_session';
const PROTECTED = ['/dashboard', '/admin'];
/**
* Coarse gate: unauthenticated visitors are redirected to /login before the page renders,
* so the response is a real 307 (not a streamed client redirect). Role checks stay in the
* page/layout guards, which remain authoritative.
*/
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const isProtected = PROTECTED.some((p) => pathname === p || pathname.startsWith(`${p}/`));
if (!isProtected) return NextResponse.next();
if (request.cookies.get(SESSION_COOKIE)) return NextResponse.next();
const url = request.nextUrl.clone();
url.pathname = '/login';
url.search = '';
url.searchParams.set('next', pathname);
return NextResponse.redirect(url);
}
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*'],
};