disclosure-bureau/web/middleware.ts

63 lines
2 KiB
TypeScript
Raw Normal View History

/**
* Next.js middleware refreshes the Supabase auth session on every request,
* so Server Components see the latest user state.
*
* Skipped on static assets and the static-file API to keep them fast.
*/
import { NextResponse, type NextRequest } from "next/server";
import { createServerClient, type CookieOptions } from "@supabase/ssr";
export async function middleware(request: NextRequest) {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
let response = NextResponse.next({ request });
if (!url || !key) {
// Supabase not configured — skip auth refresh entirely
return response;
}
const supabase = createServerClient(url, key, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(toSet: Array<{ name: string; value: string; options?: CookieOptions }>) {
toSet.forEach(({ name, value }) => request.cookies.set(name, value));
response = NextResponse.next({ request });
toSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options));
},
},
});
// Trigger refresh (silently if token still valid)
const { data: { user } } = await supabase.auth.getUser();
// Gate /admin/* by role. Non-admin (including anonymous) gets the public
// 404, not a redirect — we don't want to leak the existence of the route.
const pathname = request.nextUrl.pathname;
if (pathname.startsWith("/admin")) {
if (!user) {
return new NextResponse("Not Found", { status: 404 });
}
const { data: profile } = await supabase
.from("profiles")
.select("role")
.eq("id", user.id)
.maybeSingle();
if (profile?.role !== "admin") {
return new NextResponse("Not Found", { status: 404 });
}
}
return response;
}
export const config = {
matcher: [
// Match everything EXCEPT static files + the static-file API
"/((?!_next/static|_next/image|favicon.ico|api/static).*)",
],
};