· By John Kavanagh

Hydrating a Query Cache Without Sharing Another User's Data

Photograph of blue parcel lockers inside a station concourse.
Image by Clique Retire, licensed from Unsplash.

Two people open their order history. Each request has the right session cookie. The database query checks the right account. Somehow, both pages contain Alice's order.

There doesn't have to be anything wrong with authentication for this to happen. A query client created at module scope can outlive the request that populated it. The next request asks that client for ['orders'], and the client already has an answer. A very efficient answer, unfortunately addressed to the wrong person.

For a server‑rendered account page, I want to follow the private data through three places: the request's query cache, the props sent to the browser, and the browser's own cache after hydration. Getting the first one right does not make the other two harmless.

This example uses the Next.js Pages Router and TanStack Query v4. The API names below are those of v4.16.1.


Give Every Request Its Own Client

In my comparison of static generation and server‑side rendering, the starting point is whether the response depends on the request. An order‑history page clearly does. Its cache needs the same boundary.

Create the server query client inside getServerSideProps, after establishing the session, and keep it local to that request:

export async function getServerSideProps({ req, res }) {
  const user = await requireSession(req);
  const client = new QueryClient();

  res.setHeader('Cache-Control', 'private, no-store');

  await client.fetchQuery({
    queryKey: ['orders'],
    queryFn: () => readOrdersFor(user.id),
    staleTime: 60_000,
  });

  return {
    props: { dehydratedState: dehydrate(client) },
  };
}

requireSession and readOrdersFor represent application code. The server must establish the user from trusted authentication and authorise the read. A user identifier supplied in the URL is not a substitute.

The query key is deliberately the same for both users in this example. Separate clients make those separate caches. Including an account identifier in a key can help organise data within a browser session, but it does not make a shared server cache safe to dehydrate wholesale. Other users' queries could still be sitting in it.

A module‑level client is especially easy to miss in a helper named something reassuring like getQueryClient. I'd inspect where the object is created, rather than taking the helper's name as a character reference.


Make the Overlap Happen on Purpose

A sequential test can miss the most interesting part of this bug. Start Alice's query, keep it pending, then start Bob's request with the same key. A shared client can deduplicate the two reads by sharing the pending query. Only one account's loader runs, and both callers receive its result.

The companion exercise uses two synthetic sessions, different prices, and unmistakable private markers. Its read delay keeps the requests overlapping. The broken case uses a shared client; the corrected case constructs one per request. Both use identical query keys.

Check each response's HTML and serialised props. Alice's marker must be absent from Bob's response, and vice versa. Merely checking that each page has the right account name is insufficient: that name can come from the session whilst the order data comes from somebody else's cached result.

Keep the broken case as a negative control. If both implementations pass the isolation assertion, the test probably isn't forcing the situation it claims to cover. It is quite possible to write a reassuring test for a leaking cache.


Hydration is Another Transfer of Data

Dehydration turns successful query state into a representation we can send to the browser. It does not inspect every field and decide which ones the visitor ought to receive.

Select the fields needed by the page before putting records into the cache. An internal support note should never become part of the dehydrated payload just because the component happens not to display it. Inspecting the HTML source is enough to spoil that particular hiding place.

In the application wrapper, create a stable browser client and hydrate it using v4's Hydrate component:

const [client] = useState(() => new QueryClient());

return (
  <QueryClientProvider client={client}>
    <Hydrate state={pageProps.dehydratedState}>
      <Component {...pageProps} />
    </Hydrate>
  </QueryClientProvider>
);

That state initialiser avoids recreating the client on every render. During server rendering, each wrapper instance gets its own client too. Hoisting this object to module scope to "avoid unnecessary work" would reintroduce the problem at another level.

The v4 server‑rendering guide describes the full setup. Keep the server cache alive for as long as the rendering path needs it. An eager clear() is not an isolation strategy if it removes state before a dependent render has used it.


Decide When the Browser Should Ask Again

Hydrated data carries the time it was updated on the server. Freshness is measured from that point, not from when the browser finished loading the page. A slow response has already used some of the freshness window.

With staleTime: 0, the browser can refetch immediately on mounting the query. That may be exactly the policy you want. It may also explain the apparently mysterious second request in the network panel. A sixty‑second stale time avoids that immediate refetch for sufficiently recent data; it does not mean the data can never be invalidated.

The v4 query options keep cacheTime separate from this decision. In v4 it concerns removal of unused query data, rather than how long a result is considered fresh. Making it larger will not repair an unwanted immediate refetch.

Count requests with fixed settings and a fresh browser context. Test direct entry and a return visit through navigation. Check the server's clock as well: a timestamp unexpectedly in the future can make old data look fresh. These observations are more useful than assuming every repeated request is a hydration failure.


Failure and Account Changes Need Their Own Checks

The query‑client methods distinguish failure too: a failed prefetchQuery() does not reject in the same way as fetchQuery(). By default, failed queries are omitted from dehydration, so the browser may try again. That can be a reasonable fallback for optional content. For order history that the server must provide, I prefer fetchQuery() and an explicit response when it fails. Test that separately from query retry settings.

On an account change, stop displaying the previous account's private view, cancel outstanding queries, and discard its private cache before presenting the new account. The exercise replaces the provider for the new session. Clearing one visible result whilst retaining other private query entries would leave the job unfinished.

Finally, protect the HTTP response as well as the in‑process cache. My earlier Cache‑Control guide explains why private and shared caches have different rules. A request‑local query client cannot stop a misconfigured intermediary serving a cached account page to the next visitor.

My isolation lab puts those boundaries under separate checks. The useful outcome is straightforward: the right account's data, in the right response, surviving hydration without borrowing anything from the request next door.

Postscript

November 2026: Query v5 uses HydrationBoundary in place of Hydrate, and calls the unused‑query retention option gcTime rather than cacheTime. TanStack's migration guide also explains the changed timing when newer state hydrates an existing query. My download includes a current Next.js and Query v5 application, with the v4 excerpts kept separately. Request ownership still needs the same boundary; renaming the component does not create one.

Downloadable Resource

  • Next.js Query Cache Isolation Lab

    Force overlapping private requests, expose a shared query cache, and check isolated SSR payloads, hydration freshness, errors, and account changes.

    Download ZIP

Want to find out more?

If you need senior hands‑on support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.