diff --git a/app/api/auth/callback/route.ts b/app/api/auth/callback/route.ts index 4abd65e..2e6ba12 100644 --- a/app/api/auth/callback/route.ts +++ b/app/api/auth/callback/route.ts @@ -24,13 +24,18 @@ import Surreal from 'surrealdb'; export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url); + // Get base URL from request headers to preserve the original host + const protocol = request.headers.get('x-forwarded-proto') || 'http'; + const host = request.headers.get('host') || 'localhost:3000'; + const baseUrl = `${protocol}://${host}`; + // Check for error from OAuth provider const error = searchParams.get('error'); if (error) { const errorDescription = searchParams.get('error_description') || 'Unknown error'; console.error('[OAuth Callback] Error from provider:', error, errorDescription); return NextResponse.redirect( - new URL(`/login?error=${encodeURIComponent(errorDescription)}`, request.url) + new URL(`/login?error=${encodeURIComponent(errorDescription)}`, baseUrl) ); } @@ -105,7 +110,7 @@ export async function GET(request: NextRequest) { } // Create redirect response - const response = NextResponse.redirect(new URL(returnTo, request.url)); + const response = NextResponse.redirect(new URL(returnTo, baseUrl)); // Set SurrealDB JWT cookie (for our app's authorization) response.cookies.set('ponderants-auth', surrealJwt, { @@ -130,20 +135,20 @@ export async function GET(request: NextRequest) { if (error instanceof Error) { if (error.message.includes('Invalid state')) { return NextResponse.redirect( - new URL('/login?error=Invalid or expired session', request.url) + new URL('/login?error=Invalid or expired session', baseUrl) ); } if (error.message.includes('DPoP')) { console.error('[OAuth Callback] DPoP error - this should not happen with the library!', error); return NextResponse.redirect( - new URL('/login?error=Authentication protocol error', request.url) + new URL('/login?error=Authentication protocol error', baseUrl) ); } } return NextResponse.redirect( - new URL('/login?error=Authentication failed', request.url) + new URL('/login?error=Authentication failed', baseUrl) ); } }