import { NextResponse, NextRequest } from 'next/server' import { createServerClient } from '@supabase/ssr' import { prisma } from '@/lib/prisma' export async function GET(request: NextRequest) { const { searchParams, origin } = new URL(request.url) const code = searchParams.get('code') // if "next" is in param, use it as the redirect URL const next = searchParams.get('next') ?? '/dashboard' // Determine the correct redirect origin (handling ngrok) const forwardedHost = request.headers.get('x-forwarded-host') let redirectOrigin = origin; // If behind ngrok/proxy, use that host if (forwardedHost) { redirectOrigin = `https://${forwardedHost}` } else if (process.env.NODE_ENV === 'development') { // Force HTTP for localhost to avoid SSL errors if not using ngrok redirectOrigin = origin.replace('https', 'http') } if (code) { // Create a response object first so we can manipulate its cookies const response = NextResponse.redirect(`${redirectOrigin}${next}`) const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { getAll() { return request.cookies.getAll() as any; // Cast to any if needed to match generic type }, setAll(cookiesToSet) { cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value) ) cookiesToSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options) ) }, }, } ) const { error, data: { session } } = await supabase.auth.exchangeCodeForSession(code) if (!error && session?.user) { // Sync user to Prisma try { const { user } = session; const email = user.email!; if (email) { await prisma.user.upsert({ where: { email }, update: { image: user.user_metadata?.avatar_url || user.user_metadata?.picture }, create: { id: user.id, email, image: user.user_metadata?.avatar_url || user.user_metadata?.picture, } }); } } catch (e) { console.error("Failed to sync user to Prisma:", e) } return response } } // return the user to an error page with instructions return NextResponse.redirect(`${redirectOrigin}/auth/auth-code-error`) }