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

ssr.md

537 lines22.5 KB

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 } }
34​
35function Posts(props) {
36 const { data } = useQuery({
37 queryKey: ['posts'],
38 queryFn: getPosts,
39 initialData: props.posts,
40 })
41​
42 // ...
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 )
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 }
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 // ...
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 })
138​
139function Posts() {
140 const { posts } = useLoaderData()
141​
142 const { data } = useQuery({
143 queryKey: ['posts'],
144 queryFn: getPosts,
145 initialData: posts,
146 })
147​
148 // ...
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 )
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) })
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 // ...
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()
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'),
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.
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 )
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 )
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} />
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 // ...
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 )
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 // ...
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()
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`.