DEV Community

Cover image for Token refresh race condition prevention in React Native
Warren de Leon
Warren de Leon

Posted on Originally published at warrendeleon.com

Token refresh race condition prevention in React Native

📚 Supabase Security series — read it in full on warrendeleon.com, where new parts land first.

The bug that looks like a random logout

The worst auth bug is the one that looks like a random logout. No crash, no useful error message, just a user opening the app and getting thrown back to login. Nothing in the logs explains it. The user reports it as "the app keeps signing me out" and the engineer can't reproduce it because it only happens after the access token has expired and multiple screens load at once.

Your token expires. The app makes an API call. Supabase returns a 401. The interceptor catches it, refreshes the token, retries the request. The user never notices. That's the tutorial version. It works perfectly when one request fails at a time.

Now take the same scenario at scale. The user opens the app after an hour. The home screen fires five API calls simultaneously. Profile data, work experience, education, settings, notifications. All five hit the server with an expired token. All five get 401s. All five trigger the interceptor.

Five refresh attempts. At the same time. Against the same refresh token.

The first one succeeds. It gets a new access token and a new refresh token. The old refresh token is now invalid.

The second refresh attempt uses the old refresh token. Supabase rejects it. The third, fourth, and fifth do the same. Four failures. The interceptor catches the failures and logs the user out.

The user opens the app, sees a loading screen for half a second, and gets thrown back to login. Nothing crashed. No error message. Just a silent logout.

This is a race condition. It only happens when multiple requests fire concurrently with an expired token. In development, you're usually testing one screen at a time. In production, the home screen loads everything at once.

The auth client from part 2 of the Supabase-without-the-SDK series is where that race lives. This post, part 3, adds the response interceptor that stops it.

Assumptions

The setup below was written against:

  • React Native 0.74+ (bare or Expo)
  • TypeScript with the standard RN Babel config
  • Axios as the HTTP client (the pattern works with fetch too, but the interceptor API is Axios-specific)
  • A token-refresh-style auth API (Supabase, OAuth, JWT, anything that returns a refresh token)
  • Secure storage for tokens (or any storage that returns a Promise)

The pattern is library-agnostic. If you're not on Axios, replace the interceptor mechanics with your client's equivalent. The state machine (gate, queue, retry) is the same.

"Doesn't the SDK already do this?"

Mostly, yes. The Supabase JS SDK ships autoRefreshToken: true by default and coordinates concurrent refreshes internally. If you're using the SDK, you can stop reading. This post is for the case where you've chosen to talk to Supabase REST directly: bundle size, a wider set of clients sharing the same auth scheme, a need to plug refresh into a custom storage tier, or one of the other reasons covered in Building a Supabase REST client without the SDK. Once you've stepped outside supabase-js, the race becomes yours to handle.

Where this code lives

The snippets below sit on a class that wraps an Axios instance. The full structure:

// src/httpClients/SupabaseAuthClient.ts
import Config from 'react-native-config';
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios';
import { SecureStore, SecureStoreKey } from '@app/utils/storage';

class SupabaseAuthClientClass {
  private axiosInstance: AxiosInstance;
  private isRefreshing = false;
  private refreshSubscribers: Array<(token: string) => void> = [];

  constructor() {
    this.axiosInstance = axios.create({
      baseURL: Config.SUPABASE_URL,
      timeout: 10_000,
      headers: {
        'Content-Type': 'application/json',
        apikey: Config.SUPABASE_ANON_KEY,
      },
    });

    this.axiosInstance.interceptors.request.use(this.attachToken);
    this.axiosInstance.interceptors.response.use(
      response => response,
      this.handle401,
    );
  }

  // ... the methods below all live on this class
}

export const SupabaseAuthClient = new SupabaseAuthClientClass();
Enter fullscreen mode Exit fullscreen mode

Two pieces of state on the class instance: isRefreshing is the gate, refreshSubscribers is the queue. Both are instance properties so they're shared across requests through the same client. If you put them at module scope or per-request, the coordination falls apart.

The class, the export, and the headers block are the same as part 2's, and the apikey default header is required here: the refresh POST goes through this same instance, and Supabase rejects a refresh sent without apikey with a 401.

The naive approach

Most token refresh implementations look like this:

