Open History to see the last commit
1---
2id: ssr
3title: Server Rendering & Hydration
4redirect_from:
5 - framework/react/reference/hydration
6---
7β
8In this guide you'll learn how to use React Query with server rendering.
9β
10For TanStack Start, use the [Start + TanStack Query guide](https://tanstack.com/start/latest/docs/framework/react/guide/tanstack-query) for its SSR integration, request-scoped QueryClient setup, and mutation invalidation example.
11β
12See the guide on [Prefetching & Router Integration](./prefetching.md) for some background. You might also want to check out the [Performance & Request Waterfalls guide](./request-waterfalls.md) before that.
13β
14For deeper examples on hydration + prefetching (including code splitting), see the [Dependent Queries & Code Splitting](./prefetching.md#dependent-queries-code-splitting) section.
15β
16For advanced server rendering patterns, such as streaming, Server Components and the new Next.js app router, see the [Advanced Server Rendering guide](./advanced-ssr.md).
17β
18If you just want to see some code, you can skip ahead to the [Full Next.js pages router example](#full-next-js-pages-router-example) or the [Full Remix example](#full-remix-example) below.
19β
20## Server Rendering & React Query
21β
22So what is server rendering anyway? The rest of this guide will assume you are familiar with the concept, but let's spend some time to look at how it relates to React Query. Server rendering is the act of generating the initial html on the server, so that the user has some content to look at as soon as the page loads. This can happen on demand when a page is requested (SSR). It can also happen ahead of time either because a previous request was cached, or at build time (SSG).
23β
24If you've read the [Performance & Request Waterfalls guide](./request-waterfalls.md), you might remember this:
25β
26```
271. |-> Markup (without content)
282. |-> JS
293. |-> Query
30```
31β
32With a client rendered application, these are the minimum 3 server roundtrips you will need to make before getting any content on the screen for the user. One way of viewing server rendering is that it turns the above into this:
33β
34```
351. |-> Markup (with content AND initial data)
362. |-> JS
37```
38β
39As soon as **1.** is complete, the user can see the content and when **2.** finishes, the page is interactive and clickable. Because the markup also contains the initial data we need, step **3.** does not need to run on the client at all, at least until you want to revalidate the data for some reason.
40β
41This is all from the client's perspective. On the server, we need to **prefetch** that data before we generate/render the markup, we need to **dehydrate** that data into a serializable format we can embed in the markup, and on the client we need to **hydrate** that data into a React Query cache so we can avoid doing a new fetch on the client.
42β
43Read on to learn how to implement these three steps with React Query.
44β
45## A quick note on Suspense
46β
47This guide uses the regular `useQuery` API. While we don't necessarily recommend it, it is possible to replace this with `useSuspenseQuery` instead **as long as you always prefetch all your queries**. The upside is that you get to use `<Suspense>` for loading states on the client.
48β
49If you do forget to prefetch a query when you are using `useSuspenseQuery`, the consequences will depend on the framework you are using. In some cases, the data will Suspend and get fetched on the server but never be hydrated to the client, where it will fetch again. In these cases you will get a markup hydration mismatch, because the server and the client tried to render different things.
50β
51## Initial setup
52β
53The first steps of using React Query are always to create a `queryClient` and wrap the application in a `<QueryClientProvider>`. When doing server rendering, it's important to create the `queryClient` instance **inside of your app**, in React state (an instance ref works fine too). **This ensures that data is not shared between different users and requests**, while still only creating the `queryClient` once per component lifecycle.
54β
55Next.js pages router:
56β
57```tsx
58// _app.tsx
59import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
60β
61// NEVER DO THIS:
62// const queryClient = new QueryClient()
63//
64// Creating the queryClient at the file root level makes the cache shared
65// between all requests and means _all_ data gets passed to _all_ users.
66// Besides being bad for performance, this also leaks any sensitive data.
67β
68export default function MyApp({ Component, pageProps }) {
69 // Instead do this, which ensures each request has its own cache:
70 const [queryClient] = React.useState(
71 () =>
72 new QueryClient({
73 defaultOptions: {
74 queries: {
75 // With SSR, we usually want to set some default staleTime
76 // above 0 to avoid refetching immediately on the client
77 staleTime: 60 * 1000,
78 },
79 },
80 }),
81 )
82β
83 return (
84 <QueryClientProvider client={queryClient}>
85 <Component {...pageProps} />
86 </QueryClientProvider>
87 )
88}
89```
90β
91Remix:
92β
93```tsx
94// app/root.tsx
95import { Outlet } from '@remix-run/react'
96import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
97β
98export default function MyApp() {
99 const [queryClient] = React.useState(
100 () =>
101 new QueryClient({
102 defaultOptions: {
103 queries: {
104 // With SSR, we usually want to set some default staleTime
105 // above 0 to avoid refetching immediately on the client
106 staleTime: 60 * 1000,
107 },
108 },
109 }),
110 )
111β
112 return (
113 <QueryClientProvider client={queryClient}>
114 <Outlet />
115 </QueryClientProvider>
116 )
117}
118```
119β
120## Get started fast with `initialData`
121β
122The quickest way to get started is to not involve React Query at all when it comes to prefetching and not use the `dehydrate`/`hydrate` APIs. What you do instead is passing the raw data in as the `initialData` option to `useQuery`. Let's look at an example using Next.js pages router, using `getServerSideProps`.
123β
124```tsx
125export async function getServerSideProps() {
126 const posts = await getPosts()
127 return { props: { posts } }
128}
129β
130function Posts(props) {
131 const { data } = useQuery({
132 queryKey: ['posts'],
133 queryFn: getPosts,
134 initialData: props.posts,
135 })
136β
137 // ...
138}
139```
140β
141This also works with `getStaticProps` or even the older `getInitialProps` and the same pattern can be applied in any other framework that has equivalent functions. This is what the same example looks like with Remix:
142β
143```tsx
144export async function loader() {
145 const posts = await getPosts()
146 return json({ posts })
147}
148β
149function Posts() {
150 const { posts } = useLoaderData<typeof loader>()
151β
152 const { data } = useQuery({
153 queryKey: ['posts'],
154 queryFn: getPosts,
155 initialData: posts,
156 })
157β
158 // ...
159}
160```
161β
162The setup is minimal and this can be a quick solution for some cases, but there are a **few tradeoffs to consider** when compared to the full approach:
163β
164- If you are calling `useQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
165- If you are calling `useQuery` with the same query in multiple locations, passing `initialData` to only one of them can be brittle and break when your app changes. If you remove or move the component that has the `useQuery` with `initialData`, the more deeply nested `useQuery` might no longer have any data. Passing `initialData` to **all** queries that need it can also be cumbersome.
166- There is no way to know at what time the query was fetched on the server, so `dataUpdatedAt` and determining if the query needs refetching is based on when the page loaded instead
167- If there is already data in the cache for a query, `initialData` will never overwrite this data, **even if the new data is fresher than the old one**.
168 - To understand why this is especially bad, consider the `getServerSideProps` example above. If you navigate back and forth to a page several times, `getServerSideProps` would get called each time and fetch new data, but because we are using the `initialData` option, the client cache and data would never be updated.
169β
170Setting up the full hydration solution is straightforward and does not have these drawbacks, this will be the focus for the rest of the documentation.
171β
172## Using the Hydration APIs
173β
174With just a little more setup, you can use a `queryClient` to prefetch queries during a preload phase, pass a serialized version of that `queryClient` to the rendering part of the app and reuse it there. This avoids the drawbacks above. Feel free to skip ahead for full Next.js pages router and Remix examples, but at a general level these are the extra steps:
175β
176- In the framework loader function, create a `const queryClient = new QueryClient(options)`
177- In the loader function, do `await queryClient.query(...)` for each query you want to prefetch
178 - You want to use `await Promise.all(...)` to fetch the queries in parallel when possible
179 - It's fine to have queries that aren't prefetched. These won't be server rendered, instead they will be fetched on the client after the application is interactive. This can be great for content that is shown only after user interaction, or is far down on the page to avoid blocking more critical content.
180- From the loader, return `dehydrate(queryClient)`, note that the exact syntax to return this differs between frameworks
181- Wrap your tree with `<HydrationBoundary state={dehydratedState}>` where `dehydratedState` comes from the framework loader. How you get `dehydratedState` also differs between frameworks.
182 - This can be done for each route, or at the top of the application to avoid boilerplate, see examples
183β
184> An interesting detail is that there are actually _three_ `queryClient`s involved. The framework loaders are a form of "preloading" phase that happens before rendering, and this phase has its own `queryClient` that does the prefetching. The dehydrated result of this phase gets passed to **both** the server rendering process **and** the client rendering process which each has its own `queryClient`. This ensures they both start with the same data so they can return the same markup.
185β
186> Server Components are another form of "preloading" phase, that can also "preload" (pre-render) parts of a React component tree. Read more in the [Advanced Server Rendering guide](./advanced-ssr.md).
187β
188### Full Next.js pages router example
189β
190> For app router documentation, see the [Advanced Server Rendering guide](./advanced-ssr.md).
191β
192Initial setup:
193β
194```tsx
195// _app.tsx
196import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
197β
198export default function MyApp({ Component, pageProps }) {
199 const [queryClient] = React.useState(
200 () =>
201 new QueryClient({
202 defaultOptions: {
203 queries: {
204 // With SSR, we usually want to set some default staleTime
205 // above 0 to avoid refetching immediately on the client
206 staleTime: 60 * 1000,
207 },
208 },
209 }),
210 )
211β
212 return (
213 <QueryClientProvider client={queryClient}>
214 <Component {...pageProps} />
215 </QueryClientProvider>
216 )
217}
218```
219β
220In each route:
221β
222```tsx
223// pages/posts.tsx
224import {
225 dehydrate,
226 HydrationBoundary,
227 noop,
228 QueryClient,
229 useQuery,
230} from '@tanstack/react-query'
231β
232// This could also be getServerSideProps
233export async function getStaticProps() {
234 const queryClient = new QueryClient()
235β
236 await queryClient
237 .query({
238 queryKey: ['posts'],
239 queryFn: getPosts,
240 })
241 .catch(noop)
242β
243 return {
244 props: {
245 dehydratedState: dehydrate(queryClient),
246 },
247 }
248}
249β
250function Posts() {
251 // This useQuery could just as well happen in some deeper child to
252 // the <PostsRoute>, data will be available immediately either way
253 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
254β
255 // This query was not prefetched on the server and will not start
256 // fetching until on the client, both patterns are fine to mix
257 const { data: commentsData } = useQuery({
258 queryKey: ['posts-comments'],
259 queryFn: getComments,
260 })
261β
262 // ...
263}
264β
265export default function PostsRoute({ dehydratedState }) {
266 return (
267 <HydrationBoundary state={dehydratedState}>
268 <Posts />
269 </HydrationBoundary>
270 )
271}
272```
273β
274### Full Remix example
275β
276Initial setup:
277β
278```tsx
279// app/root.tsx
280import { Outlet } from '@remix-run/react'
281import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
282β
283export default function MyApp() {
284 const [queryClient] = React.useState(
285 () =>
286 new QueryClient({
287 defaultOptions: {
288 queries: {
289 // With SSR, we usually want to set some default staleTime
290 // above 0 to avoid refetching immediately on the client
291 staleTime: 60 * 1000,
292 },
293 },
294 }),
295 )
296β
297 return (
298 <QueryClientProvider client={queryClient}>
299 <Outlet />
300 </QueryClientProvider>
301 )
302}
303```
304β
305In each route, note that it's fine to do this in nested routes too:
306β
307```tsx
308// app/routes/posts.tsx
309import { json } from '@remix-run/node'
310import {
311 dehydrate,
312 HydrationBoundary,
313 noop,
314 QueryClient,
315 useQuery,
316} from '@tanstack/react-query'
317β
318export async function loader() {
319 const queryClient = new QueryClient()
320β
321 await queryClient
322 .query({
323 queryKey: ['posts'],
324 queryFn: getPosts,
325 })
326 .catch(noop)
327β
328 return json({ dehydratedState: dehydrate(queryClient) })
329}
330β
331function Posts() {
332 // This useQuery could just as well happen in some deeper child to
333 // the <PostsRoute>, data will be available immediately either way
334 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
335β
336 // This query was not prefetched on the server and will not start
337 // fetching until on the client, both patterns are fine to mix
338 const { data: commentsData } = useQuery({
339 queryKey: ['posts-comments'],
340 queryFn: getComments,
341 })
342β
343 // ...
344}
345β
346export default function PostsRoute() {
347 const { dehydratedState } = useLoaderData<typeof loader>()
348 return (
349 <HydrationBoundary state={dehydratedState}>
350 <Posts />
351 </HydrationBoundary>
352 )
353}
354```
355β
356## Optional - Remove boilerplate
357β
358Having this part in every route might seem like a lot of boilerplate:
359β
360```tsx
361export default function PostsRoute({ dehydratedState }) {
362 return (
363 <HydrationBoundary state={dehydratedState}>
364 <Posts />
365 </HydrationBoundary>
366 )
367}
368```
369β
370While there is nothing wrong with this approach, if you want to get rid of this boilerplate, here's how you can modify your setup in Next.js:
371β
372```tsx
373// _app.tsx
374import {
375 HydrationBoundary,
376 QueryClient,
377 QueryClientProvider,
378} from '@tanstack/react-query'
379β
380export default function MyApp({ Component, pageProps }) {
381 const [queryClient] = React.useState(
382 () =>
383 new QueryClient({
384 defaultOptions: {
385 queries: {
386 // With SSR, we usually want to set some default staleTime
387 // above 0 to avoid refetching immediately on the client
388 staleTime: 60 * 1000,
389 },
390 },
391 }),
392 )
393β
394 return (
395 <QueryClientProvider client={queryClient}>
396 <HydrationBoundary state={pageProps.dehydratedState}>
397 <Component {...pageProps} />
398 </HydrationBoundary>
399 </QueryClientProvider>
400 )
401}
402β
403// pages/posts.tsx
404// Remove PostsRoute with the HydrationBoundary and instead export Posts directly:
405export default function Posts() { ... }
406```
407β
408With Remix, this is a little bit more involved, we recommend checking out the [use-dehydrated-state](https://github.com/maplegrove-io/use-dehydrated-state) package.
409β
410## Prefetching dependent queries
411β
412Over in the Prefetching guide we learned how to [prefetch dependent queries](./prefetching.md#dependent-queries-code-splitting), but how do we do this in framework loaders? Consider the following code, taken from the [Dependent Queries guide](./dependent-queries.md):
413β
414```tsx
415// Get the user
416const { data: user } = useQuery({
417 queryKey: ['user', email],
418 queryFn: getUserByEmail,
419})
420β
421const userId = user?.id
422β
423// Then get the user's projects
424const {
425 status,
426 fetchStatus,
427 data: projects,
428} = useQuery({
429 queryKey: ['projects', userId],
430 queryFn: getProjectsByUser,
431 // The query will not execute until the userId exists
432 enabled: !!userId,
433})
434```
435β
436How would we prefetch this so it can be server rendered? Here's an example:
437β
438```tsx
439// For Remix, rename this to loader instead
440export async function getServerSideProps() {
441 const queryClient = new QueryClient()
442β
443 const user = await queryClient.query({
444 queryKey: ['user', email],
445 queryFn: getUserByEmail,
446 })
447β
448 if (user?.id) {
449 await queryClient.query({
450 queryKey: ['projects', user.id],
451 queryFn: getProjectsByUser,
452 })
453 }
454β
455 // For Remix:
456 // return json({ dehydratedState: dehydrate(queryClient) })
457 return { props: { dehydratedState: dehydrate(queryClient) } }
458}
459```
460β
461This can get more complex of course, but since these loader functions are just JavaScript, you can use the full power of the language to build your logic. Make sure you prefetch all queries that you want to be server rendered.
462β
463## Error handling
464β
465React Query defaults to a graceful degradation strategy. This means:
466β
467- `dehydrate(...)` only includes successful queries, not failed ones
468- We can intentionally ignore the returned promise from `void queryClient.query(...)` and add `.catch(noop)` to swallow any errors, so surrounding loader code will not observe query errors
469β
470This will lead to any failed queries being retried on the client and that the server rendered output will include loading states instead of the full content.
471β
472While a good default, sometimes this is not what you want. When critical content is missing, you might want to respond with a 404 or 500 status code depending on the situation. For these cases, use `await queryClient.query(...)` without the noop catch, which will throw errors when it fails, letting you handle things in a suitable way.
473β
474```tsx
475let result
476β
477try {
478 result = await queryClient.query(...)
479} catch (error) {
480 // Handle the error, refer to your framework documentation
481}
482β
483// You might also want to check and handle any invalid `result` here
484```
485β
486If you for some reason want to include failed queries in the dehydrated state to avoid retries, you can use the option `shouldDehydrateQuery` to override the default function and implement your own logic:
487β
488```tsx
489dehydrate(queryClient, {
490 shouldDehydrateQuery: (query) => {
491 // This will include all queries, including failed ones,
492 // but you can also implement your own logic by inspecting `query`
493 return true
494 },
495})
496```
497β
498## Serialization
499β
500When doing `return { props: { dehydratedState: dehydrate(queryClient) } }` in Next.js, or `return json({ dehydratedState: dehydrate(queryClient) })` in Remix, what happens is that the `dehydratedState` representation of the `queryClient` is serialized by the framework so it can be embedded into the markup and transported to the client.
501β
502By default, these frameworks only support returning things that are safely serializable/parsable, and therefore do not support `undefined`, `Error`, `Date`, `Map`, `Set`, `BigInt`, `Infinity`, `NaN`, `-0`, regular expressions etc. This also means that you can not return any of these things from your queries. If returning these values is something you want, check out [superjson](https://github.com/blitz-js/superjson) or similar packages.
503β
504If you are using a custom SSR setup, you need to take care of this step yourself. Your first instinct might be to use `JSON.stringify(dehydratedState)`, but because this doesn't escape things like `<script>alert('Oh no..')</script>` by default, this can easily lead to **XSS-vulnerabilities** in your application. [superjson](https://github.com/blitz-js/superjson) also **does not** escape values and is unsafe to use by itself in a custom SSR setup (unless you add an extra step for escaping the output). Instead we recommend using a library like [Serialize JavaScript](https://github.com/yahoo/serialize-javascript) or [devalue](https://github.com/Rich-Harris/devalue) which are both safe against XSS injections out of the box.
505β
506## A note about request waterfalls
507β
508In the [Performance & Request Waterfalls guide](./request-waterfalls.md) we mentioned we would revisit how server rendering changes one of the more complex nested waterfalls. Check back for the [specific code example](./request-waterfalls.md#code-splitting), but as a refresher, we have a code split `<GraphFeedItem>` component inside a `<Feed>` component. This only renders if the feed contains a graph item and both of these components fetch their own data. With client rendering, this leads to the following request waterfall:
509β
510```
5111. |> Markup (without content)
5122. |> JS for <Feed>
5133. |> getFeed()
5144. |> JS for <GraphFeedItem>
5155. |> getGraphDataById()
516```
517β
518The nice thing about server rendering is that we can turn the above into:
519β
520```
5211. |> Markup (with content AND initial data)
5222. |> JS for <Feed>
5232. |> JS for <GraphFeedItem>
524```
525β
526Note that the queries are no longer fetched on the client, instead their data was included in the markup. The reason we can now load the JS in parallel is that since `<GraphFeedItem>` was rendered on the server we know that we are going to need this JS on the client as well and can insert a script-tag for this chunk in the markup. On the server, we would still have this request waterfall:
527β
528```
5291. |> getFeed()
5302. |> getGraphDataById()
531```
532β
533We simply can not know before we have fetched the feed if we also need to fetch graph data, they are dependent queries. Because this happens on the server where latency is generally both lower and more stable, this often isn't such a big deal.
534β
535Amazing, we've mostly flattened our waterfalls! There's a catch though. Let's call this page the `/feed` page, and let's pretend we also have another page like `/posts`. If we type in `www.example.com/feed` directly in the url bar and hit enter, we get all these great server rendering benefits, BUT, if we instead type in `www.example.com/posts` and then **click a link** to `/feed`, we're back to this:
536β
537```
5381. |> JS for <Feed>
5392. |> getFeed()
5403. |> JS for <GraphFeedItem>
5414. |> getGraphDataById()
542```
543β
544This is because with SPA's, server rendering only works for the initial page load, not for any subsequent navigation.
545β
546Modern frameworks often try to solve this by fetching the initial code and data in parallel, so if you were using Next.js or Remix with the prefetching patterns we outlined in this guide, including how to prefetch dependent queries, it would actually look like this instead:
547β
548```
5491. |> JS for <Feed>
5501. |> getFeed() + getGraphDataById()
5512. |> JS for <GraphFeedItem>
552```
553β
554This is much better, but if we want to improve this further we can flatten this to a single roundtrip with Server Components. Learn how in the [Advanced Server Rendering guide](./advanced-ssr.md).
555β
556## Tips, Tricks and Caveats
557β
558### Staleness is measured from when the query was fetched on the server
559β
560A query is considered stale depending on when it was `dataUpdatedAt`. A caveat here is that the server needs to have the correct time for this to work properly, but UTC time is used, so timezones do not factor into this.
561β
562Because `staleTime` defaults to `0`, queries will be refetched in the background on page load by default. You might want to use a higher `staleTime` to avoid this double fetching, especially if you don't cache your markup.
563β
564This refetching of stale queries is a perfect match when caching markup in a CDN! You can set the cache time of the page itself decently high to avoid having to re-render pages on the server, but configure the `staleTime` of the queries lower to make sure data is refetched in the background as soon as a user visits the page. Maybe you want to cache the pages for a week, but refetch the data automatically on page load if it's older than a day?
565β
566### High memory consumption on server
567β
568In case you are creating the `QueryClient` for every request, React Query creates the isolated cache for this client, which is preserved in memory for the `gcTime` period. That may lead to high memory consumption on server in case of high number of requests during that period.
569β
570On the server, `gcTime` defaults to `Infinity` which disables manual garbage collection and will automatically clear memory once a request has finished. If you are explicitly setting a non-Infinity `gcTime` then you will be responsible for clearing the cache early.
571β
572Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/functions/HydrationBoundary.md) places necessary data into the cache for rendering, but if the garbage collector removes the data before the rendering completes, issues may arise. If you require a shorter `gcTime`, we recommend setting it to `2 * 1000` to allow sufficient time for the app to reference the data.
573β
574To clear the cache after it is not needed and to lower memory consumption, you can add a call to [`queryClient.clear()`](../reference/classes/QueryClient.md#clear) after the request is handled and dehydrated state has been sent to the client.
575β
576Alternatively, you can set a smaller `gcTime`.
577β
578### Caveat for Next.js rewrites
579β
580There's a catch if you're using [Next.js' rewrites feature](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites) together with [Automatic Static Optimization](https://nextjs.org/docs/pages/building-your-application/rendering/automatic-static-optimization) or `getStaticProps`: It will cause a second hydration by React Query. That's because [Next.js needs to ensure that they parse the rewrites](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites#rewrite-parameters) on the client and collect any params after hydration so that they can be provided in `router.query`.
581β
582The result is missing referential equality for all the hydration data, which for example triggers wherever your data is used as props of components or in the dependency array of `useEffect`s/`useMemo`s.