auth: Flow State not found

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

I am using self-hosted supabase with gotrue and next js for auth. A few users can’t login to the app because they get redirected to the following page every time they try to sign in with google.

[GET] /auth/callback?next=%2F&error_description=Flow%20State%20not%20found&error=server_error status=307

I haven’t found anything unusual about these users.

On the client side I call

            const { error } = await supabase.auth.signInWithOAuth({
              provider: "google",
              options: {
                redirectTo: `${window.location.origin}/auth/callback?next=${window.location.href}`,
                queryParams: {
                  access_type: "offline",
                  prompt: "consent",
                },
              },
            });

To Reproduce

I haven’t found why it happens to these specific users. They are using mobile chrome and using the same auth flow as other users. They tried logging in using multiple different google accounts.

  1. Go to https://climbest.app/
  2. Click on login
  3. Be lucky I guess?
  4. Get redirected to the Flow State not found error.

Expected behavior

Users can log in to the app.

Screenshots

https://imgur.com/a/D9WGyMH

System information

  • User agent: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36
  • OS: Android 10
  • Browser: Chrome 120
  • Version of supabase-js: 2.39.0
  • Version of Node.js: Node.js 18.x

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 1
  • Comments: 28 (5 by maintainers)

Most upvoted comments

We recently discovered that users clicked twice on the Google OAuth confirmation page, causing issues. The first click successfully triggers Supabase’s /callback, but the second click fails because /callback deletes the flow state ID after the initial successful call.

By the way, I’m using the Supabase cloud not self-hosted.

@J0

I’m getting this when trying to confirm emails using a callback url

const { error } = await supabase.auth.exchangeCodeForSession(code);

We’re also seeing this, it’s happening 20-40 times a day for our users. Redirect looks like this:

/error?error=server_error&error_code=422&error_description=Flow+state+not+found&message=Missing+cod
e#error=server error&error code=422&error_description=Flow+state+not+found

What libraries do you use with NextJS?

    "@supabase/ssr": "^0.0.4",
    "@supabase/supabase-js": "^2.39.0",

Please send us a code snippet that includes the initialization of the Supabase client.

I’m initializing the client like this:

import { createBrowserClient } from "@supabase/ssr";

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

And using like this:

const { error } = await supabase.auth.signInWithOAuth({
  provider: "google",
  options: {
    redirectTo: `${window.location.origin}/auth/callback?next=${window.location.href}`,
    queryParams: {
      access_type: "offline",
      prompt: "consent",
    },
  },
});

I think I copy-pasted code from https://supabase.com/docs/guides/auth/server-side/oauth-with-pkce-flow-for-ssr to my climbclimb/src/app/auth/callback/route.ts:

import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { type CookieOptions, createServerClient } from "@supabase/ssr";

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 cookieStore = cookies();
    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        cookies: {
          get(name: string) {
            return cookieStore.get(name)?.value;
          },
          set(name: string, value: string, options: CookieOptions) {
            cookieStore.set({ name, value, ...options });
          },
          remove(name: string, options: CookieOptions) {
            cookieStore.delete({ name, ...options });
          },
        },
      }
    );

    try {
      if (!code) {
        throw new Error(
          `code param is missing in ${
            request.url
          }; all params: ${JSON.stringify(searchParams)}`
        );
      }
      const { error } = await supabase.auth.exchangeCodeForSession(code);

      if (!error) {
        return NextResponse.redirect(`${next}`);
      } else {
        console.error(error);
        return NextResponse.redirect(`${origin}/?error=${error.message}`);
      }
    } catch (error: unknown) {
      console.log(error);
      if (error instanceof Error) {
        return NextResponse.redirect(`${origin}/?error=${error.message}`);
      } else {
        return NextResponse.redirect(`${origin}/?error=${error?.toString()}`);
      }
    }
  }

  // return the user to an error page with instructions
  return NextResponse.redirect(`${origin}/auth/auth-code-error`);
}

After supabase.auth.exchangeCodeForSession I returned a page that performed a redirect, when I just return return NextResponse.redirect(requestUrl.origin); the problem goes away. I suspect its a race condition with setting/reading the cookie