this.axiosInstance.interceptors.response.use(
  response => response,
  async (error) => {
    const originalRequest = error.config;

    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      const refreshToken = await SecureStore.get(SecureStoreKey.REFRESH_TOKEN);
      const { data } = await this.axiosInstance.post(
        '/auth/v1/token?grant_type=refresh_token',
        { refresh_token: refreshToken }
      );

      await SecureStore.set(SecureStoreKey.ACCESS_TOKEN, data.access_token);
      originalRequest.headers.Authorization = `Bearer ${data.access_token}`;
      return this.axiosInstance(originalRequest);
    }
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

One request, one 401, one refresh. Works fine. The _retry flag prevents infinite loops. But there's no coordination between requests.

The five-concurrent-401 timeline:

Timeline (milliseconds):

  0ms  Request A fires → 401
  0ms  Request B fires → 401
  0ms  Request C fires → 401
  0ms  Request D fires → 401
  0ms  Request E fires → 401

  1ms  A starts refresh (refresh_token_v1)
  1ms  B starts refresh (refresh_token_v1)  ← same token!
  1ms  C starts refresh (refresh_token_v1)  ← same token!
  1ms  D starts refresh (refresh_token_v1)  ← same token!
  1ms  E starts refresh (refresh_token_v1)  ← same token!

 50ms  A's refresh succeeds → new tokens stored
       refresh_token_v1 is now INVALID

 51ms  B's refresh fails → refresh_token_v1 rejected
       → SecureStore cleared → user logged out

 52ms  C's refresh fails → same
 53ms  D's refresh fails → same
 54ms  E's refresh fails → same
Enter fullscreen mode Exit fullscreen mode

Five requests. One success. Four failures. One silent logout. The _retry flag only prevents the same request from retrying twice. It does nothing to prevent different requests from all refreshing simultaneously.

The subscriber queue

The fix: only one refresh runs at a time. Every other 401 waits in a queue, and the queue notifies all waiters whether the refresh succeeded or failed.

Two pieces of state:

type SubscriberCallback = (token: string | null, error?: unknown) => void;

private isRefreshing = false;
private refreshSubscribers: SubscriberCallback[] = [];
Enter fullscreen mode Exit fullscreen mode

isRefreshing is a gate. When the first 401 arrives, it flips to true and the refresh starts. When the second, third, fourth, and fifth 401s arrive, they see the gate is closed and add themselves to the queue instead of starting their own refresh.

// The refresh call itself goes through this instance, and so through this
// interceptor. If it comes back 401, bail out instead of queueing it.
if (originalRequest.url?.includes('grant_type=refresh_token')) {
  return Promise.reject(error);
}

if (isTokenExpired && !originalRequest._retry) {
  // Mark this request as already-retried before either branch runs, so a
  // 401 on the retry itself can't drop us back into the queue.
  originalRequest._retry = true;

  // Gate check: is someone already refreshing?
  if (this.isRefreshing) {
    // Yes. Don't refresh. Just wait.
    return new Promise((resolve, reject) => {
      this.refreshSubscribers.push((token, error) => {
        if (error) {
          reject(error);
          return;
        }
        originalRequest.headers.Authorization = `Bearer ${token}`;
        resolve(this.axiosInstance(originalRequest));
      });
    });
  }

  // I'm the first. I'll do the refresh.
  this.isRefreshing = true;
Enter fullscreen mode Exit fullscreen mode

The early-exit guard at the top is the most instructive line in the file. Without it, a 401 on the refresh request itself re-enters this handler, sees isRefreshing is true, and queues itself: a promise that only settles when the refresh finishes, and the refresh is now waiting on that promise. Neither catch nor finally ever runs, the gate stays closed, and every future 401 joins a queue nobody will drain. Supabase normally answers a dead refresh token with a 400, which never enters this path, but a stripped header, a corporate proxy, or a gateway 401 hits the deadlock.

Each subscriber stores a callback function that takes either a token (success) or an error (failure). On success, attach the token and retry. On failure, reject the queued promise so the caller sees the same error the refresh did.

When the refresh finishes:

  try {
    const refreshToken = await SecureStore.get(SecureStoreKey.REFRESH_TOKEN);
    const { data } = await this.axiosInstance.post(
      '/auth/v1/token?grant_type=refresh_token',
      { refresh_token: refreshToken }
    );

    await SecureStore.set(SecureStoreKey.ACCESS_TOKEN, data.access_token);
    await SecureStore.set(SecureStoreKey.REFRESH_TOKEN, data.refresh_token);

    // Wake up everyone in the queue with the new token
    this.refreshSubscribers.forEach(cb => cb(data.access_token));
    this.refreshSubscribers = [];

    // Retry my own request
    originalRequest.headers.Authorization = `Bearer ${data.access_token}`;
    return this.axiosInstance(originalRequest);
  } catch (refreshError) {
    // Refresh failed. Reject every queued request, clear storage, log out.
    this.refreshSubscribers.forEach(cb => cb(null, refreshError));
    this.refreshSubscribers = [];
    await SecureStore.clear();
    return Promise.reject(refreshError);
  } finally {
    this.isRefreshing = false;
  }
Enter fullscreen mode Exit fullscreen mode

Two forEaches, both load-bearing. The success path notifies subscribers with the new token so all five retries fire. The failure path notifies subscribers with the error so all four queued promises reject cleanly instead of hanging. Without the failure-path notification, the four queued requests would never resolve and the UI would freeze on a refresh failure.

The fixed timeline

Same scenario. Five concurrent 401s. Completely different outcome.

Timeline (milliseconds):

  0ms  Request A fires → 401
  0ms  Request B fires → 401
  0ms  Request C fires → 401
  0ms  Request D fires → 401
  0ms  Request E fires → 401

  1ms  A sees isRefreshing=false → starts refresh
       isRefreshing = true

  1ms  B sees isRefreshing=true → joins queue
  1ms  C sees isRefreshing=true → joins queue
  1ms  D sees isRefreshing=true → joins queue
  1ms  E sees isRefreshing=true → joins queue

 50ms  A's refresh succeeds → new tokens stored
       A notifies B, C, D, E with new token
       isRefreshing = false

 51ms+ A, B, C, D, E retry with the new token. The retries fan out
       through the network as normal. All five eventually succeed.
Enter fullscreen mode Exit fullscreen mode

Five requests. One refresh. Zero failures. Zero logouts. The user sees a small delay on their home screen and nothing else.

What about the 403?

Supabase doesn't always return a clean 401. Sometimes an expired token triggers a 403 with a JWT error in the body. If you only check for status === 401, you'll miss these.

const errorData = error.response?.data as
  | { error_code?: string; msg?: string; message?: string }
  | undefined;
const errorMessage = errorData?.msg ?? errorData?.message ?? '';

const isTokenExpired =
  status === 401 ||
  (status === 403 &&
    (errorData?.error_code === 'bad_jwt' ||
      errorMessage.includes('token is expired') ||
      /\bexp\b/.test(errorMessage)));
Enter fullscreen mode Exit fullscreen mode

Three checks: the status code, the error code field, and the error message. The last check matches exp on a word boundary because a bare substring match would also catch "unexpected" or "expected" and treat unrelated 403s as token expiry. Paranoid, but necessary. I've seen Supabase return all three variants depending on which endpoint was called and how the token expired. Test token expiry against every endpoint your app calls before trusting any single error shape.

What if the refresh itself fails?

The finally block resets isRefreshing on every path, success or failure:

} finally {
  this.isRefreshing = false;
}
Enter fullscreen mode Exit fullscreen mode

Without this, a failed refresh would leave the gate permanently closed. Every subsequent 401 would join a queue that never gets processed. The app would freeze on every API call. The guarantee only holds because of the early-exit guard above: it stops the refresh's own 401 from parking itself in the queue before finally gets a chance to run.

When the refresh fails, SecureStore.clear() wipes all tokens. The user gets logged out. That's the correct behaviour. If your refresh token is rejected, the session is dead. Trying to recover from that state would create worse problems than a clean logout.

Where the tokens themselves live

The interceptor reads from iOS Keychain / Android Keystore on every refresh, so backgrounding the app mid-refresh doesn't lose them. The Keychain database itself isn't in the Secure Enclave on iOS, but the encryption key that protects it is, which is the bit that matters here. AsyncStorage or a plain JavaScript variable wouldn't give you that guarantee. I covered the storage tiers in detail in React Native token storage.

Proving it works

You can't trust a fix you haven't tested. The test below uses MSW to fire five concurrent requests through a real public method on the auth client (getCurrentUser), watch all five hit /auth/v1/user with an expired token, count how many times /auth/v1/token is called, and assert exactly one refresh happened even with five 401s.

// src/httpClients/__tests__/SupabaseAuthClient.race.rntl.ts
import { http, HttpResponse } from 'msw';
import { server } from '@app/test-utils/msw/server';
import { SupabaseAuthClient } from '../SupabaseAuthClient';

jest.mock('react-native-config', () => ({
  SUPABASE_URL: 'https://test.supabase.co',
  SUPABASE_ANON_KEY: 'test-anon-key',
}));

jest.mock('@app/config/e2e', () => ({
  isE2EMockEnabled: jest.fn(() => false),
}));

jest.mock('@app/utils/storage/EncryptedStore', () => ({
  EncryptedStore: { set: jest.fn(), get: jest.fn(), clear: jest.fn() },
  EncryptedStoreKey: { USER_EMAIL: 'userEmail' },
}));

// SecureStore.get switches the returned token after the refresh has stored
// the new value, so the second call to /auth/v1/user uses the fresh token.
let currentToken = 'expired-token';
jest.mock('@app/utils/storage/SecureStore', () => ({
  SecureStore: {
    get: jest.fn(async (key: string) => {
      if (key === 'accessToken') return currentToken;
      if (key === 'refreshToken') return 'valid-refresh';
      return null;
    }),
    set: jest.fn(async (key: string, value: string) => {
      if (key === 'accessToken') currentToken = value;
    }),
    clear: jest.fn(),
  },
  SecureStoreKey: {
    ACCESS_TOKEN: 'accessToken',
    REFRESH_TOKEN: 'refreshToken',
    USER_ID: 'userId',
  },
}));

const SUPABASE_URL = 'https://test.supabase.co';

const mockUser = {
  id: '550e8400-e29b-41d4-a716-446655440000',
  aud: 'authenticated',
  email: 'warren@example.com',
  email_confirmed_at: '2026-01-01T00:00:00Z',
  phone: null,
  confirmed_at: '2026-01-01T00:00:00Z',
  last_sign_in_at: '2026-01-01T00:00:00Z',
  created_at: '2026-01-01T00:00:00Z',
};

describe('Token refresh under concurrent 401s', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    server.resetHandlers();
    currentToken = 'expired-token';
  });

  it('only refreshes once when five requests get 401 simultaneously', async () => {
    let refreshCount = 0;
    let userCallCount = 0;

    server.use(
      // /auth/v1/user: returns 401 if the Authorization is the old token, else returns the user
      http.get(`${SUPABASE_URL}/auth/v1/user`, ({ request }) => {
        userCallCount++;
        const auth = request.headers.get('Authorization');
        if (auth === 'Bearer expired-token') {
          return HttpResponse.json({ msg: 'JWT expired' }, { status: 401 });
        }
        return HttpResponse.json(mockUser);
      }),
      // /auth/v1/token: counts how many refreshes hit the server
      http.post(`${SUPABASE_URL}/auth/v1/token`, () => {
        refreshCount++;
        return HttpResponse.json({
          access_token: 'fresh-token',
          refresh_token: 'new-refresh',
          token_type: 'bearer',
          expires_in: 3600,
          user: mockUser,
        });
      }),
    );

    // Fire five concurrent reads against the same client. All five should
    // hit the response interceptor's 401 path, only one should trigger a
    // refresh, and the other four should queue behind it.
    const results = await Promise.all([
      SupabaseAuthClient.getCurrentUser(),
      SupabaseAuthClient.getCurrentUser(),
      SupabaseAuthClient.getCurrentUser(),
      SupabaseAuthClient.getCurrentUser(),
      SupabaseAuthClient.getCurrentUser(),
    ]);

    expect(refreshCount).toBe(1);              // Only ONE refresh hit the network
    expect(userCallCount).toBeGreaterThanOrEqual(5);  // First 5 with old token, then retries with new
    expect(results.every(r => r?.email === 'warren@example.com')).toBe(true);
  });
});
Enter fullscreen mode Exit fullscreen mode

