SSR and prefetching
Prefetching fills the cache before a component asks for the data, so the first render already has it. This page covers doing that on a server: which helper to call, how the data reaches the browser, and how to make server-side requests carry the current user's credentials.
The hydration mechanics are TanStack's and are not repeated here; see its SSR guide for the framework setup.
Prefetch, dehydrate, hydrate
Create a QueryClient for the request, fill it with the query's own helpers, and hand the dehydrated state to the client. The example is a Next.js server component; the three steps are the same in any framework.
The same query objects run on both sides. Only the QueryClient differs.
The server and the client must pass the same arguments, because the arguments are the cache key. prefetch(queryClient) on the server and use({ params: { page: 1 } }) in the browser are two entries, and the second one fetches again. See the key shape.
Set a staleTime on the browser's QueryClient, or hydrated data counts as stale and is refetched on mount.
Choosing a helper
A failed prefetch is silent on the server. The component then fetches in the browser and reports the failure through its hook or error boundary.
Use fetch when the server should answer differently:
ensure suits client-side route loaders, where a cached value should win over a request:
On an infinite query the three helpers load the first page.
A client per request
A builder has one HTTP client, shared by every call. On a server that is the wrong scope: each incoming request has its own cookies or token. setHttpClient binds an HTTP client to a QueryClient, and every query, infinite query and mutation that runs through that QueryClient uses it instead of the builder's.
Since a server creates one QueryClient per request, the binding isolates requests without any global state. A QueryClient without a binding, such as the one in the browser, keeps using the builder's client.
setHttpClient(queryClient, client)binds;setHttpClient(queryClient, null)removes the binding.getHttpClient(queryClient)returns the bound client, orundefined.
The bound client is any object that satisfies Builder's HTTP client contract.
What can be dehydrated
Query data must survive serialization to cross from server to browser. JSON responses do. So does a withResponse: true entry, because its headers are stored as a plain record. A Blob or a stream does not, so prefetch those in the browser instead.
Related: Cache helpers, Keys and invalidation.