Joan Comadran
Field notes

Engineering

Supabase email confirmation not working

Supabase email confirmation fails when the token is already dead (otp_expired), when the link is opened outside the sign-up browser, or when Site URL is still localhost:3000.

October 19, 2026Updated December 4, 202617 min read

Supabase email confirmation is not working for one of three reasons, and the URL after the click says which. error_code=otp_expired, with the description "Email link is invalid or has expired", means the one-time token was already used, is past its expiry, or a mail scanner opened the link first. If that URL is localhost:3000/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired&sb=, Auth rejected the token and sent the browser to the Site URL, which on a new project is still http://localhost:3000. A missing PKCE code verifier is the other common failure: the default link was opened outside the browser that signed up.

The fix for the cross-device case is your own route. Point the Confirm signup template at it and verify the token_hash there:

html
<a href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&next=/onboarding">
  Confirm your email
</a>
ts
// app/auth/confirm/route.ts
const { error } = await supabase.auth.verifyOtp({ token_hash, type: 'email' });

The other symptoms are in the table. All of this comes from the sign-up flow of Claient, a multi-tenant WhatsApp lead agent on Next.js and Supabase, where I hit most of these between June and July 2026. Supabase defaults below are as of December 2026.

Which one do you have?

What you seeLikely causeFix
localhost:3000/#error=access_denied&error_code=otp_expired, often with an empty sbToken already used, past the email OTP expiry, or prefetched. Redirect fell back to the default Site URLRead the hash on that page, then resend. Fix Site URL
PKCE code verifier not found in storageLink opened in another browser, app or devicetoken_hash + verifyOtp
Email link is invalid or has expiredSame dead token, before or instead of the redirectResend. For corporate mail, confirm on a button click, or send only {{ .Token }}
No email at allConfirmations off locally, built-in sender (team addresses only, 2 per hour), or the address is already confirmedTurn confirmations on, or custom SMTP. Check identities
Clicked, still email_not_confirmedConfirm route behind auth middleware, or a trigger on auth.users failingMake the route public, debug the trigger

What does the otp_expired URL on localhost:3000 mean?

People paste the whole redirect into Google. The form that shows up in search looks like this:

text
http://localhost:3000/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired&sb=

Three separate facts are packed into that string.

  • error_code=otp_expired is Auth's code for a dead email token. The error code list (3 December 2026) describes it as "OTP code for this sign-in has expired." The description on the redirect is Email link is invalid or has expired, including when the token was never found because it was already used. The OTP verification failures note (4 November 2026) groups that sentence with a 403 on /verify. error=access_denied is the OAuth error name Auth attaches to that 403. It does not mean an admin blocked the user.
  • The hash is always there, and on PKCE the query string gets a copy. Auth's verify redirect writes error, error_code and error_description into the fragment, and adds an empty sb parameter so a client can tell the redirect came from Supabase Auth. On the PKCE flow it also writes those fields into the query string (prepErrorRedirectURL). On the implicit flow they land in the hash only. The Redirect URLs guide tells you to read the fragment with window.location.hash.
  • The host is localhost:3000 because that is the default Site URL. A failed verify still redirects, and with no matching emailRedirectTo the target is the Site URL. The error page is your homepage, not /auth/confirm, so error handling that lives only on the confirm route never runs.

The token is already dead by the time this URL exists. These params are the failure report, not a token you can verify again. Send a new email.

How to read it in Next.js. The fragment stays in the browser. searchParams in a Server Component or Route Handler sees the query string (PKCE) and nothing after #. Read the hash on the client, on the page the redirect actually hits:

tsx
'use client';

import { useEffect, useState } from 'react';

export function AuthHashError() {
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''));
    const query = new URLSearchParams(window.location.search);
    const code = query.get('error_code') ?? hash.get('error_code');
    if (code === 'otp_expired') {
      setMessage('This link has expired or was already used. Sign in and we will send a new one.');
    }
  }, []);

  if (!message) return null;
  return <p>{message}</p>;
}

useSearchParams() does not include the hash. If you only check that, the implicit-flow case looks like a normal visit to /.

PKCE code verifier not found in storage

With @supabase/ssr, sign-up stores a code verifier in a cookie. The default {{ .ConfirmationURL }} hits Supabase /verify, then redirects back with ?code=.... exchangeCodeForSession(code) sends that code plus the verifier.

No verifier, no session. That is the Gmail in-app browser, a phone when the user signed up on a laptop, a private window. The PKCE flow guide says the auth code lasts 5 minutes and works once. A second exchange, or one after those 5 minutes, comes back as flow_state_not_found or flow_state_expired. That is a different failure from otp_expired: the email token was fine, the PKCE handoff was not.

