Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

ssr.md

561 lines24.7 KB

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