Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Login works locally but fails in production (callbacks, emails)

We read 6,996 public posts from builders whose apps broke at or after launch and verified 727 recent cases. 54 of them are the same story: sign-in works for the builder and fails for the first real user. The nearest cate

We read 6,996 public posts from builders whose apps broke at or after launch and verified 727 recent cases. 54 of them are the same story: sign-in works for the builder and fails for the first real user. The nearest categories in our split are sign-in & sessions (8% of the 727) and email delivery (3%).

From the builder's side it looks like this. You press "Sign in with GitHub" on the live site and end up on localhost:3000, or back on the login page. A new user's confirmation email never arrives. Or it arrives and says "Token has expired or is invalid" the first time they click it. Every one of your own tests passes, because each failure depends on who is signing in: your address, your browser, your mail provider.

The full troubleshooting page is here. This article is the reproduction, the tests and the fix, using Supabase and Next.js.

Reproduce it

Start with a fresh Supabase project. In Authentication > URL Configuration the Site URL is http://localhost:3000 and the Redirect URLs list is empty. The code below is correct and works on your laptop:

'use client'
import { createBrowserClient } from '@supabase/ssr'

const supabase = createBrowserClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
)

export function Login() {
  const github = () =>
    supabase.auth.signInWithOAuth({
      provider: 'github',
      options: { redirectTo: `${location.origin}/auth/callback` },
    })

  return <button onClick={github}>Sign in with GitHub</button>
}

Locally, redirectTo is http://localhost:3000/auth/callback, which is the Site URL's own origin, so nothing looks wrong. Deploy it to https://app.example.com without touching the dashboard. The code now sends https://app.example.com/auth/callback, which is on no list. A real user finishes at GitHub and is sent to http://localhost:3000/?code=..., a page that does not exist on their machine. On your machine it does exist if your dev server is still running, so you see a working login and conclude production is fine.

Why it happens

There are four separate causes. Each one is checked against the vendor's docs below.

The Site URL still says localhost. The Supabase redirect docs tell you to change it from http://localhost:3000 to your production URL, and say it "defines the default redirect URL when no redirectTo is specified" and is critical for email confirmations and password resets. They also say the URL in redirectTo "should match the Redirect URLs list". What the page does not spell out is the result of a non-matching redirectTo. Reports in Supabase's GitHub discussions describe the user landing on the Site URL, which fits the repro above. Treat that as observed behaviour, not documented behaviour.

Wildcards behave differently from what people assume. * matches a sequence of non-separator characters, where separators are . and /. ** matches any sequence. So http://localhost:3000/* matches /foo but not /foo/bar. For production the docs recommend setting the exact redirect URL path.

The built-in email service is a development tool. The docs say it sends only to pre-authorised addresses, refuses addresses that are not part of the project's team, is currently limited to 2 messages per hour and carries no SLA. That is why your own sign-up works and your first customer's does not. After you save custom SMTP settings, a limit of 30 messages per hour applies until you change it on the Rate Limits page.

Mail scanners spend one-time links. The Supabase email template docs say some providers prefetch links in incoming mail. Their example is Safe Links in Microsoft Defender for Office 365. The link "will be consumed instantly", and the user sees "Token has expired or is invalid". A link that signs someone in on a plain GET request is spent before the person reads the email.

Two more causes sit outside Supabase. Gmail's sender guidelines require SPF or DKIM for your sending domain and spam rates under 0.3% in Postmaster Tools. Unauthenticated messages "might be marked as spam or rejected with a 5.7.26 error". Senders of 5,000 or more messages a day to Gmail also need DMARC. And if your own server sends mail over SMTP from Railway, note that Railway disables SMTP on Free, Trial and Hobby plans and says to use a transactional email service with an HTTPS API.

Catch it before your users do

Both tests below need an address you do not control. Use a fresh Gmail account that is not on your Supabase team, and a throwaway user, because test A consumes the link.

Test A: the link from a real email. Sign up on the production domain with the fresh Gmail address. In the email, copy the link address without clicking it. Save this as linkcheck.mjs (Node 18 or later, no dependencies):

const link = new URL(process.argv[2])
const problems = []
const local = /^https?:\/\/(localhost|127\.0\.0\.1)/

const redirectTo = link.searchParams.get('redirect_to')
if (!redirectTo) problems.push('no redirect_to: the Site URL is used, check it')
else if (local.test(redirectTo)) problems.push(`redirect_to is ${redirectTo}`)
else if (!redirectTo.startsWith('https://')) problems.push(`redirect_to is not https: ${redirectTo}`)

