fifteen/apps/web/middleware.ts
2026-03-01 21:59:44 +01:00

30 lines
826 B
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getSession } from "./lib/admin-auth";
export const config = {
matcher: ["/admin/:path*", "/api/admin/:path*"],
};
const PUBLIC_PATHS = ["/admin/login", "/api/admin/login"];
export async function middleware(req: NextRequest): Promise<NextResponse> {
const { pathname } = req.nextUrl;
if (PUBLIC_PATHS.some((p) => pathname.startsWith(p))) {
return NextResponse.next();
}
const session = await getSession(req);
if (!session) {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const url = req.nextUrl.clone();
url.pathname = "/admin/login";
url.searchParams.set("from", pathname);
return NextResponse.redirect(url);
}
return NextResponse.next();
}