Skip to content

Bug: _callRefreshToken permanently deletes session on non-retryable refresh failure, even when access token is still valid #2145

Description

@haveaguess

Bug: _callRefreshToken permanently deletes session on non-retryable refresh failure, even when access token is still valid

Bug report

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

Describe the bug

When getSession() proactively refreshes a token that's within the EXPIRY_MARGIN_MS (90s) window, and the refresh fails with a non-retryable error (e.g. 400 invalid_grant), _callRefreshToken calls _removeSession() which permanently deletes the session from storage — even though the access token is still valid for up to 90 more seconds.

After deletion, every subsequent getSession() call returns { session: null, error: null } forever. The user is silently logged out with no error reported to the caller.

The problematic code

GoTrueClient.ts — _callRefreshToken method (still present in v2.98.0, line ~1997 in compiled output):

catch (error) {
    if (isAuthError(error)) {
        const result = { data: null, error };
        if (!isAuthRetryableFetchError(error)) {
            await this._removeSession();  // 💀 Permanently deletes session from storage
        }
        this.refreshingDeferred?.resolve(result);
        return result;
    }
}

The refresh is triggered proactively by getSession() → __loadSession():

const hasExpired = currentSession.expires_at
    ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS  // 90,000ms
    : false;

if (hasExpired) {
    // Token still valid for up to 90s, but SDK considers it "expired"
    const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token);
    // If this fails → session PERMANENTLY DELETED
}

Why this is wrong

  1. The access token is still valid. The EXPIRY_MARGIN_MS (90s) is a proactive optimization — the token hasn't actually expired. Destroying a valid token because an optimization failed is incorrect.

  2. The refresh failure is often transient. Common causes include refresh token rotation races (two tabs refreshing simultaneously), brief Supabase service issues returning 400 instead of 5xx, and mobile browser tab lifecycle quirks.

  3. There is no recovery path. Once _removeSession() fires, the session is gone from storage. getSession() returns { session: null, error: null } — the error: null means callers have no way to distinguish "user is not logged in" from "SDK destroyed your valid session".

  4. _removeSession() fires SIGNED_OUT event. This is misleading — the user never signed out. Listeners that clean up state on SIGNED_OUT will tear down the application unnecessarily.

Reproduction

Automated test (runs against real GoTrueClient)

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { GoTrueClient } from "@supabase/auth-js";

describe("getSession permanently null after failed refresh", () => {
  let authClient: GoTrueClient;
  let memoryStore: Record<string, string>;

  const createExpiringSession = (secondsUntilExpiry: number) => ({
    access_token: "still-valid-access-token",
    refresh_token: "refresh-token-abc123",
    expires_in: secondsUntilExpiry,
    expires_at: Math.floor(Date.now() / 1000) + secondsUntilExpiry,
    token_type: "bearer",
    user: {
      id: "user-123",
      email: "test@example.com",
      aud: "authenticated",
      role: "authenticated",
      app_metadata: {},
      user_metadata: {},
      created_at: new Date().toISOString(),
    },
  });

  beforeEach(() => {
    vi.useFakeTimers({ shouldAdvanceTime: false });
    memoryStore = {};

    // Mock fetch: returns 400 for refresh (simulates token rotation race)
    const mockFetch = vi.fn().mockImplementation(async (url: string) => {
      if (url.includes("/token?grant_type=refresh_token")) {
        return {
          ok: false,
          status: 400,
          json: async () => ({
            error: "invalid_grant",
            error_description: "Invalid Refresh Token: Already Used",
          }),
          headers: new Headers({ "Content-Type": "application/json" }),
        };
      }
      return { ok: true, status: 200, json: async () => ({}), headers: new Headers() };
    });

    authClient = new GoTrueClient({
      url: "https://fake.supabase.co/auth/v1",
      headers: { apikey: "fake-anon-key" },
      storageKey: "sb-test-auth-token",
      autoRefreshToken: false,
      persistSession: true,
      detectSessionInUrl: false,
      storage: {
        getItem: (key: string) => memoryStore[key] ?? null,
        setItem: (key: string, value: string) => { memoryStore[key] = value; },
        removeItem: (key: string) => { delete memoryStore[key]; },
      },
      fetch: mockFetch,
    });
  });

  afterEach(() => vi.useRealTimers());

  it("BUG: session within 90s margin → refresh 400 → session PERMANENTLY deleted", async () => {
    // Token expires in 60s — within the 90s EXPIRY_MARGIN but STILL VALID
    const session = createExpiringSession(60);
    memoryStore["sb-test-auth-token"] = JSON.stringify(session);

    expect(memoryStore["sb-test-auth-token"]).toBeDefined(); // Session IS in storage

    const result1 = await authClient.getSession();

    // SDK tried to refresh, got 400, called _removeSession()
    expect(result1.data.session).toBeNull();
    expect(memoryStore["sb-test-auth-token"]).toBeUndefined(); // 💀 DELETED from storage

    // All subsequent calls return null forever — no recovery
    const result2 = await authClient.getSession();
    expect(result2.data.session).toBeNull();
    expect(result2.error).toBeNull(); // No error reported — silent failure
  });
});

