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](../guides/prefetching) for some background. You might also want to check out the [Performance & Request Waterfalls guide](../guides/request-waterfalls) 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](../guides/advanced-ssr).
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 avoid 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 it's 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 it's 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](../guides/advanced-ssr).
181β
182### Full Next.js pages router example
183β
184> For app router documentation, see the [Advanced Server Rendering guide](../guides/advanced-ssr).
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.jsx
218import { dehydrate, HydrationBoundary, QueryClient, useQuery } from '@tanstack/react-query'
219β
220// This could also be getServerSideProps
221export async function getStaticProps() {
222 const queryClient = new QueryClient()
223β
224 await queryClient.prefetchQuery({
225 queryKey: ['posts'],
226 queryFn: getPosts,
227 })
228β
229 return {
230 props: {
231 dehydratedState: dehydrate(queryClient),
232 },
233 }
234}
235β
236function Posts() {
237 // This useQuery could just as well happen in some deeper child to
238 // the <PostsRoute>, data will be available immediately either way
239 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
240β
241 // This query was not prefetched on the server and will not start
242 // fetching until on the client, both patterns are fine to mix
243 const { data: commentsData } = useQuery({
244 queryKey: ['posts-comments'],
245 queryFn: getComments,
246 })
247β
248 // ...
249}
250β
251export default PostsRoute({ dehydratedState }) {
252 return (
253 <HydrationBoundary state={dehydratedState}>
254 <Posts />
255 </HydrationBoundary>
256 )
257}
258```
259β
260### Full Remix example
261β
262Initial setup:
263β
264```tsx
265// app/root.tsx
266import { Outlet } from '@remix-run/react'
267import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
268β
269export default function MyApp() {
270 const [queryClient] = React.useState(
271 () =>
272 new QueryClient({
273 defaultOptions: {
274 queries: {
275 // With SSR, we usually want to set some default staleTime
276 // above 0 to avoid refetching immediately on the client
277 staleTime: 60 * 1000,
278 },
279 },
280 }),
281 )
282β
283 return (
284 <QueryClientProvider client={queryClient}>
285 <Outlet />
286 </QueryClientProvider>
287 )
288}
289```
290β
291In each route, note that it's fine to do this in nested routes too:
292β
293```tsx
294// app/routes/posts.tsx
295import { json } from '@remix-run/node'
296import {
297 dehydrate,
298 HydrationBoundary,
299 QueryClient,
300 useQuery,
301} from '@tanstack/react-query'
302β
303export async function loader() {
304 const queryClient = new QueryClient()
305β
306 await queryClient.prefetchQuery({
307 queryKey: ['posts'],
308 queryFn: getPosts,
309 })
310β
311 return json({ dehydratedState: dehydrate(queryClient) })
312}
313β
314function Posts() {
315 // This useQuery could just as well happen in some deeper child to
316 // the <PostsRoute>, data will be available immediately either way
317 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
318β
319 // This query was not prefetched on the server and will not start
320 // fetching until on the client, both patterns are fine to mix
321 const { data: commentsData } = useQuery({
322 queryKey: ['posts-comments'],
323 queryFn: getComments,
324 })
325β
326 // ...
327}
328β
329export default PostsRoute() {
330 const { dehydratedState } = useLoaderData<typeof loader>();
331 return (
332 <HydrationBoundary state={dehydratedState}>
333 <Posts />
334 </HydrationBoundary>
335 )
336}
337```
338β
339## Optional - Remove boilerplate
340β
341Having this part in every route might seem like a lot of boilerplate:
342β
343```tsx
344export default PostsRoute({ dehydratedState }) {
345 return (
346 <HydrationBoundary state={dehydratedState}>
347 <Posts />
348 </HydrationBoundary>
349 )
350}
351```
352β
353While 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:
354β
355```tsx
356// _app.tsx
357import {
358 HydrationBoundary,
359 QueryClient,
360 QueryClientProvider,
361} from '@tanstack/react-query'
362β
363export default function MyApp({ Component, pageProps }) {
364 const [queryClient] = React.useState(() => new QueryClient())
365β
366 return (
367 <QueryClientProvider client={queryClient}>
368 <HydrationBoundary state={pageProps.dehydratedState}>
369 <Component {...pageProps} />
370 </HydrationBoundary>
371 </QueryClientProvider>
372 )
373}
374β
375// pages/posts.tsx
376// Remove PostsRoute with the HydrationBoundary and instead export Posts directly:
377export default function Posts() { ... }
378```
379β
380With 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.
381β
382## Prefetching dependent queries
383β
384Over in the Prefetching guide we learned how to [prefetch dependent queries](../guides/prefetching#dependent-queries--code-splitting), but how do we do this in framework loaders? Consider the following code, taken from the [Dependent Queries guide](../guides/dependent-queries):
385β
386```tsx
387// Get the user
388const { data: user } = useQuery({
389 queryKey: ['user', email],
390 queryFn: getUserByEmail,
391})
392β
393const userId = user?.id
394β
395// Then get the user's projects
396const {
397 status,
398 fetchStatus,
399 data: projects,
400} = useQuery({
401 queryKey: ['projects', userId],
402 queryFn: getProjectsByUser,
403 // The query will not execute until the userId exists
404 enabled: !!userId,
405})
406```
407β
408How would we prefetch this so it can be server rendered? Here's an example:
409β
410```tsx
411// For Remix, rename this to loader instead
412export async function getServerSideProps() {
413 const queryClient = new QueryClient()
414β
415 const user = await queryClient.fetchQuery({
416 queryKey: ['user', email],
417 queryFn: getUserByEmail,
418 })
419β
420 if (user?.userId) {
421 await queryClient.prefetchQuery({
422 queryKey: ['projects', userId],
423 queryFn: getProjectsByUser,
424 })
425 }
426β
427 // For Remix:
428 // return json({ dehydratedState: dehydrate(queryClient) })
429 return { props: { dehydratedState: dehydrate(queryClient) } }
430}
431```
432β
433This 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.
434β
435## Error handling
436β
437React Query defaults to a graceful degradation strategy. This means:
438β
439- `queryClient.prefetchQuery(...)` never throws errors
440- `dehydrate(...)` only includes successful queries, not failed ones
441β
442This 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.
443β
444While 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.
445β
446```tsx
447let result
448β
449try {
450 result = await queryClient.fetchQuery(...)
451} catch (error) {
452 // Handle the error, refer to your framework documentation
453}
454β
455// You might also want to check and handle any invalid `result` here
456```
457β
458If 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:
459β
460```tsx
461dehydrate(queryClient, {
462 shouldDehydrateQuery: (query) => {
463 // This will include all queries, including failed ones,
464 // but you can also implement your own logic by inspecting `query`
465 return true
466 },
467})
468```
469β
470## Serialization
471β
472When 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.
473β
474By default, these frameworks only supports returning things that are safely serializable/parsable, and therefor 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.
475β
476If 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.
477β
478## A note about request waterfalls
479β
480In the [Performance & Request Waterfalls guide](../guides/request-waterfalls) we mentioned we would revisit how server rendering changes one of the more complex nested waterfalls. Check back for the [specific code example](../guides/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:
481β
482```
4831. |> Markup (without content)
4842. |> JS for <Feed>
4853. |> getFeed()
4864. |> JS for <GraphFeedItem>
4875. |> getGraphDataById()
488```
489β
490The nice thing about server rendering is that we can turn the above into:
491β
492```
4931. |> Markup (with content AND initial data)
4942. |> JS for <Feed>
4952. |> JS for <GraphFeedItem>
496```
497β
498Note 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:
499β
500```
5011. |> getFeed()
5022. |> getGraphDataById()
503```
504β
505We 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.
506β
507Amazing, 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:
508β
509```
5101. |> JS for <Feed>
5112. |> getFeed()
5123. |> JS for <GraphFeedItem>
5134. |> getGraphDataById()
514```
515β
516This is because with SPA's, server rendering only works for the initial page load, not for any subsequent navigation.
517β
518Modern frameworks often tries 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:
519β
520```
5211. |> JS for <Feed>
5221. |> getFeed() + getGraphDataById()
5232. |> JS for <GraphFeedItem>
524```
525β
526This 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](../guides/advanced-ssr).
527β
528## Tips, Tricks and Caveats
529β
530### Staleness is measured from when the query was fetched on the server
531β
532A 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.
533β
534Because `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.
535β
536This 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?
537β
538### High memory consumption on server
539β
540In 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.
541β
542On 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.
543β
544Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/hydration#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.
545β
546To clear the cache after it is not needed and to lower memory consumption, you can add a call to [`queryClient.clear()`](../reference/QueryClient#queryclientclear) after the request is handled and dehydrated state has been sent to the client.
547β
548Alternatively, you can set a smaller `gcTime`.
549β
550### Caveat for Next.js rewrites
551β
552There's a catch if you're using [Next.js' rewrites feature](https://nextjs.org/docs/api-reference/next.config.js/rewrites) together with [Automatic Static Optimization](https://nextjs.org/docs/advanced-features/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/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`.
553β
554The 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.