yes - i have GOTRUE_EXTERNAL_GOOGLE_REDIRECT_URI working with a hosted react site with an external self hosted supabaes ssl site - and basically the app hands off sign in to google - and then google successfully hits the external supabase endpoint - and then website comes good with the callback. it took a few days and eyeballs to work this out.

im self hosting - when i check docker container (ive gone through google sign in many times )

Image

docker-compose logs auth i see the inserts i see the error -

https://mywebsite.com/auth/v1/token?grant_type=pkce

grant_type: pkce {auth_code: “4/0Ab_5qlmQXkW5fewhd38uT4GJu01KQM2-Uza3bnPKB1ucvLrliEpLjDqrZLyhT-oigaQprg”,…} auth_code : “4/0Ab_5qlmQXkW5fewhd38uT4GJu01KQM2-Uza3bnPKB1ucvLrliEpLjDqrZLyhT-oigaQprg” code_verifier : “c92db6530ed056b3754ac4598af499cdeda88ffd9ce1e11f9a3b1ea21504816b438ae7a5a0c315e1b5668882d32efd07d48a01f637d2dc87”

2025/04/30 12:53:45 stderr: [POP] 2025/04/30 12:53:45 sql - INSERT INTO "flow_state" ("auth_code", "auth_code_issued_at", "authentication_method", "code_challenge", "code_challenge_method", "created_at", "id", "provider_access_token", "provider_refresh_token", "provider_type", "updated_at", "user_id") VALUES (:auth_code, :auth_code_issued_at, :authentication_method, :code_challenge, :code_challenge_method, :created_at, :id, :provider_access_token, :provider_refresh_token, :provider_type, :updated_at, :user_id) | [&{c745d9f4-8f41-4c89-aa11-8daff5632e43 <nil> bc2b4a0e-afdd-4333-afc4-704a3c318ab7 oauth Cs5LHDZeP9F0nYQnhiuGGGfGc3v8I1QHJFR2JJkYaCs s256 google   <nil> 2025-04-30 12:53:45.350436 +0000 UTC 2025-04-30 12:53:45.350436 +0000 UTC}] (conn=conn-4760421034211792560, tx=0, maxconn: 0, openconn: 1, in-use: 0, idle: 1)
2025/04/30 12:53:45 stderr: {"component":"api","duration":362696066,"level":"info","method":"GET","msg":"request completed","path":"/authorize","referer":"https://blabla.com/auth/callback","remote_addr":"10.0.1.200","request_id":"b7f5ed71-64d0-4b7f-b81c-178366cc9c0f","status":302,"time":"2025-04-30T12:53:45Z"}
2025/04/30 12:54:00 stderr: {"level":"info","msg":"Request received external host in X-Forwarded-Host or Host headers, but the values have not been added to GOTRUE_MAILER_EXTERNAL_HOSTS and will not be used. To suppress this message add the host, or sanitize the headers before the request reaches Auth.","time":"2025-04-30T12:54:00Z","x_forwarded_host":"\\supabase.nonprod.aws.mailopoly.com","x_forwarded_proto":"http"}
2025/04/30 12:54:00 stderr: [POP] 2025/04/30 12:54:00 sql - SELECT flow_state.auth_code, flow_state.auth_code_issued_at, flow_state.authentication_method, flow_state.code_challenge, flow_state.code_challenge_method, flow_state.created_at, flow_state.id, flow_state.provider_access_token, flow_state.provider_refresh_token, flow_state.provider_type, flow_state.updated_at, flow_state.user_id FROM flow_state AS flow_state WHERE auth_code = $1 LIMIT 1 | ["4/0Ab_5qlmQXkW5fewhd38uT4GJu01KQM2-Uza3bnPKB1ucvLrliEpLjDqrZLyhT-oigaQprg"] (conn=conn-4760421034211792560-UeTesp, tx=0)
2025/04/30 12:54:00 stderr: {"component":"api","error":"404: invalid flow state, no valid flow state found","level":"info","method":"POST","msg":"404: invalid flow state, no valid flow state found","path":"/token","referer":"https://blabla.com/","remote_addr":"10.0.1.200","request_id":"db9c4676-6eab-46b4-a1fd-face8ed02f98","time":"2025-04-30T12:54:00Z"}
2025/04/30 12:54:00 stderr: {"component":"api","duration":11531054,"error_code":"flow_state_not_found","level":"info","method":"POST","msg":"request completed","path":"/token","referer":"https://blabla.com/","remote_addr":"10.0.1.200","request_id":"db9c4676-6eab-46b4-a1fd-face8ed02f98","status":404,"time":"2025-04-30T12:54:00Z"}
2025/04/30 12:54:00 stderr: {"level":"info","msg":"Request received external host in X-Forwarded-Host or Host headers, but the values have not been added to GOTRUE_MAILER_EXTERNAL_HOSTS and will not be used. To suppress this message add the host, or sanitize the headers before the request reaches Auth.","time":"2025-04-30T12:54:00Z","x_forwarded_host":"\\supabase.nonprod.aws.mailopoly.com","x_forwarded_proto":"http"}
2025/04/30 12:54:00 stderr: [POP] 2025/04/30 12:54:00 sql - SELECT flow_state.auth_code, flow_state.auth_code_issued_at, flow_state.authentication_method, flow_state.code_challenge, flow_state.code_challenge_method, flow_state.created_at, flow_state.id, flow_state.provider_access_token, flow_state.provider_refresh_token, flow_state.provider_type, flow_state.updated_at, flow_state.user_id FROM flow_state AS flow_state WHERE auth_code = $1 LIMIT 1 | ["4/0Ab_5qlmQXkW5fewhd38uT4GJu01KQM2-Uza3bnPKB1ucvLrliEpLjDqrZLyhT-oigaQprg"] (conn=conn-4760421034211792560-hFOMCk, tx=0)
2025/04/30 12:54:00 stderr: {"component":"api","error":"404: invalid flow state, no valid flow state found","level":"info","method":"POST","msg":"404: invalid flow state, no valid flow state found","path":"/token","referer":"https://blabla.com/","remote_addr":"10.0.1.200","request_id":"84ed4342-b99b-4409-94f5-6d248ab1ea79","time":"2025-04-30T12:54:00Z"}
2025/04/30 12:54:00 stderr: {"component":"api","duration":5640007,"error_code":"flow_state_not_found","level":"info","method":"POST","msg":"request completed","path":"/token","referer":"https://blabla.com/","remote_addr":"10.0.1.200","request_id":"84ed4342-b99b-4409-94f5-6d248ab1ea79","status":404,"time":"2025-04-30T12:54:00Z"}

