/** * 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) await supabase.auth.getUser(); return response; } export const config = { matcher: [ // Match everything EXCEPT static files + the static-file API "/((?!_next/static|_next/image|favicon.ico|api/static).*)", ], };