My first Claient callback (commit 5cf4697, June 2026) was the textbook PKCE handler:

ts
// Works only in the sign-up browser
if (code) {
  const { error } = await supabaseServer().auth.exchangeCodeForSession(code);
  if (!error) return NextResponse.redirect(`${origin}${next}`);
}
return NextResponse.redirect(`${origin}/login?error=Could not confirm the account`);

It works when you test it yourself, in the same browser, within five minutes. Two days later (436f7d0) it learned the token_hash path. verifyOtp sends the hashed token and gets a session back, with no cookie from the sign-up browser. Supabase's Next.js examples use an /auth/confirm route for this.

The confirm route

This is the Claient route, translated and trimmed (in Claient it lives at /auth/callback). The template decides which shape arrives, and Supabase's own /verify attaches an error when the token is already dead. On PKCE that error is in the query string, so the route can see it:

ts
// app/auth/confirm/route.ts
import { NextRequest, NextResponse } from 'next/server';
import type { EmailOtpType } from '@supabase/supabase-js';
import { createClient } from '@/lib/supabase/server';

export async function GET(req: NextRequest) {
  const { searchParams, origin } = req.nextUrl;
  const tokenHash = searchParams.get('token_hash');
  const type = searchParams.get('type') as EmailOtpType | null;
  const code = searchParams.get('code');
  const next = internalPath(searchParams.get('next'), '/onboarding');

  const fail = (msg: string) =>
    NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(msg)}`);

  const supabaseError = searchParams.get('error_description') || searchParams.get('error');
  if (supabaseError) return fail(friendly(supabaseError));

  const supabase = await createClient();

  if (tokenHash && type) {
    const { error } = await supabase.auth.verifyOtp({ type, token_hash: tokenHash });
    return error ? fail(friendly(error.message)) : NextResponse.redirect(`${origin}${next}`);
  }

  if (code) {
    const { error } = await supabase.auth.exchangeCodeForSession(code);
    return error ? fail(friendly(error.message)) : NextResponse.redirect(`${origin}${next}`);
  }

  return fail('This confirmation link is not valid.');
}

// `next` comes from the URL. Only allow internal paths ('//evil.com' is an open redirect).
function internalPath(raw: string | null, fallback: string) {
  if (raw?.startsWith('/') && !raw.startsWith('//') && !raw.startsWith('/\\')) return raw;
  return fallback;
}

function friendly(raw: string) {
  const m = raw.toLowerCase();
  if (m.includes('expired')) return 'This link has expired. Sign in and we will send a new one.';
  if (m.includes('invalid') || m.includes('used')) return 'This link was already used. If you confirmed, just sign in.';
  return 'Could not confirm the account. Please sign in.';
}

Use type=email in the template. That is what the current Auth examples pass to verifyOtp, and the server accepts it for both signup confirmation and magic links. signup and magiclink are still on the JavaScript EmailOtpType union. The Python and Flutter references mark those two as deprecated for email verification, so I would not start a new template with them. resend() is a different call: a confirmation resend is type: 'signup', and passing 'email' there is a type error. The JavaScript resend reference shows type: 'signup' with emailRedirectTo.

Three details that each cost me a commit:

  • The next guard. A ?next= you redirect to is an open redirect unless you check it. Claient's callback has had this guard since the audit fixes, and 03f1753 moved it into one shared helper after a review found the same protocol-relative hole (//other-site.com) on another redirect. I wrote about that trap in the pre-launch security checklist.
  • Async client. On Next.js 15 and later cookies() is async, so the server client is await createClient(). Claient predates that and its helper is synchronous.
  • Same route for password recovery. resetPasswordForEmail points at it with next=/reset-password. One route verifies every email link. Recovery uses type=recovery.

This is the same otp_expired 403, whether you see it as JSON from /verify or as the redirect above. Two causes sit in the token itself. A third, a mail scanner, has its own section below.

  1. It was already used. Double-clicks, or the second of two emails after the first one confirmed them. Auth uses the same message when the token is missing and when it is past its expiry.
  2. It expired. As of December 2026 the passwordless guide (1 December 2026) says a magic link and an email OTP last 1 hour, and the CLI config default for auth.email.otp_expiry is 3600 seconds. The JavaScript auth overview still says 24 hours. The value that applies is the dashboard setting, Authentication > Sign In / Providers > Auth Providers > Email > Email OTP expiration. Changing it also changes magic links, confirmation, password recovery, email change and invites. Anything over 86,400 seconds (one day) is discouraged and can only be set through the Management API. The production checklist says to keep it at 3600 seconds or lower.

The fix that mattered more for Claient was the dead end. The login page used to say "confirm your account, check your email", and an expired email had no way to get another one. Since d8f1009, signing in with an unconfirmed account resends on the spot:

ts
const { error } = await supabase.auth.signInWithPassword({ email, password });

if (error?.code === 'email_not_confirmed') {
  const { error: resendError } = await supabase.auth.resend({
    type: 'signup',
    email,
    options: { emailRedirectTo: `${appUrl()}/auth/confirm` },
  });
  // tell the user it was resent, or to wait if the resend was rate limited
}

Before that, Claient showed "wrong email or password" for both cases (18678b9 split them). Saying the account exists but is not confirmed, and handing over a fresh link, is the difference between a stuck user and a signed-in one.

Microsoft Defender Safe Links, and the same idea in other corporate gateways, fetches URLs in the mail before the recipient clicks. The OTP troubleshooting note calls that prefetch the usual reason a token looks expired immediately. {{ .ConfirmationURL }} confirms on GET, so the scanner spends the one-time token and the user's click is otp_expired. A route that calls verifyOtp on GET has the same hole.

The passwordless guide says that if the template still contains a link, opening that link still signs the user in. A code printed next to the link is then the same token. Two fixes, pick one:

  • Link to a page with a Confirm button, and call verifyOtp from that click. Do not call it while the page loads.
  • Send only the code, {{ .Token }}, and drop {{ .ConfirmationURL }} from the template. The default length is 6 digits (auth.email.otp_length). Verify with verifyOtp({ email, token, type: 'email' }) when the person submits it.

Why does Supabase redirect to localhost:3000 after email confirmation?

Auth uses emailRedirectTo only when it matches an entry in the Redirect URLs allow list. Otherwise it falls back to the Site URL. The Redirect URLs guide (30 October 2026) says to change that Site URL from http://localhost:3000 to the production origin. A failed verify uses the same target, which is why the otp_expired hash shows up on the homepage.

  • Set the Site URL to your production domain in Authentication > URL Configuration.
  • Add each redirect you use. Matching is exact unless you add a wildcard. For Vercel, the guide's preview entries are https://*-.vercel.app/** and http://localhost:3000/**. * stops at . and /. ** crosses them. Keep production on an exact path.
  • Send an absolute URL. Claient originally built the redirect from NEXT_PUBLIC_APP_URL with an empty-string fallback, so a missing variable became a relative /auth/callback. A relative URL does not match the allow list, and the password recovery flow fell back to the Site URL without an error in the client. 03f1753 replaced it with an appUrl() helper that always returns an absolute URL.
  • If the template uses {{ .SiteURL }}, the link goes to the Site URL no matter what you passed as emailRedirectTo. Use {{ .RedirectTo }} when each environment should land on its own host. The same guide shows that swap.

Local development reads supabase/config.toml, not the hosted dashboard. As of the CLI config reference, auth.site_url defaults to http://localhost:3000 and is used as an allow-list and for URLs in emails. auth.additional_redirect_urls defaults to ["https://localhost:3000"]: exact, and https, so it does not cover http://localhost:3000/auth/confirm. Add every absolute emailRedirectTo you pass. Changes apply after supabase stop and then supabase start.

toml
[auth]
site_url = "http://localhost:3000"
additional_redirect_urls = [
  "http://localhost:3000/auth/confirm",
  "https://your-domain.example/auth/confirm",
]

[auth.email]
enable_confirmations = true

Why is the Supabase confirmation email not sending?

  • Local sign-up is silent until you ask for the email. Email confirmation is off by default in local development and on by default for hosted projects (20 November 2026). The passwords guide (3 December 2026) says the same. In config.toml, auth.email.enable_confirmations defaults to false. Set it to true and restart the stack, or a local sign-up never sends anything. The confirmation template is sent only when confirmations are on.
  • The built-in sender is for testing, and only for your team. As of December 2026 it delivers only to email addresses on the Supabase organization's team. Any other address fails with email_address_not_authorized ("Email address not authorized"). It also sends 2 emails per hour for the whole project while Confirm email is on. Past that, Auth returns 429 over_email_send_rate_limit. The custom SMTP guide says that hourly cap can change without notice, and that the current value is 2 messages per hour. Example domains such as user@example.com fail separately, with email_address_invalid.
  • Custom SMTP, or a Send Email hook, before launch. Either one lets you mail any address and change the limit under Authentication > Rate Limits. Custom SMTP starts you at 30 emails per hour until you raise it. Turning Confirm email off also removes the built-in hourly cap, and it marks whatever address the person typed as confirmed. Leave it on for a hosted project.
  • Per-user cooldown. The rate limits guide (26 October 2026) gives the same address 60 seconds between signup confirmation requests, and the same window for /otp (magic links and OTPs) and password recovery. Locally, auth.email.max_frequency defaults to 1m. A quick resend inside that window is rejected.
  • The address is already confirmed. The Swift sign-up reference says that when both Confirm email and Confirm phone are enabled (it still says this when the phone provider itself is disabled), signUp on an existing confirmed address returns an obfuscated user whose identities list is empty, and sends no email. When either confirmation is off, the duplicate comes back as "User already registered". The current JavaScript signUp page only says the response may hide the fact that the account exists. Claient checks data.user.identities.length and shows the same "check your email" screen, with links to sign in or reset the password.
  • Spam. Default sender, default template, no domain of your own. Custom SMTP on a domain with SPF, DKIM and DMARC is the usual way out.

Why does the user still get "Email not confirmed"?

Then the verify step did not succeed. Check in this order:

  1. Is the confirm route public? If middleware.ts (renamed proxy.ts in Next.js 16) sends signed-out users to /login and its matcher covers /auth/confirm, the user is bounced before anything verifies. Claient's matcher only covers /dashboard/:path*. On pollitics.es the proxy matcher lists the few routes that need the session and nothing else.
  2. Does a trigger on auth.users fail? A function that creates a profile and throws (a renamed column, a text-to-uuid cast) fails the confirmation with a database error. Claient skips the trigger: the sign-up server action runs an idempotent account setup with the service key, which is easier to retry.
  3. Is it the right project? A preview deployment pointed at a different Supabase project than the one that sent the email.
  4. Read the Auth logs. The /verify request and its error code tell you which section above you are in. otp_expired is the email token. flow_state_expired is the PKCE code.

A 60-second checklist

  1. Confirm signup template links to your route with token_hash and type=email. Keep {{ .ConfirmationURL }} plus exchangeCodeForSession for a flow that starts and finishes in the same browser. If the inbox is corporate mail, confirm on a button click, or send only {{ .Token }}.
  2. The route calls verifyOtp, validates next, and turns Auth's errors into a sentence a user can act on.
  3. The page the redirect actually lands on (often /) reads error_code from the query string and from the hash.
  4. Site URL is production. Every emailRedirectTo is absolute and on the allow list. Locally, auth.site_url and auth.additional_redirect_urls match those URLs, and the stack was restarted after the edit.
  5. Custom SMTP or a Send Email hook is on before real users sign up. Local confirmations are on if you are testing the email.
  6. Sign-in with email_not_confirmed resends, and the confirm route is outside the auth middleware or proxy.

Once confirmation works, the next Supabase error is usually the first insert after sign-up: new row violates row-level security policy. The rest of what I check before a public launch is in the pre-launch security checklist. I do this from Barcelona. The offer is AI engineering.

FAQ

What does error_code=otp_expired mean in Supabase?

Supabase Auth rejected the email token. The redirect is usually http://localhost:3000/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired&sb=. error=access_denied is the label Auth puts on that 403. The description is the same when the token was already used, when it is past the email OTP expiry, and when a mail scanner opened the link first. On the PKCE flow the same fields are also in the query string. The hash stays in the browser, so read window.location.hash on the page the redirect lands on. The token is already dead. Send a new email.

A new project's Site URL is http://localhost:3000. Auth uses emailRedirectTo only when that absolute URL is on the Redirect URLs allow list. Otherwise the browser, including a failed verify, lands on the Site URL. Set Site URL to the production domain, add every redirect you use (the Vercel preview pattern in the docs is https://*-.vercel.app/**), and use {{ .RedirectTo }} in the template when the link should follow emailRedirectTo. Locally, set auth.site_url and auth.additional_redirect_urls in supabase/config.toml and restart with supabase stop and supabase start.

As of December 2026 the passwordless guide and the CLI default auth.email.otp_expiry of 3600 say one hour. The JavaScript auth overview still says 24 hours. The value that applies is Email OTP expiration under Authentication, Sign In / Providers, Auth Providers, Email, and the same number covers magic links, password recovery, email change, and invites. Anything over 86400 seconds can only be set through the Management API. The link works once.

Why is no Supabase confirmation email arriving?

Email confirmation is off by default in local development and on by default on a hosted project, so a local sign-up sends nothing until auth.email.enable_confirmations is true and the stack is restarted. On the built-in sender, as of December 2026, mail goes only to addresses on the Supabase organization's team (anything else fails with email_address_not_authorized) and the project is limited to 2 emails per hour while Confirm email is on. The same user also waits 60 seconds between confirmation requests. Use custom SMTP or a Send Email hook before launch. Custom SMTP starts at 30 emails per hour until you raise it under Authentication, Rate Limits.

Work with me

Want this in your product?

I build AI agents, apps and websites for companies.

Let's talk →

Keep reading

03