Sub topic 17
Server rendering and hydration
This chapter covers how to render a TanStack Query screen on the server and hand the fetched data to the browser, so the client doesn't fetch it again. It assumes you know useQuery, query keys, and staleTime from earlier chapters. It also assumes you know what server-side rendering (SSR) is: React produces HTML on a server, and the browser then attaches event handlers to it. Examples use the Next.js App Router, but the same API works with any SSR setup.
The problem hydration solves
useQuery does not fetch data during a server render. Effects don't run on the server, so the query never starts. The server therefore sends HTML containing the loading state. The browser then loads JavaScript, hydrates, starts the fetch, and only afterwards shows the data. You pay for SSR and still get a loading spinner.
The fix has three steps:
- Fetch the data on the server, before rendering, into a
QueryClient. - Serialize the cache into plain JSON. This is called dehydrating.
- Load that JSON into the browser's
QueryClientbefore the components render. This is called hydrating.
With the cache already filled, useQuery returns data on its first render, on both the server and the client. The HTML matches what the client renders, and no request is made.
Share the query definition
The server and the client must use the same query key and the same query function. If they differ, the client looks up a different cache entry and fetches anyway. Define both once with queryOptions.
// todos.ts
import { queryOptions } from '@tanstack/react-query'
export type Todo = { id: number; title: string; done: boolean }
const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000'
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch(`${baseUrl}/api/todos`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export const todosQueryOptions = queryOptions({
queryKey: ['todos'],
queryFn: fetchTodos,
})Note the absolute URL. In a browser, fetch('/api/todos') resolves against the page address. On a server there is no page address, so a relative URL fails.
Create the client in the right place
In the browser, create the QueryClient once and keep it for the life of the page. In a client component, the safe way is useState with an initializer function. A module-level new QueryClient() would also be created on the server and shared between users.
// providers.tsx
'use client'
import { useState, type ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: { staleTime: 60 * 1000 },
},
}),
)
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}The staleTime default matters here, and the gotchas section below explains why.
Prefetch, dehydrate, and hydrate
On the server, build a fresh QueryClient for each request. Prefetch into it, call dehydrate, and pass the result to HydrationBoundary.
// app/page.tsx
import {
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { todosQueryOptions } from '../todos'
import { Todos } from './todos-list'
export default async function Page() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery(todosQueryOptions)
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Todos />
</HydrationBoundary>
)
}The component below is an ordinary client component. It has no special code for SSR.
// app/todos-list.tsx
'use client'
import { useQuery } from '@tanstack/react-query'
import { todosQueryOptions } from '../todos'
export function Todos() {
const { data, isPending, isError, error } = useQuery(todosQueryOptions)
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}On the first render isPending is false, because the cache entry already exists with status success. HydrationBoundary copies the dehydrated entries into the browser's QueryClient before its children render.
You can place several HydrationBoundary components in one tree, for example one per route segment. Each adds its queries to the same client. If an entry already exists in the browser cache and is newer than the incoming one, the newer entry is kept.
Why a client per request
A QueryClient holds a cache. If the server reuses one client across requests, user A's cached data can end up in user B's page. Create the server client inside the request handler or server component, as in Page above. Never hold it in a module-level variable.
The same rule has a second side. React may render a client component more than once while suspending. Creating the browser client with useState avoids throwing the cache away on a re-render.
Gotchas
Default staleTime of zero
With staleTime: 0, hydrated data is stale immediately. When the component mounts on the client, refetchOnMount sees stale data and fetches again. You then get the server data first and an immediate duplicate request. Set a positive default staleTime, as the Providers example does. Pick a value that matches how quickly the data stops being useful.
Serialization
Dehydrated state is sent as JSON inside the page. Query data must therefore survive JSON conversion. The following values will not:
| Value in query data | What happens after JSON | Suggested fix |
|---|---|---|
| `Date` object | Becomes an ISO string | Return strings from `queryFn` and convert in the component |
| `undefined` | Dropped, and v5 refuses to cache it | Return `null` instead |
| `Map` or `Set` | Becomes `{}` or is lost | Return arrays or plain objects |
| Class instance | Loses its methods | Return plain data, build the class later |
prefetchQuery hides errors
prefetchQuery never throws. If the API fails, the cache stays empty and the page renders without data. The client then fetches the data itself and shows its own error or retry behavior. This is usually the right fallback. If you want the server render to fail instead, use await queryClient.fetchQuery(todosQueryOptions), which throws.
Only successful queries are sent by default
dehydrate includes only queries with status success. A pending or failed query is not sent. If you want a promise still in flight to be streamed to the browser, that is a separate, newer feature that needs extra configuration. It is not needed for the basic pattern in this chapter.
Mismatched keys
If the server prefetches ['todos'] and the component asks for ['todos', { done: false }], there is no hit. Two prefetched entries with different parameters are separate caches. Build the keys from one shared helper, such as queryOptions, to avoid drift.
Choosing what to prefetch
Prefetching delays the server response, because the HTML waits for the API. Prefetch the data that is above the fold and needed for the first paint. Leave secondary data to normal client-side useQuery calls, which will show a loading state and load in later.
Checking your setup
- Disable JavaScript in the browser and load the page. The list should still appear in the HTML. If it doesn't, the data is not being rendered on the server.
- Enable JavaScript and reload with the Network tab open. No request to
/api/todosshould fire on initial load. - Open the Devtools and confirm the
['todos']entry has a recent "updated" time that matches the server render.
Exercise
A page prefetches ['todos'] on the server and wraps its content in HydrationBoundary. In the browser, the list renders without a loading state, but the Network tab shows a second request for /api/todos immediately after load. The QueryClient in Providers is created with new QueryClient() and no options. What is the cause, and what is the smallest change that fixes it?
Show answer
The default staleTime is 0, so the hydrated data counts as stale right away. When the component mounts, refetchOnMount triggers a background refetch. Setting a positive staleTime, for example new QueryClient({ defaultOptions: { queries: { staleTime: 60 * 1000 } } }), keeps the hydrated data fresh for that time and removes the duplicate request.
Exercise
Why must the server create a new QueryClient for each request, and why does the browser create its client with useState(() => new QueryClient()) instead of a module-level constant?
Show answer
A module-level client on the server is shared across all requests, so cached data from one user could be dehydrated into another user's page. In the browser, useState with an initializer keeps one stable client for the life of the component and avoids rebuilding the cache if React re-renders the provider.