Why parallel 401s sign users out
Most token handling starts like this: each request that comes back 401 refreshes the token and tries again.
async function apiFetch(url, options = {}) {
let res = await fetch(url, withAuth(options, accessToken));
if (res.status === 401) {
await refreshToken(); // every failed request refreshes on its own
res = await fetch(url, withAuth(options, accessToken));
}
return res;
}
A server should answer an expired bearer token with a 401 (MDN) and error="invalid_token"; the client may then get a new access token and retry (RFC 6750, section 3.1). Picture a dashboard that loads three panels just after the access token expired: three 401s come back within milliseconds, and three refresh calls leave with the same refresh token. JWT or opaque access token, the race is the same.
With refresh token rotation, every refresh returns a new refresh token and invalidates the old one. RFC 9700, Best Current Practice for OAuth 2.0 Security, requires refresh tokens for public clients to be rotated or sender-constrained, and an OAuth client that runs in the browser is a public client (RFC 6749, section 2.1). When an invalidated refresh token comes back, the server cannot tell the real client from an attacker, so it revokes the active refresh token as well (RFC 9700, section 4.14.2). The client then needs a new grant: usually, the user signs in again.
In the dashboard, the first refresh succeeds. The second carries the refresh token the first one just replaced, so the server revokes the new refresh token too. In Auth0, once reuse is detected, every later refresh is denied until the user signs in again (Auth0 docs). A server without reuse detection may still revoke the old refresh token once it issues a new one (RFC 6749, section 6), and then the second refresh fails with invalid_grant (section 5.2). Either way the second refresh fails, and if your client signs out when a refresh fails, the user is signed out. It looks random because two requests have to fail within the time one refresh takes.
Some providers allow a short overlap. Supabase accepts a used refresh token again for 10 seconds by default, and supabase-js refreshes the session for you shortly before the access token expires (Supabase docs). Auth0 has a Rotation Overlap Period that is off by default (Auth0 docs). Rotation as RFC 9700 describes it has no such window, so fix the client either way.
Fix 1: share one refresh promise
Make the refresh single-flight. The first caller starts it and every later caller gets the same promise. The promise is cleared when it settles, so the next expiry can refresh again:
let refreshing = null; // the refresh in flight, shared by every caller
function refreshOnce() {
if (!refreshing) {
refreshing = refreshToken()
.catch((err) => { signOut(); throw err; }) // sign out once, not once per request
.finally(() => { refreshing = null; });
}
return refreshing;
}
Three calls to refreshOnce() in the same tick now make one call to refreshToken(), and a failed refresh signs the user out once instead of once per waiting request. The waiting requests are your queue: each one resumes, or fails, when the shared promise settles. The same pattern works for any check-then-act across an await (race conditions in JavaScript).
Fix 2: a fetch wrapper that waits and retries once
fetch has no interceptors, so wrap it. The wrapper below follows three rules:
- A request that gets a 401 waits for the shared refresh, then retries once. If the retry gets another 401, the wrapper returns it, so a server that keeps answering 401 cannot loop the app.
- A request that went out with an older token and fails after a refresh already landed retries with the current token, without refreshing.
- The refresh call uses plain
fetch, so a 401 or 400 from the refresh endpoint goes to the failure path and never starts another refresh.
let accessToken = null;
async function refreshToken() {
// plain fetch, not apiFetch: a 401 from the refresh call never starts another refresh
const res = await fetch("/auth/refresh", { method: "POST", credentials: "include" });
if (!res.ok) throw new Error(`Refresh failed: ${res.status}`);
accessToken = (await res.json()).access_token;
}
async function apiFetch(url, options = {}) {
const sentWith = accessToken;
const res = await fetch(url, withAuth(options, sentWith));
if (res.status !== 401) return res;
if (accessToken === sentWith) await refreshOnce(); // skip if a refresh already landed
return fetch(url, withAuth(options, accessToken)); // one retry, never a second refresh
}
function withAuth(options, token) {
const headers = new Headers(options.headers);
if (token) headers.set("Authorization", `Bearer ${token}`);
return { ...options, headers };
}
The second rule saves calls. A slow request can leave with the old token and come back 401 after the refresh finished. Without the sentWith check it refreshes again. That call carries the new refresh token, so nobody is signed out, but your logs show the refresh endpoint called twice.
Fix 3: the same rules in an axios interceptor
In axios, a response interceptor's second function runs for every status outside 2xx (axios: interceptors), and the error carries the request's config and the response with its status (axios: error handling). Mark the config so each request retries once, and send it again through the same instance so the request interceptor sets the new token:
import axios from "axios";
let accessToken = null;
const api = axios.create({ baseURL: "/api" });
api.interceptors.request.use((config) => {
config.sentWith = accessToken; // the token this request carries
if (accessToken) config.headers.set("Authorization", `Bearer ${accessToken}`);
return config;
});
api.interceptors.response.use(
(response) => response,
async (error) => {
const { config, response } = error;
if (response?.status !== 401 || config.retried) throw error;
config.retried = true; // retry each request once
if (config.sentWith === accessToken) await refreshOnce();
return api(config); // the request interceptor sets the new token
}
);
async function refreshToken() {
// the default axios instance does not run api's interceptors, so this call cannot start a refresh
const { data } = await axios.post("/auth/refresh", null, { withCredentials: true });
accessToken = data.access_token;
}
refreshOnce() is the function from fix 1. Send the refresh through api instead of the default instance and a 401 from the refresh endpoint lands in the interceptor, which waits for the refresh that is waiting for it, so the request never settles. The axios docs show the same idea with an isRefreshing flag and a queue of waiting requests (axios: authentication).
Fix 4: one refresh across tabs
The shared promise lives in one tab. Two tabs whose 401s come back together still send two refreshes with the same refresh-token cookie, and reuse detection revokes the session both tabs share. The Web Locks API gives you a lock that every tab and worker of the origin shares, held until the async callback finishes (MDN: LockManager.request()). Take it around the refresh, and post the new access token on a BroadcastChannel, which reaches the other tabs of the origin:
const channel = new BroadcastChannel("auth");
channel.onmessage = (event) => { accessToken = event.data.accessToken; };
async function refreshToken() {
const before = accessToken;
await navigator.locks.request("auth-refresh", async () => {
if (accessToken !== before) return; // another tab refreshed while this one waited
const res = await fetch("/auth/refresh", { method: "POST", credentials: "include" });
if (!res.ok) throw new Error(`Refresh failed: ${res.status}`);
accessToken = (await res.json()).access_token;
channel.postMessage({ accessToken });
});
}
With the lock, the second tab's refresh starts after the first one's response came back, so it carries the new cookie and is not a reuse. That tab may still make its own call if it gets the lock before the message arrives, which costs an extra request but signs nobody out. Tabs that had not hit a 401 take the token from the message and skip the refresh. This assumes an HttpOnly refresh-token cookie, which every tab shares. Web Locks needs a secure context (HTTPS).
Fix 5: refresh before the token expires
The token response usually says how long the access token lives: expires_in, in seconds (RFC 6749, section 5.1). Schedule a refresh a minute before that (halfway, for tokens that live under two minutes), through refreshOnce(), so a timer and a 401 at the same moment still make one call:
let timer;
// call it after every refresh with the response's expires_in, in seconds
function scheduleRefresh(expiresIn) {
clearTimeout(timer);
if (!(expiresIn > 0)) return; // no lifetime given: the 401 path handles it
const seconds = Math.max(expiresIn - 60, expiresIn / 2); // a minute early, or halfway
timer = setTimeout(() => refreshOnce().catch(() => {}), seconds * 1000);
}
Keep the 401 path anyway. Browsers enforce a minimum delay on timers in background tabs, so the timer can fire late (MDN), and a server can revoke an access token before it expires (RFC 6750, section 3.1). The timer cuts down the 401s, and the retry handles the rest.
Where GenClass fits
GenClass has no check built for token refresh races. On your development build, its coding-agent link records each click, each request and the order the responses were delivered, and the GenClass MCP server gives that sequence to your coding agent. The server's genclass_analytics tool lists request counts per endpoint and the number of page loads they came from, so a refresh endpoint called three times per load shows up there.
While your agent or a test repeats your steps, genclass_explore delivers the responses in seeded orders, and slower with slow_ms, and reports a race when what the page shows differs from the runs where responses came back in request order. A double refresh that happens in every order is not a difference, so explore does not report it, and a clean report covers only the steps it ran. If your app lists the refresh endpoint in requests.protect (the auth preset matches paths with words such as auth, token and session), explore records that request and never holds its response, unless the page connects with holdProtected: true. In CI, the chaos option of @genclass/playwright holds matched requests for a seeded time before they leave, unchanged (add your refresh path to its match list), so a test that counts refresh calls gets the same delays for the same seed. Your own assertion decides whether it passes (testing race conditions with Playwright).
To try it, follow the setup in the MCP server docs.
Questions
Why is my refresh token endpoint called multiple times?
Every request that gets a 401 starts its own refresh, so a page that loads three things right after the token expires makes three calls. Keep one refresh promise and have the other requests wait for it.
Why do users get logged out at random?
Often two refreshes went out with the same refresh token. Under rotation the server treats the second as reuse of a replaced token and revokes the session, which only happens when two requests fail at nearly the same moment.
How do I stop two tabs from refreshing at once?
Run the refresh inside a Web Lock, which every tab of the origin shares, and post the new access token on a BroadcastChannel so the other tabs can use it.
Is an isRefreshing flag with a request queue enough?
It works if every path resets the flag and rejects the queued requests when the refresh fails. A shared promise does the same job in less code, because the promise is the queue.
Related: stale responses that arrive out of order, race conditions in Angular and the race condition simulator.