const hit = async () => {
  const res = await fetch(link, { redirect: 'manual' })
  return res.headers.get('location') ?? `(status ${res.status}, no redirect)`
}
const first = await hit()
const second = await hit()
console.log('first request :', first)
console.log('second request:', second)

if (/localhost|127\.0\.0\.1/.test(first)) problems.push('the link redirects to localhost')
if (/error/i.test(second)) problems.push('a second GET was refused: a scanner would spend this link')

problems.forEach((p) => console.error('fail:', p))
if (!problems.length) console.log('pass')
process.exit(problems.length ? 1 : 0)
node linkcheck.mjs "https://<ref>.supabase.co/auth/v1/verify?token=...&type=signup&redirect_to=https://app.example.com/auth/callback"

The first request plays the scanner. The second plays the person. With Supabase's default template the second request is answered with a redirect carrying an error, and the test fails. With the confirm-page pattern in the fix below, both requests are harmless and the test passes. If your provider answers a spent link differently, read the two printed lines and judge them yourself. The first line also prints a session token, which is one more reason to use a throwaway account.

Test B: the sending domain. The selector is shown in your email provider's DNS instructions. Save as mailauth.sh:

#!/bin/sh
# usage: ./mailauth.sh example.com <dkim-selector>
domain=$1; selector=$2; bad=0
check() { if [ -n "$2" ]; then echo "ok   $1"; else echo "fail $1"; bad=1; fi; }

check SPF   "$(dig +short TXT "$domain" | grep 'v=spf1')"
check DKIM  "$(dig +short TXT "$selector._domainkey.$domain" | grep -E 'v=DKIM1|p=')"
check DMARC "$(dig +short TXT "_dmarc.$domain" | grep 'v=DMARC1')"
exit $bad
sh mailauth.sh example.com resend

This proves the records exist, not that mail passes. The real check is the same Gmail inbox: open the sign-up email, choose "Show original", and confirm SPF, DKIM and DMARC all read pass. It should arrive in the inbox, not spam, within a minute.

Two checks no script covers. Complete the OAuth flow once from the production domain and once from a preview URL, with a clean browser profile, and read the address bar at each hop. Then redeploy and reload a signed-in page to confirm the session survives.

The fix

1. Set the production URLs. Change the Site URL to https://app.example.com. Add the exact callback, https://app.example.com/auth/callback, to Redirect URLs. Keep http://localhost:3000/** and your preview pattern as separate entries, since the docs say globstars suit local development and previews. Register the production callback with each OAuth provider as well. Emails already sent keep the old redirect, so send a new one to test.

2. Stop the link from being a one-shot GET. Change the confirmation template so it points at a page of yours, built from a fixed origin rather than the request's Host header:

<a href="https://app.example.com/auth/confirm?token_hash={{ .TokenHash }}&type=email">Confirm your email</a>

That page shows a button. Only the click calls Supabase:

const { error } = await supabase.auth.verifyOtp({ token_hash, type: 'email' })

Supabase documents this confirm-button pattern and a typed-code variant using {{ .Token }} with verifyOtp({ email, token, type: 'email' }). A scanner that fetches the page spends nothing.

3. Send from your own domain. Add custom SMTP or your provider's integration, verify the domain, and publish the SPF, DKIM and DMARC records it gives you. A DMARC policy of none is accepted to start. Register the domain in Google Postmaster Tools. Raise the 30 per hour default if you expect a launch spike. Keep marketing mail on a different sender or subdomain from sign-in mail. If your own server sends mail from a host that blocks SMTP, use the provider's HTTPS API.

4. Check bounces after launch. One address that hard-bounces can quietly stop mail to that person, so look at the provider's suppression list.

Before launch:

  • Site URL is the production origin and the exact callback is on the allow list
  • The production callback is registered with every OAuth provider
  • Test A passes with a Gmail address outside your team
  • Test B passes and "Show original" reads pass for SPF, DKIM and DMARC
  • A redeploy does not sign anyone out
  • A second route into your hosting, DNS and email accounts exists, such as stored backup codes, because recovery after losing a 2FA key can be impossible

Gemmein signs people in with a one-time 8-digit email code and has no OAuth, so there is no callback URL to leave on localhost.

If you have hit a scanner that spends a link in a way a plain GET does not reproduce, which provider was it?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.