UPDATE re-reading @chris-feist - maybe this is root cause. timeout issue or cookie size on nginx. i do an audit by truncated the authflow table.

I’m having the same issue on google on self hosted…Any way to fix this ?

I’m having the same issue with GitHub as the provider. It’s frustrating to see this open for so long without any resolution.

What I realized was happening in my case is that during sign up, resource creation was taking longer than 5 seconds, so the oauth callback was retried. The retried request always failed with this error since I assume the code was already read/processed. I’m using Remix, so I ended up running async functions in parallel to speed up my loader and using Streaming for a better UX.

help same issue, kakao provider too — i handle it

In my case, the error occurred because Nginx received a header from Google that was too large to process

Same for us, google oauth suddenly doesn’t work 30% of the time.

Mostly for mobile users but also happens on Desktop.

Same for us, didn’t see any issue like for months, started to happening last week…

Hey, I am experiencing the same issue. I got this callback URL, unable to replicate it on my side. It was spotted on Pagesense logs.

#error=server_error&error_code=422&error_description=Flow+state+not+found

We have seen that too, but only occasionally and I cannot reproduce that (hence can’t share more than just these):

TypeError: Cannot read properties of undefined (reading 'call')
    at Object.__webpack_require__ [as require] (/var/task/.next/server/webpack-runtime.js:1:161)
    at /var/task/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:111:463
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async rs (/var/task/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:110:4701)
    at async rT (/var/task/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:111:27761)
    at async ee (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:16:24526)
    at async en.responseCache.get.incrementalCache (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:991)
    at async rW.renderToResponseWithComponentsImpl (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:448)
    at async rW.renderPageComponent (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:4990)
    at async rW.renderToResponseImpl (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:5573)
[POST] /auth/login?error=server_error&error_description=Flow%20State%20not%20found&next=%2Fquestion-suggestion status=500

image