Fix guide · updated 2026-11-16
Supabase "invalid flow state, no valid flow state found"
AuthApiError: invalid flow state, no valid flow state found · flow_state_not_found · invalid flow state, flow state has expired
A magic link, a password reset or "Sign in with Google" brings the user back to /auth/callback?code=…, and the sign-in fails with AuthApiError: invalid flow state, no valid flow state found. The Auth logs show a 404 on /token. Supabase received a login code it doesn't have on file. We ran Supabase's real Auth server and supabase-js 2.119 on our machine to see exactly when it says this. Here's what we found, and the fix for each cause.
What the error means
With the PKCE flow (always on with @supabase/ssr, the usual Next.js setup), the link sends the user back to your app with a one-time code. Your app trades it for a session with exchangeCodeForSession(code), adding a secret that was saved in the browser when the sign-in started. Supabase looks the code up in a table of pending sign-ins (auth.flow_state). This error, HTTP 404 with error_code: "flow_state_not_found", means the code isn't in that table.
In our test, the row was deleted the moment the first exchange worked. The same code a second time got exactly this answer. So did codes Supabase never gave out: a random value, or the email's token hash. Three near relatives have different causes:
- "invalid flow state, flow state has expired" (HTTP 422): the code is real but too old. See section 4.
- "code challenge does not match previously saved code verifier" (HTTP 400): the browser's secret belongs to another sign-in attempt. In our test the code survived this: with the right secret, it still worked afterwards.
- "PKCE code verifier not found in storage": supabase-js stops before asking Supabase, because this browser has no secret at all. Usually the link was opened on another device. That one is covered in Supabase "Auth session missing!".
1. The code was exchanged in a Next.js page
This one is easy to miss. The exchange works, but your app throws the result away. In Next.js, only a Route Handler, a Server Action or middleware can set cookies. Exchange the code in a page.tsx (a Server Component) and the session cookie is never saved. Supabase's own utils/supabase/server.ts snippet hides the failure on purpose: its setAll catches the error with the comment "called from a Server Component".
The code is used up on Supabase's side, but the browser keeps its secret and gets no session. Then the code goes out again: on a reload, or from the browser client on that page, which still sees ?code= in the address and a secret in its cookies. That second exchange is the 404. Move the exchange into a Route Handler, as in Supabase's Next.js guide:
// app/auth/callback/route.ts
import { NextResponse } from 'next/server';
import { createClient } from '@/utils/supabase/server';
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get('code');
let next = searchParams.get('next') ?? '/';
if (!next.startsWith('/')) next = '/';
if (code) {
const supabase = await createClient();
const { error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) return NextResponse.redirect(`${origin}${next}`);
// Code already used? If this browser is signed in, the first exchange worked.
const { data: { user } } = await supabase.auth.getUser();
if (user) return NextResponse.redirect(`${origin}${next}`);
}
return NextResponse.redirect(`${origin}/login?error=link`);
}
Point emailRedirectTo and redirectTo at this route. It redirects to an address without code, so nothing else on the page tries again.
2. The same code was exchanged twice
A code works once. If anything sends it a second time after the first exchange finished, and still holds the browser's secret, Supabase answers with this error. What we saw:
- A second server request carrying the old secret cookie (a reload of the callback, the back button, a restored tab, or a second handler such as middleware and a route both exchanging) got the 404.
- The same supabase-js client calling
exchangeCodeForSession()twice in a row never reached Supabase the second time. supabase-js deletes the secret after the first try, so the second call failed with "PKCE code verifier not found" instead. - Two exchanges at the very same moment both worked: Supabase checks the code before it deletes it. So a race (React running an effect twice in development, two clients on one page) isn't what causes the 404. A later second attempt is.
The fix: exchange the code in exactly one place, send the user to an address without code right after, and treat "already signed in" as success (the getUser() check above).
In a browser-only app with flowType: 'pkce', supabase-js already exchanges the code by itself when the page loads (detectSessionInUrl, on by default). Don't call exchangeCodeForSession() as well. In our test, a page that did both got "PKCE code verifier not found" from its own call, while the automatic exchange had already signed the user in and removed code from the address. Wait for the sign-in event instead:
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') {
// signed in: go to the app
}
});
3. The code didn't come from Supabase
Another service's ?code=. Stripe Connect, GitHub, Discord and most other OAuth logins also send users back with a code in the address. If supabase-js loads on that page and finds a leftover secret from a sign-in that was started and never finished, it sends that code to Supabase. In our test that gave this 404, and the leftover secret was deleted. Passing a function as detectSessionInUrl didn't stop it: in supabase-js 2.119 that function only filters the old #access_token= links. Only detectSessionInUrl: false did. Turn it off and exchange the code yourself, on your callback page only:
export const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {
auth: { flowType: 'pkce', detectSessionInUrl: false },
});
// on /auth/callback only
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
const { error } = await supabase.auth.exchangeCodeForSession(code);
}
createBrowserClient() from @supabase/ssr takes the same auth: { detectSessionInUrl: false } option.
The token hash instead of a code. If your email template links to your page with token_hash={{ .TokenHash }}, that value goes to verifyOtp(), not to exchangeCodeForSession(). Passed as a code, it got this 404 in our test. Trade it like this:
const params = new URLSearchParams(window.location.search);
const { error } = await supabase.auth.verifyOtp({
token_hash: params.get('token_hash'),
type: params.get('type'), // 'recovery', 'email', 'invite'…
});
4. "flow state has expired": the code is real but too old
This sibling message (HTTP 422, flow_state_expired) has its own clock. On Auth's default settings, which is what we ran, a pending sign-in lasts 5 minutes, and where the clock starts depends on the link:
- Magic link: 5 minutes from the click to the exchange. A link clicked 40 minutes after it was sent still worked, as long as the exchange happened right away.
- Password reset and signup confirmation: 5 minutes from the moment the email was requested. A reset link clicked 5 min 10 s after the request failed, and so did one clicked after 40 minutes, even though the email link itself was still valid.
If reset or confirm links fail only when people open them a few minutes late, this is why. The robust fix is the token hash link from section 3: in our test it worked 40 minutes after the request, in a different browser, because verifyOtp() doesn't use the 5-minute pending sign-in at all. Change the template in Authentication → Email Templates:
<a href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=recovery">Reset password</a>
Self-hosting Supabase Auth? The window is the GOTRUE_EXTERNAL_FLOW_STATE_EXPIRY_DURATION setting. With 15m, a reset link clicked 10 minutes after the request worked in our test.
If an AI tool built your app
AI builders often exchange the code in a page component, or in two places at once. Paste this into your next prompt:
Our Supabase sign-in callback fails with "invalid flow state, no valid flow state found". Exchange the auth code exactly once: in a Next.js Route Handler at app/auth/callback/route.ts (never in a page.tsx Server Component, which cannot save cookies), or let supabase-js's detectSessionInUrl do it in the browser, never both. After the exchange, redirect to a URL without ?code=. If exchangeCodeForSession fails but supabase.auth.getUser() returns a user, treat it as success. If any page receives another service's ?code= (Stripe, GitHub, Discord), create the browser client with auth: { detectSessionInUrl: false }. For email templates that use {{ .TokenHash }}, call supabase.auth.verifyOtp({ token_hash, type }) instead of exchangeCodeForSession.
Not quite your error?
- "PKCE code verifier not found in storage" or "Auth session missing!": Supabase "Auth session missing!".
- The link itself says it's invalid or expired: Supabase "Email link is invalid or has expired".
- The link sends users to localhost: Supabase login redirects to localhost.
- Google says "redirect_uri_mismatch": Google login "Error 400: redirect_uri_mismatch".
Still stuck?
Open the Auth logs in your Supabase dashboard at the time of the failure and find the /token request with grant_type=pkce that answered 404. If a successful /token call for the same sign-in sits just before it, the code was used twice: look for the second place that exchanges it (sections 1 and 2). If there's none, the code wasn't Supabase's (section 3).
Other Supabase problems? See Supabase fixes.