Open History to see the last commit
1---
2id: ssr
3title: Server Rendering & Hydration
4---
5β
6In this guide you'll learn how to use React Query with server rendering.
7β
8See 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.
9β
10For 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).
11β
12If you just want to see some code, you can skip ahead to the [Full Next.js pages router example](#full-nextjs-pages-router-example) or the [Full Remix example](#full-remix-example) below.
13β
14## Server Rendering & React Query
15β
16So 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).
17β
18If you've read the Request Waterfalls guide, you might remember this:
19β
20```
211. |-> Markup (without content)
222. |-> JS
233. |-> Query
24```
25β
26With 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:
27β
28```
291. |-> Markup (with content AND initial data)
302. |-> JS
31```
32β
33As 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.
34β
35This is all from the clients 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.
36β
37Read on to learn how to implement these three steps with React Query.
38β
39## A quick note on Suspense
40β
41This 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.
42β
43If 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.
44β
45## Initial setup
46β
47The first steps of using React Query is 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.
48β
49Next.js pages router:
50β
51```tsx
52// _app.tsx
53import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
54β
55// NEVER DO THIS:
56// const queryClient = new QueryClient()
57//
58// Creating the queryClient at the file root level makes the cache shared
59// between all requests and means _all_ data gets passed to _all_ users.
60// Besides being bad for performance, this also leaks any sensitive data.
61β
62export default function MyApp({ Component, pageProps }) {
63 // Instead do this, which ensures each request has its own cache:
64 const [queryClient] = React.useState(
65 () =>
66 new QueryClient({
67 defaultOptions: {
68 queries: {
69 // With SSR, we usually want to set some default staleTime
70 // above 0 to avoid refetching immediately on the client
71 staleTime: 60 * 1000,
72 },
73 },
74 }),
75 )
76β
77 return (
78 <QueryClientProvider client={queryClient}>
79 <Component {...pageProps} />
80 </QueryClientProvider>
81 )
82}
83```
84β
85Remix:
86β
87```tsx
88// app/root.tsx
89import { Outlet } from '@remix-run/react'
90import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
91β
92export default function MyApp() {
93 const [queryClient] = React.useState(
94 () =>
95 new QueryClient({
96 defaultOptions: {
97 queries: {
98 // With SSR, we usually want to set some default staleTime
99 // above 0 to avoid refetching immediately on the client
100 staleTime: 60 * 1000,
101 },
102 },
103 }),
104 )
105β
106 return (
107 <QueryClientProvider client={queryClient}>
108 <Outlet />
109 </QueryClientProvider>
110 )
111}
112```
113β
114## Get started fast with `initialData`
115β
116The 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`.
117β
118```tsx
119export async function getServerSideProps() {
120 const posts = await getPosts()
121 return { props: { posts } }
122}
123β
124function Posts(props) {
125 const { data } = useQuery({
126 queryKey: ['posts'],
127 queryFn: getPosts,
128 initialData: props.posts,
129 })
130β
131 // ...
132}
133```
134β
135This 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:
136β
137```tsx
138export async function loader() {
139 const posts = await getPosts()
140 return json({ posts })
141}
142β
143function Posts() {
144 const { posts } = useLoaderData<typeof loader>()
145β
146 const { data } = useQuery({
147 queryKey: ['posts'],
148 queryFn: getPosts,
149 initialData: posts,
150 })
151β
152 // ...
153}
154```
155β
156The 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:
157β
158- If you are calling `useQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
159- 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 since. 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 needs it can also be cumbersome.
160- 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
161- 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**.
162 - 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.
163β
164Setting up the full hydration solution is straightforward and does not have these drawbacks, this will be the focus for the rest of the documentation.
165β
166## Using the Hydration APIs
167β
168With 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:
169β
170- In the framework loader function, create a `const queryClient = new QueryClient(options)`
171- In the loader function, do `await queryClient.prefetchQuery(...)` for each query you want to prefetch
172 - You want to use `await Promise.all(...)` to fetch the queries in parallel when possible
173 - It's fine to have queries that aren't prefetched. These wont be server rendered, instead they will be fetched on the client after the application is interactive. This can be great for content that are shown only after user interaction, or is far down on the page to avoid blocking more critical content.
174- From the loader, return `dehydrate(queryClient)`, note that the exact syntax to return this differs between frameworks
175- Wrap your tree with `<HydrationBoundary state={dehydratedState}>` where `dehydratedState` comes from the framework loader. How you get `dehydratedState` also differs between frameworks.
176 - This can be done for each route, or at the top of the application to avoid boilerplate, see examples
177β
178> 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.
179β
180> 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).
181β
182### Full Next.js pages router example
183β
184> For app router documentation, see the [Advanced Server Rendering guide](./advanced-ssr.md).
185β
186Initial setup:
187β
188```tsx
189// _app.tsx
190import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
191β
192export default function MyApp({ Component, pageProps }) {
193 const [queryClient] = React.useState(
194 () =>
195 new QueryClient({
196 defaultOptions: {
197 queries: {
198 // With SSR, we usually want to set some default staleTime
199 // above 0 to avoid refetching immediately on the client
200 staleTime: 60 * 1000,
201 },
202 },
203 }),
204 )
205β
206 return (
207 <QueryClientProvider client={queryClient}>
208 <Component {...pageProps} />
209 </QueryClientProvider>
210 )
211}
212```
213β
214In each route:
215β
216```tsx
217// pages/posts.tsx
218import {
219 dehydrate,
220 HydrationBoundary,
221 QueryClient,
222 useQuery,
223} from '@tanstack/react-query'
224β
225// This could also be getServerSideProps
226export async function getStaticProps() {
227 const queryClient = new QueryClient()
228β
229 await queryClient.prefetchQuery({
230 queryKey: ['posts'],
231 queryFn: getPosts,
232 })
233β
234 return {
235 props: {
236 dehydratedState: dehydrate(queryClient),
237 },
238 }
239}
240β
241function Posts() {
242 // This useQuery could just as well happen in some deeper child to
243 // the <PostsRoute>, data will be available immediately either way
244 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
245β
246 // This query was not prefetched on the server and will not start
247 // fetching until on the client, both patterns are fine to mix
248 const { data: commentsData } = useQuery({
249 queryKey: ['posts-comments'],
250 queryFn: getComments,
251 })
252β
253 // ...
254}
255β
256export default function PostsRoute({ dehydratedState }) {
257 return (
258 <HydrationBoundary state={dehydratedState}>
259 <Posts />
260 </HydrationBoundary>
261 )
262}
263```
264β
265### Full Remix example
266β
267Initial setup:
268β
269```tsx
270// app/root.tsx
271import { Outlet } from '@remix-run/react'
272import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
273β
274export default function MyApp() {
275 const [queryClient] = React.useState(
276 () =>
277 new QueryClient({
278 defaultOptions: {
279 queries: {
280 // With SSR, we usually want to set some default staleTime
281 // above 0 to avoid refetching immediately on the client
282 staleTime: 60 * 1000,
283 },
284 },
285 }),
286 )
287β
288 return (
289 <QueryClientProvider client={queryClient}>
290 <Outlet />
291 </QueryClientProvider>
292 )
293}
294```
295β
296In each route, note that it's fine to do this in nested routes too:
297β
298```tsx
299// app/routes/posts.tsx
300import { json } from '@remix-run/node'
301import {
302 dehydrate,
303 HydrationBoundary,
304 QueryClient,
305 useQuery,
306} from '@tanstack/react-query'
307β
308export async function loader() {
309 const queryClient = new QueryClient()
310β
311 await queryClient.prefetchQuery({
312 queryKey: ['posts'],
313 queryFn: getPosts,
314 })
315β
316 return json({ dehydratedState: dehydrate(queryClient) })
317}
318β
319function Posts() {
320 // This useQuery could just as well happen in some deeper child to
321 // the <PostsRoute>, data will be available immediately either way
322 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
323β
324 // This query was not prefetched on the server and will not start
325 // fetching until on the client, both patterns are fine to mix
326 const { data: commentsData } = useQuery({
327 queryKey: ['posts-comments'],
328 queryFn: getComments,
329 })
330β
331 // ...
332}
333β
334export default function PostsRoute() {
335 const { dehydratedState } = useLoaderData<typeof loader>()
336 return (
337 <HydrationBoundary state={dehydratedState}>
338 <Posts />
339 </HydrationBoundary>
340 )
341}
342```
343β
344## Optional - Remove boilerplate
345β
346Having this part in every route might seem like a lot of boilerplate:
347β
348```tsx
349export default function PostsRoute({ dehydratedState }) {
350 return (
351 <HydrationBoundary state={dehydratedState}>
352 <Posts />
353 </HydrationBoundary>
354 )
355}
356```
357β
358While 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:
359β
360```tsx
361// _app.tsx
362import {
363 HydrationBoundary,
364 QueryClient,
365 QueryClientProvider,
366} from '@tanstack/react-query'
367β
368export default function MyApp({ Component, pageProps }) {
369 const [queryClient] = React.useState(() => new QueryClient())
370β
371 return (
372 <QueryClientProvider client={queryClient}>
373 <HydrationBoundary state={pageProps.dehydratedState}>
374 <Component {...pageProps} />
375 </HydrationBoundary>
376 </QueryClientProvider>
377 )
378}
379β
380// pages/posts.tsx
381// Remove PostsRoute with the HydrationBoundary and instead export Posts directly:
382export default function Posts() { ... }
383```
384β
385With 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.
386β
387## Prefetching dependent queries
388β
389Over 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):
390β
391```tsx
392// Get the user
393const { data: user } = useQuery({
394 queryKey: ['user', email],
395 queryFn: getUserByEmail,
396})
397β
398const userId = user?.id
399β
400// Then get the user's projects
401const {
402 status,
403 fetchStatus,
404 data: projects,
405} = useQuery({
406 queryKey: ['projects', userId],
407 queryFn: getProjectsByUser,
408 // The query will not execute until the userId exists
409 enabled: !!userId,
410})
411```
412β
413How would we prefetch this so it can be server rendered? Here's an example:
414β
415```tsx
416// For Remix, rename this to loader instead
417export async function getServerSideProps() {
418 const queryClient = new QueryClient()
419β
420 const user = await queryClient.fetchQuery({
421 queryKey: ['user', email],
422 queryFn: getUserByEmail,
423 })
424β
425 if (user?.userId) {
426 await queryClient.prefetchQuery({
427 queryKey: ['projects', userId],
428 queryFn: getProjectsByUser,
429 })
430 }
431β
432 // For Remix:
433 // return json({ dehydratedState: dehydrate(queryClient) })
434 return { props: { dehydratedState: dehydrate(queryClient) } }
435}
436```
437β
438This 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.
439β
440## Error handling
441β
442React Query defaults to a graceful degradation strategy. This means:
443β
444- `queryClient.prefetchQuery(...)` never throws errors
445- `dehydrate(...)` only includes successful queries, not failed ones
446β
447This 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.
448β
449While 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 `queryClient.fetchQuery(...)` instead, which will throw errors when it fails, letting you handle things in a suitable way.
450β
451```tsx
452let result
453β
454try {
455 result = await queryClient.fetchQuery(...)
456} catch (error) {
457 // Handle the error, refer to your framework documentation
458}
459β
460// You might also want to check and handle any invalid `result` here
461```
462β
463If 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:
464β
465```tsx
466dehydrate(queryClient, {
467 shouldDehydrateQuery: (query) => {
468 // This will include all queries, including failed ones,
469 // but you can also implement your own logic by inspecting `query`
470 return true
471 },
472})
473```
474β
475## Serialization
476β
477When 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.
478β
479By default, these frameworks only supports returning things that are safely serializable/parsable, and therefore does 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.
480β
481If 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.
482β
483## A note about request waterfalls
484β
485In 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#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 fetches their own data. With client rendering, this leads to the following request waterfall:
486β
487```
4881. |> Markup (without content)
4892. |> JS for <Feed>
4903. |> getFeed()
4914. |> JS for <GraphFeedItem>
4925. |> getGraphDataById()
493```
494β
495The nice thing about server rendering is that we can turn the above into:
496β
497```
4981. |> Markup (with content AND initial data)
4992. |> JS for <Feed>
5002. |> JS for <GraphFeedItem>
501```
502β
503Note 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:
504β
505```
5061. |> getFeed()
5072. |> getGraphDataById()
508```
509β
510We 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.
511β
512Amazing, 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 to this:
513β
514```
5151. |> JS for <Feed>
5162. |> getFeed()
5173. |> JS for <GraphFeedItem>
5184. |> getGraphDataById()
519```
520β
521This is because with SPA's, server rendering only works for the initial page load, not for any subsequent navigation.
522β
523Modern 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:
524β
525```
5261. |> JS for <Feed>
5271. |> getFeed() + getGraphDataById()
5282. |> JS for <GraphFeedItem>
529```
530β
531This 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).
532β
533## Tips, Tricks and Caveats
534β
535### Staleness is measured from when the query was fetched on the server
536β
537A 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.
538β
539Because `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.
540β
541This 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?
542β
543### High memory consumption on server
544β
545In 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.
546β
547On 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.
548β
549Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/hydration.md#hydrationboundary) 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.
550β
551To clear the cache after it is not needed and to lower memory consumption, you can add a call to [`queryClient.clear()`](../../../reference/QueryClient.md#queryclientclear) after the request is handled and dehydrated state has been sent to the client.
552β
553Alternatively, you can set a smaller `gcTime`.
554β
555### Caveat for Next.js rewrites
556β
557There'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`.
558β
559The 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.