Run it:

yarn jest SupabaseAuthClient.race
Enter fullscreen mode Exit fullscreen mode
PASS  src/httpClients/__tests__/SupabaseAuthClient.race.rntl.ts
  Token refresh under concurrent 401s
    ✓ only refreshes once when five requests get 401 simultaneously (124 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Enter fullscreen mode Exit fullscreen mode

If you remove the isRefreshing gate and run the same test, refreshCount jumps to 5 and the assertion fails. That's the regression test that protects this code from someone reverting the queue "to simplify it".

Common pitfalls

Don't put isRefreshing at module scope. It needs to live on the client instance. Module-level state crosses test isolation and clients-per-environment boundaries; instance state doesn't.

Don't refresh in the request interceptor. The interceptor runs on every request and would gate every call behind a token check, even ones that aren't going to fail. Refresh in the response interceptor when a 401 actually comes back.

Don't forget the _retry flag. Without it, a 401 on the retry itself (because the new token is also bad) sends you back into the queue and you loop forever. The flag is the second guard, after the gate.

Don't drop subscribers on refresh failure. If the refresh fails, the queued requests have to be told. The finally block resets isRefreshing, but you also need to reject every queued request before clearing the array. Without that, queued promises hang forever and the UI freezes.

Don't assume the auth provider returns 401. Supabase sometimes returns 403 with error_code: 'bad_jwt'. The check at the top of the interceptor needs to cover both the status code and the body.

The SDK solves all of this internally and you never see it. Going REST makes this layer yours: more code to own, and code you can read, test and reason about.

The full implementation is at github.com/warrendeleon/rn-warrendeleon, in src/httpClients/SupabaseAuthClient.ts. The live version uses a single in-flight Promise that every caller awaits. Same guarantee (one network round-trip, all waiters resolved together on success, all waiters rejected together on failure), with the gate-and-queue mechanics folded into Promise resolution. The subscriber queue is the version that keeps the state machine visible. Each post in this series is filed under the supabase tag at warrendeleon.com.

Top comments (0)