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*'], };