The symptom#
Alice signs out and Bob signs in on the same tab. Bob opens the environments page and, for a moment, sees Alice's environments. Then the list flickers and shows his own. Nothing failed: no request returned the wrong rows, and the server authorized every read. The leak happens entirely in the browser's memory.
The same happens on an organization switcher that changes the active organization in a cookie or a header but leaves the query keys alone. Any key that does not name the account, such as ["environments"], is shared by every account that uses the tab.
Why the cache outlives the account#
Two defaults combine. First, a query that loses its last observer stays in the cache for gcTime, five minutes by default, so a page Alice left a minute ago still has her answer. Second, the default staleTime is zero, which means a new observer gets the cached data at once and refetches in the background. The caching guide walks through both. That stale-while-revalidate behavior is what makes pages feel instant, and it is the same behavior that hands Bob Alice's list.
The query keys guide says to put every variable the query function depends on into its key. The account is such a variable, but it usually lives in a cookie that the fetch sends implicitly, so it never appears in the code that builds the key.
The lab#
The lab needs Node.js and @tanstack/query-core, and runs in a second. It uses the framework-free core so the output shows the cache directly.
mkdir switch-lab && cd switch-lab && npm init -y >/dev/null
npm install @tanstack/query-core
// switch.mjs
import { QueryClient, QueryObserver } from "@tanstack/query-core";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let account = "alice";
const server = { alice: ["alice-prod", "alice-staging"], bob: ["bob-prod"] };
const options = {
queryKey: ["environments"], // the key does not name the account
queryFn: async () => {
const asked = account;
await sleep(20);
return server[asked];
},
};
async function scenario(name, onSwitch) {
account = "alice";
const client = new QueryClient();
const page = new QueryObserver(client, options);
const stop = page.subscribe(() => {});
await sleep(50); // alice's list is cached
stop(); // alice leaves the page
account = "bob"; // switch accounts without a reload
await onSwitch(client);
const next = new QueryObserver(client, options); // bob opens the page
const first = next.getOptimisticResult(next.options);
console.log(`${name}: bob's first render status=${first.status} data=${JSON.stringify(first.data ?? null)}`);
}
await scenario("nothing ", async () => {});
await scenario("invalidate ", (c) => c.invalidateQueries());
await scenario("clear ", async (c) => c.clear());
With @tanstack/query-core 5.108 on Node.js 24, node switch.mjs prints:
nothing : bob's first render status=success data=["alice-prod","alice-staging"]
invalidate : bob's first render status=success data=["alice-prod","alice-staging"]
clear : bob's first render status=pending data=null
Invalidation changed nothing that Bob sees on his first render. It marked the query stale, which it already was. Only clear() removed the entry, so Bob's page starts in pending and shows its loading state until his own answer arrives.
A second run of the lab started Alice's request, switched to Bob five milliseconds later and called clear() before her answer came back. Her answer reached neither the cache nor the observer that had asked for it: the cache held zero queries afterwards. Clearing removes each query and cancels its fetch, so a late answer for the old account has nowhere to land.
Choose the call#
The QueryClient reference lists the candidates. They differ in what the next render sees:
invalidateQueries()marks queries stale and refetches the active ones. Cached data stays visible until each refetch answers. Use it when the data changed, not when the reader changed.resetQueries()returns queries to their initial state and refetches the active ones. It does not touch the mutation cache.clear()empties the query cache and the mutation cache. A mutation's variables can hold the previous account's form input, so the mutation cache matters too.
clear() has one consequence to plan for. Components that stay mounted across the switch, such as a header with an organization picker, keep observing queries that no longer exist. In the lab, the mounted observer was left with no data and no refetch. Remount the signed-in part of the tree when the account changes, for example by giving its root a key built from the account's stable ID, or load the page again. A full page load also drops route state and pending callbacks that the cache does not own.
Putting the account ID into every query key is the other fix. It separates the entries, but it depends on every key in the app remembering to include it, and the previous account's data still sits in memory until gcTime removes it. Use it in addition to a clear, not in place of one.
Decide when the account changed#
Clearing on every HTTP 401 looks like the simple rule, and it breaks something else. Many apps answer 401 to a sensitive action, such as enrolling an authenticator, when the session is valid but the sign-in is older than the action allows. Clearing the cache on that 401 sends every mounted page back to its loading state, and a form loses what the person typed.
Ask the identity endpoint instead, and act on its answer:
- Signed out: clear the cache and show sign-in.
- A different user: clear the cache and remount or reload before rendering their routes.
- The same user: keep the cache, and show the re-authentication prompt the action needs.
If nothing on the page observes the identity, there is no answer to wait for, so clear at once. Compare users by a stable ID from the identity provider, not by login or display name, which can change or be reused.
The stale cache guide covers the related server-side question: finding the write that skips a cache's invalidation.
Where this came from#
Proofline found this in an audit of its own console, where one signed-in user's cached reads could stay visible to the next user of the same tab, and shipped the fix in its production release of 1 December 2026. Before the change, three account-boundary tests failed on the base. After it, two users at the same address in Chromium each saw only their own environment list. The first version cleared the cache on every 401, and two browser tests for a recent-sign-in action failed because the page went back to loading and lost its typed values. The shipped version asks the identity first and clears only for a signed-out answer or a different user. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms
Questions#
Does invalidateQueries() remove cached data?
No. It marks matching queries stale and refetches the active ones. Until each refetch answers, observers keep receiving the cached data.
Is a 401 enough to clear the cache?
Not on its own when the app uses 401 for recent sign-in checks. Ask the identity endpoint, and clear only when it answers signed out or names a different user.
Do I also need to clear mutations?
Usually yes. Mutation state can hold the variables of the last submitted form. queryClient.clear() empties both caches in one call.