Currently I am implementing OAuth login via Supabase and googleCloud
import { NextResponse } from 'next/server'
// The client you created from the Server-Side Auth instructions
import { createClient } from '@/utils/supabase/server'
export async function GET(request: Request) {
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') ?? '/'
if (code) {
const supabase = await createClient()
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (!error) {
const forwardedHost = request.headers.get('x-forwarded-host') // original origin before load balancer
const isLocalEnv = process.env.NODE_ENV === 'development'
if (isLocalEnv) {
// we can be sure that there is no load balancer in between, so no need to watch for X-Forwarded-Host
return NextResponse.redirect(`${origin}${next}`)
} else if (forwardedHost) {
return NextResponse.redirect(`https://${forwardedHost}${next}`)
} else {
return NextResponse.redirect(`${origin}${next}`)
}
}
}
// return the user to an error page with instructions
return NextResponse.redirect(`${origin}/auth/auth-code-error`)
}
In the official Supabase documentation, you can get the code from the URL and use it like this.
But in my project, the url does not contain the code, but contains the access token and refresh token.
I want to know why
import { createServerClient } from '@/lib/supabase/server';
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get('code');
const next = searchParams.get('next') ?? '/dashboard';
console.log('Full callback URL:', request.url);
console.log('Code from query:', code);
if (code) {
const supabase = createServerClient();
const { data, error } = await supabase.auth.exchangeCodeForSession(code);
console.log('Session data:', data);
console.log('Exchange error:', error);
if (!error) {
console.log('Redirecting to:', `${origin}${next}`);
return NextResponse.redirect(`${origin}${next}`);
} else {
console.error('Code exchange failed:', error.message);
}
} else {
console.error('No code provided in callback');
}
return NextResponse.redirect(`${origin}/auth/auth-code-error`);
}
This is my current code