Open History to see the last commit
1---
2id: ssr
3title: SSR
4---
5β
6React Query supports two ways of prefetching data on the server and passing that to the queryClient.
7β
8- Prefetch the data yourself and pass it in as `initialData`
9 - Quick to set up for simple cases
10 - Has some caveats
11- Prefetch the query on the server, dehydrate the cache and rehydrate it on the client
12 - Requires slightly more setup up front
13β
14## Using Next.js
15β
16The exact implementation of these mechanisms may vary from platform to platform, but we recommend starting with Next.js which supports [2 forms of pre-rendering](https://nextjs.org/docs/basic-features/data-fetching):
17β
18- Static Generation (SSG)
19- Server-side Rendering (SSR)
20β
21React Query supports both of these forms of pre-rendering regardless of what platform you may be using.
22β
23> Note: For notes about how to integrate with the new beta `/app`-folder in Next.js, see further down in this guide.
24β
25### Using `initialData`
26β
27Together with Next.js's [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) or [`getServerSideProps`](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering), you can pass the data you fetch in either method to `useQuery`'s' `initialData` option. From React Query's perspective, these integrate in the same way, `getStaticProps` is shown below:
28β
29```tsx
30export async function getStaticProps() {
31 const posts = await getPosts()
32 return { props: { posts } }
33}
34β
35function Posts(props) {
36 const { data } = useQuery({
37 queryKey: ['posts'],
38 queryFn: getPosts,
39 initialData: props.posts,
40 })
41β
42 // ...
43}
44```
45β
46The 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:
47β
48- If you are calling `useQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
49- If you are calling `useQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
50- 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
51β
52### Using Hydration
53β
54React Query supports prefetching multiple queries on the server in Next.js and then _dehydrating_ those queries to the queryClient. This means the server can prerender markup that is immediately available on page load and as soon as JS is available, React Query can upgrade or _hydrate_ those queries with the full functionality of the library. This includes refetching those queries on the client if they have become stale since the time they were rendered on the server.
55β
56To support caching queries on the server and set up hydration:
57β
58- Create a new `QueryClient` instance **inside of your app, and on an instance ref (or in React state). This ensures that data is not shared between different users and requests, while still only creating the QueryClient once per component lifecycle.**
59- Wrap your app component with `<QueryClientProvider>` and pass it the client instance
60- Wrap your app component with `<HydrationBoundary>` and pass it the `dehydratedState` prop from `pageProps`
61β
62```tsx
63// _app.jsx
64import { HydrationBoundary, QueryClient, QueryClientProvider } from '@tanstack/react-query'
65β
66export default function MyApp({ Component, pageProps }) {
67 const [queryClient] = React.useState(() => new QueryClient())
68β
69 return (
70 <QueryClientProvider client={queryClient}>
71 <HydrationBoundary state={pageProps.dehydratedState}>
72 <Component {...pageProps} />
73 </HydrationBoundary>
74 </QueryClientProvider>
75 )
76}
77```
78β
79Now you are ready to prefetch some data in your pages with either [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) (for SSG) or [`getServerSideProps`](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) (for SSR). From React Query's perspective, these integrate in the same way, `getStaticProps` is shown below.
80β
81- Create a new `QueryClient` instance **for each page request. This ensures that data is not shared between users and requests.**
82- Prefetch the data using the clients `prefetchQuery` method and wait for it to complete
83- Use `dehydrate` to dehydrate the query cache and pass it to the page via the `dehydratedState` prop. This is the same prop that the cache will be picked up from in your `_app.js`
84β
85```tsx
86// pages/posts.jsx
87import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'
88β
89export async function getStaticProps() {
90 const queryClient = new QueryClient()
91β
92 await queryClient.prefetchQuery(['posts'], getPosts)
93β
94 return {
95 props: {
96 dehydratedState: dehydrate(queryClient),
97 },
98 }
99}
100β
101function Posts() {
102 // This useQuery could just as well happen in some deeper child to
103 // the "Posts"-page, data will be available immediately either way
104 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
105β
106 // This query was not prefetched on the server and will not start
107 // fetching until on the client, both patterns are fine to mix
108 const { data: otherData } = useQuery({
109 queryKey: ['posts-2'],
110 queryFn: getPosts,
111 })
112β
113 // ...
114}
115```
116β
117As demonstrated, it's fine to prefetch some queries and let others fetch on the queryClient. This means you can control what content server renders or not by adding or removing `prefetchQuery` for a specific query.
118β
119### Caveat for Next.js rewrites
120β
121There'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`.
122β
123The 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.
124β
125## Using Remix
126β
127Remix supports Server-side Rendering (SSR) only.
128β
129### Using `initialData`
130β
131Together with Remix's [`loader`](https://remix.run/docs/en/v1/api/conventions#loader), you can pass the data you fetch to `useQuery`'s' `initialData` option.
132β
133```tsx
134export async function loader() {
135 const posts = await getPosts()
136 return json({ posts })
137}
138β
139function Posts() {
140 const { posts } = useLoaderData()
141β
142 const { data } = useQuery({
143 queryKey: ['posts'],
144 queryFn: getPosts,
145 initialData: posts,
146 })
147β
148 // ...
149}
150```
151β
152The 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:
153β
154- If you are calling `useQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
155- 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
156β
157### Using Hydration
158β
159React Query supports prefetching multiple queries on the server in Remix and then _dehydrating_ those queries to the queryClient. This means the server can prerender markup that is immediately available on page load and as soon as JS is available, React Query can upgrade or _hydrate_ those queries with the full functionality of the library. This includes refetching those queries on the client if they have become stale since the time they were rendered on the server.
160β
161To support caching queries on the server and set up hydration:
162β
163- Create a new `QueryClient` instance **inside of your app, and on an instance ref (or in React state). This ensures that data is not shared between different users and requests, while still only creating the QueryClient once per component lifecycle.**
164- Wrap your app component with `<QueryClientProvider>` and pass it the client instance
165- Wrap your app component with `<HydrationBoundary>` and pass it the `dehydratedState` prop from `useDehydratedState()`
166β
167```bash
168npm i use-dehydrated-state
169# or
170pnpm add use-dehydrated-state
171# or
172yarn add use-dehydrated-state
173```
174β
175```tsx
176// root.tsx
177import { HydrationBoundary, QueryClient, QueryClientProvider } from '@tanstack/react-query'
178β
179import { useDehydratedState } from 'use-dehydrated-state'
180β
181export default function MyApp() {
182 const [queryClient] = React.useState(() => new QueryClient())
183β
184 const dehydratedState = useDehydratedState()
185β
186 return (
187 <QueryClientProvider client={queryClient}>
188 <HydrationBoundary state={dehydratedState}>
189 <Outlet />
190 </HydrationBoundary>
191 </QueryClientProvider>
192 )
193}
194```
195β
196Now you are ready to prefetch some data in your [`loader`](https://remix.run/docs/en/v1/api/conventions#loader).
197β
198- Create a new `QueryClient` instance **for each page request. This ensures that data is not shared between users and requests.**
199- Prefetch the data using the clients `prefetchQuery` method and wait for it to complete
200- Use `dehydrate` to dehydrate the query cache and pass it to the page via the `dehydratedState` prop. This is the same prop that `useDehydratedState()` will pick up for caching in your `root.tsx`
201β
202```tsx
203// pages/posts.tsx
204import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'
205β
206export async function loader() {
207 const queryClient = new QueryClient()
208β
209 await queryClient.prefetchQuery(['posts'], getPosts)
210β
211 return json({ dehydratedState: dehydrate(queryClient) })
212}
213β
214function Posts() {
215 // This useQuery could just as well happen in some deeper child to
216 // the "Posts"-page, data will be available immediately either way
217 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
218β
219 // This query was not prefetched on the server and will not start
220 // fetching until on the client, both patterns are fine to mix
221 const { data: otherData } = useQuery({
222 queryKey: ['posts-2'],
223 queryFn: getPosts,
224 })
225β
226 // ...
227}
228```
229β
230As demonstrated, it's fine to prefetch some queries and let others fetch on the queryClient. This means you can control what content server renders or not by adding or removing `prefetchQuery` for a specific query.
231β
232## Using Other Frameworks or Custom SSR Frameworks
233β
234This guide is at-best, a high level overview of how SSR with React Query should work. Your mileage may vary since there are many different possible setups for SSR.
235β
236> If you can, please contribute your findings back to this page for any framework specific guidance!
237β
238### On the Server
239β
240- Create a new `QueryClient` instance **inside of your request handler. This ensures that data is not shared between different users and requests.**
241- Using the client, prefetch any data you need
242- Dehydrate the client
243- Render your app with the client provider and also **using the dehydrated state. This is extremely important! You must render both server and client using the same dehydrated state to ensure hydration on the client produces the exact same markup as the server.**
244- Serialize and embed the dehydrated cache to be sent to the client with the HTML
245- Clear the React Query caches after the dehydrated state has been sent by calling [`queryClient.clear()`](../reference/QueryClient#queryclientclear)
246β
247> SECURITY NOTE: Serializing data with `JSON.stringify` can put you at risk for XSS-vulnerabilities, [this blog post explains why and how to solve it](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0)
248β
249```tsx
250import { dehydrate, HydrationBoundary, QueryClient, QueryClientProvider } from '@tanstack/react-query';
251β
252async function handleRequest(req, res) {
253 const queryClient = new QueryClient()
254 await queryClient.prefetchQuery(['key'], fn)
255 const dehydratedState = dehydrate(queryClient)
256β
257 const html = ReactDOM.renderToString(
258 <QueryClientProvider client={queryClient}>
259 <HydrationBoundary state={dehydratedState}>
260 <App />
261 </HydrationBoundary>
262 </QueryClientProvider>
263 )
264β
265 res.send(`
266 <html>
267 <body>
268 <div id="root">${html}</div>
269 <script>
270 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
271 </script>
272 </body>
273 </html>
274 `)
275β
276 queryClient.clear()
277}
278```
279β
280### Client
281β
282- Parse the dehydrated cache state that was sent to the client with the HTML
283- Create a new `QueryClient` instance
284- Render your app with the client provider and also **using the dehydrated state. This is extremely important! You must render both server and client using the same dehydrated state to ensure hydration on the client produces the exact same markup as the server.**
285β
286```tsx
287import { HydrationBoundary, QueryClient, QueryClientProvider } from '@tanstack/react-query'
288β
289const dehydratedState = window.__REACT_QUERY_STATE__
290β
291const queryClient = new QueryClient()
292β
293ReactDOM.hydrate(
294 <QueryClientProvider client={queryClient}>
295 <HydrationBoundary state={dehydratedState}>
296 <App />
297 </HydrationBoundary>
298 </QueryClientProvider>,
299 document.getElementById('root'),
300)
301```
302β
303## Using Experimental `app` Directory in Next.js 13
304β
305> **WARNING:** The `app` directory introduced in Next.js 13 is currently in beta, and it is not recommended for use in production. The API is not stable.
306>
307> This guide is provided as is to supply a quick start for early exploration of Next.js 13's experimental features and does not represent the final APIs.
308β
309Both prefetching approaches, using `initialData` or `<Hydrate>`, are available within the `app` directory.
310β
311- Prefetch the data in a Server Component and prop drill `initialData` to Client Components
312 - Quick to set up for simple cases
313 - May need to prop drill through multiple layers of Client Components
314 - May need to prop drill to multiple Client Components using the same query
315 - Query refetching is based on when the page loads instead of when the data was prefetched on the server
316- Prefetch the query on the server, dehydrate the cache and rehydrate it on the client with `<Hydrate>`
317 - Requires slightly more setup up front
318 - No need to prop drill
319 - Query refetching is based on when the query was prefetched on the server
320β
321### `<QueryClientProvider>` is required by both the `initialData` and `<Hydrate>` prefetching approaches
322β
323The hooks provided by the `react-query` package need to retrieve a `QueryClient` from their context. Wrap your component tree with `<QueryClientProvider>` and pass it an instance of `QueryClient`.
324β
325```tsx
326// app/providers.jsx
327'use client'
328β
329import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
330β
331export default function Providers({ children }) {
332 const [queryClient] = React.useState(() => new QueryClient())
333β
334 return (
335 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
336 )
337}
338```
339β
340```tsx
341// app/layout.jsx
342import Providers from './providers'
343β
344export default function RootLayout({ children }) {
345 return (
346 <html lang="en">
347 <head />
348 <body>
349 <Providers>{children}</Providers>
350 </body>
351 </html>
352 )
353}
354```
355β
356### Using `initialData`
357β
358Fetch your initial data in a Server Component higher up in the component tree, and pass it to your Client Component as a prop.
359β
360```tsx
361// app/page.jsx
362export default async function Home() {
363 const initialData = await getPosts()
364β
365 return <Posts posts={initialData} />
366}
367```
368β
369```tsx
370// app/posts.jsx
371'use client'
372β
373import { useQuery } from '@tanstack/react-query'
374β
375export function Posts(props) {
376 const { data } = useQuery({
377 queryKey: ['posts'],
378 queryFn: getPosts,
379 initialData: props.posts,
380 })
381β
382 // ...
383}
384```
385β
386### Using `<Hydrate>`
387β
388Create a request-scoped singleton instance of `QueryClient`. **This ensures that data is not shared between different users and requests, while still only creating the QueryClient once per request.**
389β
390```tsx
391// app/getQueryClient.jsx
392import { QueryClient } from '@tanstack/react-query'
393import { cache } from 'react'
394β
395const getQueryClient = cache(() => new QueryClient())
396export default getQueryClient
397```
398β
399Fetch your data in a Server Component higher up in the component tree than the Client Components that use the prefetched queries. Your prefetched queries will be available to all components deeper down the component tree.
400β
401- Retrieve the `QueryClient` singleton instance
402- Prefetch the data using the client's prefetchQuery method and wait for it to complete
403- Use `dehydrate` to obtain the dehydrated state of the prefetched queries from the query cache
404- Wrap the component tree that needs the prefetched queries inside `<Hydrate>`, and provide it with the dehydrated state
405- You can fetch inside multiple Server Components and use `<Hydrate>` in multiple places
406β
407> NOTE: TypeScript currently complains of a type error when using async Server Components. As a temporary workaround, use `{/* @ts-expect-error Server Component */}` when calling this component inside another. For more information, see [End-to-End Type Safety](https://beta.nextjs.org/docs/configuring/typescript#end-to-end-type-safety) in the Next.js 13 beta docs.
408β
409```tsx
410// app/hydratedPosts.jsx
411import { dehydrate, Hydrate } from '@tanstack/react-query'
412import getQueryClient from './getQueryClient'
413β
414export default async function HydratedPosts() {
415 const queryClient = getQueryClient()
416 await queryClient.prefetchQuery(['posts'], getPosts)
417 const dehydratedState = dehydrate(queryClient)
418β
419 return (
420 <Hydrate state={dehydratedState}>
421 <Posts />
422 </Hydrate>
423 )
424}
425```
426β
427During server rendering, calls to `useQuery` nested within the `<Hydrate>` Client Component will have access to prefetched data provided in the state property.
428β
429```tsx
430// app/posts.jsx
431'use client'
432β
433import { useQuery } from '@tanstack/react-query'
434β
435export default function Posts() {
436 // This useQuery could just as well happen in some deeper child to
437 // the "HydratedPosts"-component, data will be available immediately either way
438 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
439β
440 // This query was not prefetched on the server and will not start
441 // fetching until on the client, both patterns are fine to mix
442 const { data: otherData } = useQuery({
443 queryKey: ['posts-2'],
444 queryFn: getPosts,
445 })
446β
447 // ...
448}
449```
450β
451As demonstrated, it's fine to prefetch some queries and let others fetch on the client. This means you can control what content server renders or not by adding or removing `prefetchQuery` for a specific query.
452β
453### Streaming, Suspense and server-side fetching
454β
455Right now, you always have to `await` the data in the Server Component. In the future, the goal is to be able to _start_ prefetching in a Server Component but not block rendering, instead streaming markup and data to the client incrementally as it gets available. This is currently lacking support in both React and Query.
456β
457Similarily, you _must_ currently prefetch the data in a Server Component if you want it to be server rendered. A `useQuery()` call even with the `suspense` option enabled will not fetch data on the server, only on the client. We hope to support this in the future, but exact details are still unknown.
458β
459## Custom SSR with suspense
460β
461If you do not want to provide `prefetchQuery()` for all your queries in the SSR you can use suspense.
462β
463### Server
464β
465```tsx
466import {
467 dehydrate,
468 QueryClient,
469 QueryClientProvider,
470} from '@tanstack/react-query'
471import ssrPrepass from 'react-ssr-prepass'
472β
473async function handleRequest(req, res) {
474 const queryClient = new QueryClient()
475β
476 // React SSR does not support ErrorBoundary
477 try {
478 // Traverse the tree and fetch all Suspense data (thrown promises)
479 await ssrPrepass(<App />)
480 } catch (e) {
481 console.error(e)
482 // Send the index.html (without SSR) on error, so user can try to recover and see something
483 return res.sendFile('path/to/dist/index.html')
484 }
485β
486 const html = ReactDOM.renderToString(
487 <QueryClientProvider client={queryClient}>
488 <App />
489 </QueryClientProvider>,
490 )
491β
492 const dehydratedState = dehydrate(queryClient)
493β
494 res.send(`
495 <html>
496 <body>
497 <div id="root">${html}</div>
498 <script>
499 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
500 </script>
501 </body>
502 </html>
503 `)
504β
505 queryClient.clear()
506}
507```
508β
509### Client
510β
511Make sure to [use suspense in your queries](../guides/suspense).
512β
513## Tips, Tricks and Caveats
514β
515### Only successful queries are included in dehydration
516β
517Any query with an error is automatically excluded from dehydration. This means that the default behavior is to pretend these queries were never loaded on the server, usually showing a loading state instead, and retrying the queries on the queryClient. This happens regardless of error.
518β
519Sometimes this behavior is not desirable, maybe you want to render an error page with a correct status code instead on certain errors or queries. In those cases, use `fetchQuery` and catch any errors to handle those manually.
520β
521### Staleness is measured from when the query was fetched on the server
522β
523A 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.
524β
525Because `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.
526β
527This 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?
528β
529### High memory consumption on server
530β
531In 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.
532β
533On 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.
534β
535To 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.
536β
537Alternatively, you can set a smaller `gcTime`.