import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { hasValidSessionToken } from "@/lib/auth/roles"; import { ADMIN_SESSION_COOKIE } from "@/lib/auth/session"; import { publicRequestUrl } from "@/lib/request-public-url"; function hasValidSession(request: NextRequest): boolean { return hasValidSessionToken( request.cookies.get(ADMIN_SESSION_COOKIE)?.value, ); } export function proxy(request: NextRequest) { const { pathname } = request.nextUrl; const isLogin = pathname === "/login"; const isAuthApi = pathname.startsWith("/api/auth/"); if (isAuthApi) { return NextResponse.next(); } // Let route handlers return JSON (401, etc.). A redirect to /login breaks `fetch` + `res.json()` in the admin UI. if (!hasValidSession(request) && pathname.startsWith("/api/")) { return NextResponse.next(); } if (isLogin) { if (hasValidSession(request)) { return NextResponse.redirect(publicRequestUrl(request, "/")); } return NextResponse.next(); } if (!hasValidSession(request)) { return NextResponse.redirect(publicRequestUrl(request, "/login")); } return NextResponse.next(); } export const config = { matcher: [ "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)", ], };