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 `/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 the `app` Directory in Next.js 13
304β
305Both prefetching approaches, using `initialData` or `<HydrationBoundary>`, are available within the `app` directory.
306β
307- Prefetch the data in a Server Component and prop drill `initialData` to Client Components
308 - Quick to set up for simple cases
309 - May need to prop drill through multiple layers of Client Components
310 - May need to prop drill to multiple Client Components using the same query
311 - Query refetching is based on when the page loads instead of when the data was prefetched on the server
312- Prefetch the query on the server, dehydrate the cache and rehydrate it on the client with `<HydrationBoundary>`
313 - Requires slightly more setup up front
314 - No need to prop drill
315 - Query refetching is based on when the query was prefetched on the server
316β
317### `<QueryClientProvider>` is required by both the `initialData` and `<HydrationBoundary>` prefetching approaches
318β
319The 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`.
320β
321```tsx
322// app/providers.jsx
323'use client'
324β
325import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
326β
327export default function Providers({ children }) {
328 const [queryClient] = React.useState(() => new QueryClient())
329β
330 return (
331 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
332 )
333}
334```
335β
336```tsx
337// app/layout.jsx
338import Providers from './providers'
339β
340export default function RootLayout({ children }) {
341 return (
342 <html lang="en">
343 <head />
344 <body>
345 <Providers>{children}</Providers>
346 </body>
347 </html>
348 )
349}
350```
351β
352### Using `initialData`
353β
354Fetch your initial data in a Server Component higher up in the component tree, and pass it to your Client Component as a prop.
355β
356```tsx
357// app/page.jsx
358export default async function Home() {
359 const initialData = await getPosts()
360β
361 return <Posts posts={initialData} />
362}
363```
364β
365```tsx
366// app/posts.jsx
367'use client'
368β
369import { useQuery } from '@tanstack/react-query'
370β
371export function Posts(props) {
372 const { data } = useQuery({
373 queryKey: ['posts'],
374 queryFn: getPosts,
375 initialData: props.posts,
376 })
377β
378 // ...
379}
380```
381β
382### Using `<HydrationBoundary>`
383β
384Create 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.**
385β
386```tsx
387// app/getQueryClient.jsx
388import { QueryClient } from '@tanstack/react-query'
389import { cache } from 'react'
390β
391const getQueryClient = cache(() => new QueryClient())
392export default getQueryClient
393```
394β
395Fetch 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.
396β
397- Retrieve the `QueryClient` singleton instance
398- Prefetch the data using the client's prefetchQuery method and wait for it to complete
399- Use `dehydrate` to obtain the dehydrated state of the prefetched queries from the query cache
400- Wrap the component tree that needs the prefetched queries inside `<HydrationBoundary>`, and provide it with the dehydrated state
401- You can fetch inside multiple Server Components and use `<HydrationBoundary>` in multiple places
402β
403> 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.
404β
405```tsx
406// app/hydratedPosts.jsx
407import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
408import getQueryClient from './getQueryClient'
409β
410export default async function HydratedPosts() {
411 const queryClient = getQueryClient()
413 await queryClient.prefetchQuery({querykey:['posts'], queryFn:getPosts})
414 // for infinite queries with useInfiniteQuery use
415 // await queryClient.prefetchInfiniteQuery({queryKey:['posts'], queryFn:getPosts,...})
416 const dehydratedState = dehydrate(queryClient)
417β
418 return (
419 <HydrationBoundary state={dehydratedState}>
420 <Posts />
421 </HydrationBoundary>
422 )
423}
424```
425β
426During server rendering, calls to `useQuery` nested within the `<HydrationBoundary>` Client Component will have access to prefetched data provided in the state property.
427β
428```tsx
429// app/posts.jsx
430'use client'
431β
432import { useQuery } from '@tanstack/react-query'
433β
434export default function Posts() {
435 // This useQuery could just as well happen in some deeper child to
436 // the "HydratedPosts"-component, data will be available immediately either way
437 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
438β
439 // This query was not prefetched on the server and will not start
440 // fetching until on the client, both patterns are fine to mix
441 const { data: otherData } = useQuery({
442 queryKey: ['posts-2'],
443 queryFn: getPosts,
444 })
445β
446 // ...
447}
448```
449β
450As 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.
451β
452### Streaming, Suspense and server-side fetching
453β
454Right 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.
455β
456Similarily, 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.
457β
458## Custom SSR with suspense
459β
460If you do not want to provide `prefetchQuery()` for all your queries in the SSR you can use suspense.
461β
462### Server
463β
464```tsx
465import {
466 dehydrate,
467 QueryClient,
468 QueryClientProvider,
469} from '@tanstack/react-query'
470import ssrPrepass from 'react-ssr-prepass'
471β
472async function handleRequest(req, res) {
473 const queryClient = new QueryClient()
474β
475 // React SSR does not support ErrorBoundary
476 try {
477 // Traverse the tree and fetch all Suspense data (thrown promises)
478 await ssrPrepass(<App />)
479 } catch (e) {
480 console.error(e)
481 // Send the index.html (without SSR) on error, so user can try to recover and see something
482 return res.sendFile('path/to/dist/index.html')
483 }
484β
485 const html = ReactDOM.renderToString(
486 <QueryClientProvider client={queryClient}>
487 <App />
488 </QueryClientProvider>,
489 )
490β
491 const dehydratedState = dehydrate(queryClient)
492β
493 res.send(`
494 <html>
495 <body>
496 <div id="root">${html}</div>
497 <script>
498 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
499 </script>
500 </body>
501 </html>
502 `)
503β
504 queryClient.clear()
505}
506```
507β
508### Client
509β
510Make sure to [use suspense in your queries](../guides/suspense).
511β
512## Tips, Tricks and Caveats
513β
514### Only successful queries are included in dehydration
515β
516Any 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.
517β
518Sometimes 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.
519β
520### Staleness is measured from when the query was fetched on the server
521β
522A 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.
523β
524Because `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.
525β
526This 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?
527β
528### High memory consumption on server
529β
530In 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.
531β
532On 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.
533β
534To 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.
535β
536Alternatively, you can set a smaller `gcTime`.