import { createClient } from '@supabase/supabase-js' import { NextRequest, NextResponse } from 'next/server' export async function GET(request: NextRequest) { const { searchParams, origin, hash } = new URL(request.url) const code = searchParams.get('code') const error = searchParams.get('error') const error_description = searchParams.get('error_description') const next = searchParams.get('next') ?? '/' console.log('Auth callback received:', { code: code ? 'present' : 'missing', error, error_description, origin, next, hash: hash || 'none', fullUrl: request.url }) // Check for OAuth errors first if (error) { console.error('OAuth error received:', { error, error_description }) return NextResponse.redirect(`${origin}/auth/auth-code-error?error=${error}&description=${encodeURIComponent(error_description || '')}`) } // Handle Authorization Code Flow if (code) { try { const supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! ) console.log('Attempting to exchange code for session...') const { data, error: exchangeError } = await supabase.auth.exchangeCodeForSession(code) if (exchangeError) { console.error('Code exchange failed:', { error: exchangeError.message, status: exchangeError.status, details: exchangeError }) return NextResponse.redirect(`${origin}/auth/auth-code-error?error=exchange_failed&description=${encodeURIComponent(exchangeError.message)}`) } if (data?.session) { console.log('Session created successfully for user:', data.user?.email) return NextResponse.redirect(`${origin}${next}`) } else { console.error('No session created despite successful exchange') return NextResponse.redirect(`${origin}/auth/auth-code-error?error=no_session`) } } catch (err) { console.error('Unexpected error in auth callback:', err) return NextResponse.redirect(`${origin}/auth/auth-code-error?error=unexpected&description=${encodeURIComponent(String(err))}`) } } // Handle Implicit Flow (hash-based tokens) - Lightweight version console.log('No code found, checking for implicit flow tokens...') // Create a minimal response that will handle hash-based tokens on the client side const html = `
Setting up your session...