import { createServerClient } from "@supabase/ssr"; import { NextResponse, type NextRequest } from "next/server"; export async function proxy(request: NextRequest) { let supabaseResponse = NextResponse.next({ request }); if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY) { return supabaseResponse; } const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY, { cookies: { getAll() { return request.cookies.getAll(); }, setAll(cookiesToSet) { cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value)); supabaseResponse = NextResponse.next({ request }); cookiesToSet.forEach(({ name, value, options }) => supabaseResponse.cookies.set(name, value, options)); }, }, } ); // MUST await — otherwise auth check is useless const { data: { user } } = await supabase.auth.getUser(); const pathname = request.nextUrl.pathname; const isAuthPage = pathname.startsWith("/auth/") && !pathname.includes("callback"); const isDashboard = pathname.startsWith("/dashboard-pages") || pathname.startsWith("/admin"); // Logged-in user on auth pages → redirect to dashboard if (user && isAuthPage) { return NextResponse.redirect(new URL("/dashboard-pages/dashboard", request.url)); } // Not logged in on protected pages → redirect to login if (!user && isDashboard) { const url = request.nextUrl.clone(); url.pathname = "/auth/login"; url.searchParams.set("next", pathname); return NextResponse.redirect(url); } return supabaseResponse; } export const config = { // FIX v4.3: Match ALL routes so auth cookies are refreshed on every page load. // Without this, navigating to / or other non-dashboard pages doesn't refresh // the Supabase session cookie, causing auth to break on page reload. matcher: [ "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)", ], };