Browser console reproduction (against a real Supabase instance)

// Run in browser console with any Supabase project
const { createClient } = await import("https://esm.sh/@supabase/supabase-js@2");

const SUPABASE_URL = "https://YOUR_PROJECT.supabase.co";
const ANON_KEY = "YOUR_ANON_KEY";
const REPRO_KEY = "sb-repro-bug-auth-token";

// 1. Inject a session within the 90s danger zone
const nowSec = Math.floor(Date.now() / 1000);
localStorage.setItem(REPRO_KEY, JSON.stringify({
  access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.fake",
  refresh_token: "fake-refresh-token-will-get-400",
  expires_in: 60,
  expires_at: nowSec + 60,  // 60s remaining — within 90s EXPIRY_MARGIN
  token_type: "bearer",
  user: { id: "x", email: "x@x.com", aud: "authenticated", role: "authenticated",
          app_metadata: {}, user_metadata: {}, created_at: new Date().toISOString() }
}));

// 2. Wrap storage to trace operations
const trace = [];
const tracingStorage = {
  getItem: (key) => { const v = localStorage.getItem(key); trace.push({ op: "GET", key, found: v !== null }); return v; },
  setItem: (key, value) => { trace.push({ op: "SET", key }); localStorage.setItem(key, value); },
  removeItem: (key) => { trace.push({ op: "DELETE", key }); localStorage.removeItem(key); },
};

// 3. Create client — initialization triggers _recoverAndRefresh → _callRefreshToken → _removeSession
const supabase = createClient(SUPABASE_URL, ANON_KEY, {
  auth: { autoRefreshToken: false, persistSession: true, detectSessionInUrl: false,
          storageKey: REPRO_KEY, storage: tracingStorage }
});

await new Promise(r => setTimeout(r, 3000));

// 4. Observe the damage
console.table(trace);
// Output:
//   GET  sb-repro-bug-auth-token-code-verifier  → not found
//   GET  sb-repro-bug-auth-token                → found ✅
//   GET  sb-repro-bug-auth-token                → found ✅
//   DELETE sb-repro-bug-auth-token              → 💀 DELETED
//   GET  sb-repro-bug-auth-token                → not found
//   GET  sb-repro-bug-auth-token                → not found

const result = await supabase.auth.getSession();
console.log("session:", result.data.session);  // null
console.log("error:", result.error);            // null — SILENT FAILURE

localStorage.removeItem(REPRO_KEY);

Verified live

We ran this reproduction against a real Supabase instance (sfkvqohjfyohvhgsgybk.supabase.co) with auth-js v2.88.0 and confirmed the storage trace shows the exact sequence: GET (found) → GET (found) → DELETE → GET (not found).

We also confirmed the bug is still present in v2.98.0 — the _removeSession() call inside _callRefreshToken's catch block for non-retryable errors remains at line 1997 of the compiled output.

Real-world impact

We're seeing this in production affecting real users:

  • 19 occurrences, 5 users reported via Sentry
  • Primarily affects Mobile Safari (iOS 18.7) and Chrome on Windows/iOS
  • Manifests as HTTP 401 errors during long-running operations (SSE streams, long http calls) that start during the ~59 minute mark of a session
  • Users have no way to recover without a full page reload and re-login

Suggested fix

_callRefreshToken should not call _removeSession() when the access token is still within its valid expiry window. A proactive refresh failure should degrade gracefully — return the existing (still-valid) session, not destroy it.

// Instead of unconditionally deleting:
if (!isAuthRetryableFetchError(error)) {
    await this._removeSession();
}

// Consider: only remove if the token has ACTUALLY expired
if (!isAuthRetryableFetchError(error)) {
    const currentSession = await this._getSessionFromStorage();
    const actuallyExpired = currentSession?.expires_at
        ? currentSession.expires_at * 1000 < Date.now()
        : true;
    if (actuallyExpired) {
        await this._removeSession();
    } else {
        // Token still valid — keep it, log the refresh failure, try again later
        this._debug('_callRefreshToken', 'refresh failed but token still valid, keeping session');
    }
}

Alternatively, getSession() could simply return the existing session when the proactive refresh fails, since the token hasn't actually expired yet.

Related issues

Note: auth-js has moved into this monorepo at packages/core/auth-js/. The old issues are archived at supabase/auth-js:

Environment

  • auth-js version: 2.88.0 (verified still present in 2.98.0)
  • Browser: Mobile Safari 26.2 (iOS 18.7), Chrome 144 (Windows), Chrome Mobile iOS 145
  • Framework: React (Vite)

Activity

  1. nathanschram commented on Mar 1, 2026

    @nathanschram

    Yeah, your analysis here is spot on - I traced through the same code path in GoTrueClient.ts on master and can confirm everything you've described.

    The core issue is that handleError() in fetch.ts only classifies [502, 503, 504] and network exceptions as AuthRetryableFetchError. A 400 invalid_grant comes back as AuthApiError, so isAuthRetryableFetchError() returns false, and _callRefreshToken nukes the session even though the access token still has time on it.

    What makes this particularly rough is how common invalid_grant is in practice - multi-tab refresh races, mobile browsers suspending/resuming mid-refresh, the refresh token reuse window expiring between request and response. These are all transient situations where the session itself is fine.

    I also noticed _recoverAndRefresh() (the initialisation path) has a double _removeSession() call for the same failure - once inside _callRefreshToken at line ~2728 and again in its own error handler at line ~2649. So during init, SIGNED_OUT fires twice.

    Your suggested fix of checking expires_at * 1000 < Date.now() before calling _removeSession() seems right to me. The proactive refresh is an optimisation - if it fails but the token is still valid, the sensible thing is to keep the session and let the next refresh tick have another go.

    It's also worth noting that supabase/auth-js#915 fixed this same class of bug (premature _removeSession) for sign-in/sign-up flows but didn't touch _callRefreshToken. So there's precedent for the fix pattern.

    For anyone else hitting this in the meantime - there's no clean userland workaround since _removeSession() fires before onAuthStateChange and the session is already gone from storage by the time the SIGNED_OUT event reaches your listener.

    Let me know if there's anything else I can dig into here.

  2. nathanschram commented on Mar 5, 2026

    @nathanschram

    Hey, just checking if that _callRefreshToken diagnosis matched what you were seeing? Happy to dig deeper if the session deletion is still happening.

  3. haveaguess commented on Mar 5, 2026

    @haveaguess
    Author

    Hey, just checking if that _callRefreshToken diagnosis matched what you were seeing? Happy to dig deeper if the session deletion is still happening.

    Hi, thanks for tracing and confirming, yes your diagnosis seems to match what was being seen, I can't guarantee this is the root cause, but this is current theory. Didn't understand your last sentence, the session deletion is still happening because nothing has been fixed? We store the token and use it as a fallback in this scenario rather than relying on supabase api to reliably give us a token.

  4. claygeo commented on Mar 27, 2026

    @claygeo
    Contributor

    This is a real problem. The access token is still valid for up to 90 seconds, but the proactive refresh failure nukes the entire session. The user gets logged out for no user-visible reason.

    The fix should distinguish between two cases:

    1. Proactive refresh (token still valid, within EXPIRY_MARGIN): On failure, keep the session alive and schedule a retry. The access token works until actual expiry.
    2. Reactive refresh (token already expired): On failure, the session is genuinely dead and _removeSession() is correct.

    The key signal is whether Date.now() < expiresAt at the time of the refresh failure. If true, the session should survive the failed refresh attempt. Something like:

    if (error && !isRetryable(error)) {
      if (this._isTokenStillValid(currentSession)) {
        // Proactive refresh failed but token still works -- keep session, warn
        console.warn('Proactive token refresh failed, will retry at expiry');
        return { session: currentSession, error: null };
      }
      // Token actually expired -- session is dead
      await this._removeSession();
      return { session: null, error };
    }

    This matches how mobile SDKs typically handle token refresh: opportunistic refresh failures are silent retries, not session deletions.

  5. thomaslarsson commented on May 16, 2026

    @thomaslarsson

    Sharing this in case it helps. We've been chasing a refresh loop in our app for a while. Small site, less than 10 active users, but at one point we got 30-60k POST /token requests per hour from a single IP, almost all 429s. Some of it was old clients holding stale bundles, but the pattern kept showing up even after we sorted that out.

    We ended up working around it in our own code. A circuit breaker on /token that returns a synthetic 400 to auth-js for 60s after any 4xx and 5min after a 429, plus a location.replace("/") on trip, because otherwise our Realtime channels and components reading session via state will keep firing requests against a session that doesn't exist anymore. It works, but it always felt wrong to have to do this from outside auth-js.

    When I dug into the source to understand why a single bad refresh would loop instead of just failing, I think the answer is in __loadSession (which both getSession and getUser go through). It re-reads the session from storage on every call, and if the token is within EXPIRY_MARGIN_MS (90s) of expiry it calls _callRefreshToken right away. The dedupe via refreshingDeferred only catches concurrent callers. It's set back to null in the parent's finally, so any caller arriving even one tick later starts a brand new refresh against the same broken token.

    This looks like the same root cause as #2344, just showing up with the opposite symptom. There, __loadSession running during init leaves a pendingInLock entry that never resolves and the client deadlocks. For us, __loadSession keeps re-firing _callRefreshToken with nothing to remember that the previous attempt failed, so the client storms instead of hanging. Both come from the same overeager-refresh trigger inside __loadSession, and both will get worse once #2146 lands. With _removeSession no longer called on non-retryable refresh failures, every consumer hitting the 90s margin will re-fire _callRefreshToken until the access token actually expires past the margin or rate limiting kicks in. The same shape already exists on the retryable-error branch (502/503/504/network) since _removeSession isn't called there either. It's just less visible today because the non-retryable branch at least cleans up after itself.

    I think the cleanest fix is to extend the existing dedupe inside _callRefreshToken so failures stick around for a short window instead of being released the moment the request returns. Something like:

    private refreshingDeferred: Deferred<CallRefreshTokenResult> | null = null
    private lastRefreshResult: { result: CallRefreshTokenResult; expiresAt: number } | null = null
    private static readonly REFRESH_FAILURE_COOLDOWN_MS = 30_000
    
    private async _callRefreshToken(refreshToken: string): Promise<CallRefreshTokenResult> {
      // existing concurrent dedupe
      if (this.refreshingDeferred) {
        return this.refreshingDeferred.promise
      }
    
      // serial cooldown after last failure
      if (this.lastRefreshResult && Date.now() < this.lastRefreshResult.expiresAt) {
        return this.lastRefreshResult.result
      }
    
      this.refreshingDeferred = new Deferred()
      try {
        // ... existing success path ...
        this.lastRefreshResult = null
        return result
      } catch (error) {
        const result = { data: null, error }
        if (isAuthError(error) /* and we're preserving the session */) {
          this.lastRefreshResult = {
            result,
            expiresAt: Date.now() + GoTrueClient.REFRESH_FAILURE_COOLDOWN_MS,
          }
        }
        return result
      } finally {
        this.refreshingDeferred = null
      }
    }

    Concurrent callers still share the in-flight refreshingDeferred.promise. Serial callers arriving within the cooldown get the cached failure result. Resetting lastRefreshResult = null on success means the cooldown ends the moment any refresh works, including one arriving via BroadcastChannel from another tab.

    This composes naturally with #2344's suggestion to make __loadSession skip the in-line refresh when called outside the lock. Different protection boundary, same direction. Don't let arbitrary call sites drive refreshes. I'd be in favor of having both.

    If this lands I think we could drop our circuit breaker entirely. Happy to PR if useful.

    Edit: Referenced another issue, updated suggested solution, etc.

  6. mandarini commented on May 18, 2026

    @mandarini
    Contributor

    Hi @haveaguess, thank you for the incredibly thorough writeup on this issue! 💚 And thanks to @nathanschram, @claygeo, and @thomaslarsson for following up with such useful analysis.

    A few things at once:

    On the diagnosis

    Your analysis is correct. _callRefreshToken calling _removeSession() on a non-retryable error inside the 90s EXPIRY_MARGIN_MS window destroys a still-valid session, and there is currently no clean recovery path. The Sentry data you shared is consistent with what we see on our side too. This is a real bug, not a misunderstanding.

    On #2146

    We have decided not to merge that PR (and just closed it). Removing the _removeSession() call unconditionally is not the right fix on its own: the caller still receives { session: null, error }, so from the application's perspective the user is logged out anyway, but the dead session now sticks around in storage. And as @thomaslarsson described above, with no cleanup the proactive-refresh storm pattern gets worse, not better, because every caller hitting the 90s margin keeps re-firing _callRefreshToken against the same broken token until expiry catches up or rate limiting kicks in. This is the same root pattern as #2126 and #2344.

    On the path forward

    We are actively working on a lockless redesign of the auth client that should ship next month. It changes how refresh deduplication and session lifecycle are coordinated, and it is the right place to fix this end to end (proactive vs reactive distinction, failure cooldown, single source of truth for the in-flight refresh, the lot). @thomaslarsson, your cooldown sketch is along the same lines as where we are heading, so thank you for laying that out so clearly. I am keeping that writeup as a reference for the redesign work.

    We are keeping this issue open. I will report back here when the rework lands so you can sanity check it against your scenarios.

    Thank you all for being patient and constructive on this. It really helps.

  7. added
    auth-js
    temp - locks
    on May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    auth-jstemp - locks

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions