Supabase magic link or OAuth login redirects to localhost in production
Error message: Supabase email link redirects to localhost:3000
You deploy, try to sign in, and the link in the email opens http://localhost:3000. Supabase is falling back to its default address, and there are three places to fix.
1. Set the Site URL
In Supabase → Authentication → URL Configuration, change Site URL from http://localhost:3000 to your live address, for example https://yourapp.com. This is the fallback used whenever a requested redirect isn't allowed.
2. Allow your redirect URLs
On the same page, add every address that's allowed to receive users after login:
https://yourapp.com/**http://localhost:3000/**(to keep local development working)- A pattern for preview deploys, if you use them. Check your host's preview URL format.
If the address you ask for isn't on this list, Supabase silently uses the Site URL instead. That's why it "randomly" goes to localhost.
3. Ask for the right redirect in code
Don't hard-code localhost. Use an environment variable that differs per environment:
await supabase.auth.signInWithOtp({
email,
options: { emailRedirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/callback` }
});For OAuth it's options.redirectTo in signInWithOAuth. Set NEXT_PUBLIC_SITE_URL in your host's environment variables and redeploy: values starting with NEXT_PUBLIC_ are baked in at build time.
Other things that cause the same symptom
- Custom email templates. If you edited the template and used
{{ .SiteURL }}where the default uses{{ .ConfirmationURL }}, the link ignores your redirect. - Opening the link in a different browser. With
@supabase/ssrthe login uses PKCE. The browser that requested the link stores a code verifier, so opening the email on another device or in another browser fails with an error even when the URL is correct. - No callback route. The link lands on
/auth/callback?code=…. That route must callexchangeCodeForSession(code)and then redirect to your app.
Checklist
- Site URL = your live domain.
- Live domain and localhost are in Redirect URLs, with
/**. emailRedirectTo/redirectTocomes from an environment variable.- Redeployed after setting it.