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

ssr.md

554 lines22.4 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 `<Hydrate>` and pass it the `dehydratedState` prop from `pageProps`
61​
62```tsx
63// _app.jsx
64import {
65 Hydrate,
66 QueryClient,
67 QueryClientProvider,
68} from '@tanstack/react-query'
69​
70export default function MyApp({ Component, pageProps }) {
71 const [queryClient] = React.useState(() => new QueryClient())
72​
73 return (
74 <QueryClientProvider client={queryClient}>
75 <Hydrate state={pageProps.dehydratedState}>
76 <Component {...pageProps} />
77 </Hydrate>
78 </QueryClientProvider>
79 )
81```
82​
83Now 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.
84​
85- Create a new `QueryClient` instance **for each page request. This ensures that data is not shared between users and requests.**
86- Prefetch the data using the clients `prefetchQuery` method and wait for it to complete
87- 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`
88​
89```tsx
90// pages/posts.jsx
91import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'
92​
93export async function getStaticProps() {
94 const queryClient = new QueryClient()
95​
96 await queryClient.prefetchQuery(['posts'], getPosts)
97​
98 return {
99 props: {
100 dehydratedState: dehydrate(queryClient),
101 },
102 }
104​
105function Posts() {
106 // This useQuery could just as well happen in some deeper child to
107 // the "Posts"-page, data will be available immediately either way
108 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
109​
110 // This query was not prefetched on the server and will not start
111 // fetching until on the client, both patterns are fine to mix
112 const { data: otherData } = useQuery({
113 queryKey: ['posts-2'],
114 queryFn: getPosts,
115 })
116​
117 // ...
119```
120​
121As 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.
122​
123### Caveat for Next.js rewrites
124​
125There'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`.
126​
127The 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.
128​
129## Using Remix
130​
131Remix supports Server-side Rendering (SSR) only.
132​
133### Using `initialData`
134​
135Together 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.
136​
137```tsx
138export async function loader() {
139 const posts = await getPosts()
140 return json({ posts })
142​
143function Posts() {
144 const { posts } = useLoaderData()
145​
146 const { data } = useQuery({
147 queryKey: ['posts'],
148 queryFn: getPosts,
149 initialData: posts,
150 })
151​
152 // ...
154```
155​
156The setup is minimal and this can be a quick solution for some cases, but there are a **few tradeoffs to consider** when compared to the full approach:
157​
158- If you are calling `useQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
159- 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
160​
161### Using Hydration
162​
163React 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.
164​
165To support caching queries on the server and set up hydration:
166​
167- 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.**
168- Wrap your app component with `<QueryClientProvider>` and pass it the client instance
169- Wrap your app component with `<Hydrate>` and pass it the `dehydratedState` prop from `useDehydratedState()`
170​
171```bash
172npm i use-dehydrated-state
173# or
174pnpm add use-dehydrated-state
175# or
176yarn add use-dehydrated-state
177```
178​
179```tsx
180// root.tsx
181import {
182 Hydrate,
183 QueryClient,
184 QueryClientProvider,
185} from '@tanstack/react-query'
186​
187import { useDehydratedState } from 'use-dehydrated-state'
188​
189export default function MyApp() {
190 const [queryClient] = React.useState(() => new QueryClient())
191​
192 const dehydratedState = useDehydratedState()
193​
194 return (
195 <QueryClientProvider client={queryClient}>
196 <Hydrate state={dehydratedState}>
197 <Outlet />
198 </Hydrate>
199 </QueryClientProvider>
200 )
202```
203​
204Now you are ready to prefetch some data in your [`loader`](https://remix.run/docs/en/v1/api/conventions#loader).
205​
206- Create a new `QueryClient` instance **for each page request. This ensures that data is not shared between users and requests.**
207- Prefetch the data using the clients `prefetchQuery` method and wait for it to complete
208- 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`
209​
210```tsx
211// pages/posts.tsx
212import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'
213​
214export async function loader() {
215 const queryClient = new QueryClient()
216​
217 await queryClient.prefetchQuery(['posts'], getPosts)
218​
219 return json({ dehydratedState: dehydrate(queryClient) })
221​
222function Posts() {
223 // This useQuery could just as well happen in some deeper child to
224 // the "Posts"-page, data will be available immediately either way
225 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
226​
227 // This query was not prefetched on the server and will not start
228 // fetching until on the client, both patterns are fine to mix
229 const { data: otherData } = useQuery({
230 queryKey: ['posts-2'],
231 queryFn: getPosts,
232 })
233​
234 // ...
236```
237​
238As 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.
239​
240## Using Other Frameworks or Custom SSR Frameworks
241​
242This 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.
243​
244> If you can, please contribute your findings back to this page for any framework specific guidance!
245​
246### On the Server
247​
248- Create a new `QueryClient` instance **inside of your request handler. This ensures that data is not shared between different users and requests.**
249- Using the client, prefetch any data you need
250- Dehydrate the client
251- 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.**
252- Serialize and embed the dehydrated cache to be sent to the client with the HTML
253- Clear the React Query caches after the dehydrated state has been sent by calling [`queryClient.clear()`](../reference/QueryClient#queryclientclear)
254​
255> 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)
256​
257```tsx
258import {
259 dehydrate,
260 Hydrate,
261 QueryClient,
262 QueryClientProvider,
263} from '@tanstack/react-query'
264​
265async function handleRequest(req, res) {
266 const queryClient = new QueryClient()
267 await queryClient.prefetchQuery(['key'], fn)
268 const dehydratedState = dehydrate(queryClient)
269​
270 const html = ReactDOM.renderToString(
271 <QueryClientProvider client={queryClient}>
272 <Hydrate state={dehydratedState}>
273 <App />
274 </Hydrate>
275 </QueryClientProvider>,
276 )
277​
278 res.send(`
279 <html>
280 <body>
281 <div id="root">${html}</div>
282 <script>
283 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
284 </script>
285 </body>
286 </html>
287 `)
288​
289 queryClient.clear()
291```
292​
293### Client
294​
295- Parse the dehydrated cache state that was sent to the client with the HTML
296- Create a new `QueryClient` instance
297- 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.**
298​
299```tsx
300import {
301 Hydrate,
302 QueryClient,
303 QueryClientProvider,
304} from '@tanstack/react-query'
305​
306const dehydratedState = window.__REACT_QUERY_STATE__
307​
308const queryClient = new QueryClient()
309​
310ReactDOM.hydrate(
311 <QueryClientProvider client={queryClient}>
312 <Hydrate state={dehydratedState}>
313 <App />
314 </Hydrate>
315 </QueryClientProvider>,
316 document.getElementById('root'),
318```
319​
320## Using Experimental `app` Directory in Next.js 13
321​
322> **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.
324> 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.
325​
326Both prefetching approaches, using `initialData` or `<Hydrate>`, are available within the `app` directory.
327​
328- Prefetch the data in a Server Component and prop drill `initialData` to Client Components
329 - Quick to set up for simple cases
330 - May need to prop drill through multiple layers of Client Components
331 - May need to prop drill to multiple Client Components using the same query
332 - Query refetching is based on when the page loads instead of when the data was prefetched on the server
333- Prefetch the query on the server, dehydrate the cache and rehydrate it on the client with `<Hydrate>`
334 - Requires slightly more setup up front
335 - No need to prop drill
336 - Query refetching is based on when the query was prefetched on the server
337​
338### `<QueryClientProvider>` is required by both the `initialData` and `<Hydrate>` prefetching approaches
339​
340The 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`.
341​
342```tsx
343// app/providers.jsx
344'use client'
345​
346import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
347​
348export default function Providers({ children }) {
349 const [queryClient] = React.useState(() => new QueryClient())
350​
351 return (
352 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
353 )
355```
356​
357```tsx
358// app/layout.jsx
359import Providers from './providers'
360​
361export default function RootLayout({ children }) {
362 return (
363 <html lang="en">
364 <head />
365 <body>
366 <Providers>{children}</Providers>
367 </body>
368 </html>
369 )
371```
372​
373### Using `initialData`
374​
375Fetch your initial data in a Server Component higher up in the component tree, and pass it to your Client Component as a prop.
376​
377```tsx
378// app/page.jsx
379export default async function Home() {
380 const initialData = await getPosts()
381​
382 return <Posts posts={initialData} />
384```
385​
386```tsx
387// app/posts.jsx
388'use client'
389​
390import { useQuery } from '@tanstack/react-query'
391​
392export function Posts(props) {
393 const { data } = useQuery({
394 queryKey: ['posts'],
395 queryFn: getPosts,
396 initialData: props.posts,
397 })
398​
399 // ...
401```
402​
403### Using `<Hydrate>`
404​
405Create 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.**
406​
407```tsx
408// app/getQueryClient.jsx
409import { QueryClient } from '@tanstack/react-query'
410import { cache } from 'react'
411​
412const getQueryClient = cache(() => new QueryClient())
413export default getQueryClient
414```
415​
416Fetch 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.
417​
418- Retrieve the `QueryClient` singleton instance
419- Prefetch the data using the client's prefetchQuery method and wait for it to complete
420- Use `dehydrate` to obtain the dehydrated state of the prefetched queries from the query cache
421- Wrap the component tree that needs the prefetched queries inside `<Hydrate>`, and provide it with the dehydrated state
422- You can fetch inside multiple Server Components and use `<Hydrate>` in multiple places
423​
424> 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.
425​
426```tsx
427// app/hydratedPosts.jsx
428import { dehydrate, Hydrate } from '@tanstack/react-query'
429import getQueryClient from './getQueryClient'
430​
431export default async function HydratedPosts() {
432 const queryClient = getQueryClient()
433 await queryClient.prefetchQuery(['posts'], getPosts)
434 const dehydratedState = dehydrate(queryClient)
435​
436 return (
437 <Hydrate state={dehydratedState}>
438 <Posts />
439 </Hydrate>
440 )
442```
443​
444During server rendering, calls to `useQuery` nested within the `<Hydrate>` Client Component will have access to prefetched data provided in the state property.
445​
446```tsx
447// app/posts.jsx
448'use client'
449​
450import { useQuery } from '@tanstack/react-query'
451​
452export default function Posts() {
453 // This useQuery could just as well happen in some deeper child to
454 // the "HydratedPosts"-component, data will be available immediately either way
455 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
456​
457 // This query was not prefetched on the server and will not start
458 // fetching until on the client, both patterns are fine to mix
459 const { data: otherData } = useQuery({
460 queryKey: ['posts-2'],
461 queryFn: getPosts,
462 })
463​
464 // ...
466```
467​
468As 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.
469​
470### Streaming, Suspense and server-side fetching
471​
472Right 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.
473​
474Similarily, 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.
475​
476## Custom SSR with suspense
477​
478If you do not want to provide `prefetchQuery()` for all your queries in the SSR you can use suspense.
479​
480### Server
481​
482```tsx
483import {
484 dehydrate,
485 QueryClient,
486 QueryClientProvider,
487} from '@tanstack/react-query'
488import ssrPrepass from 'react-ssr-prepass'
489​
490async function handleRequest(req, res) {
491 const queryClient = new QueryClient()
492​
493 // React SSR does not support ErrorBoundary
494 try {
495 // Traverse the tree and fetch all Suspense data (thrown promises)
496 await ssrPrepass(<App />)
497 } catch (e) {
498 console.error(e)
499 // Send the index.html (without SSR) on error, so user can try to recover and see something
500 return res.sendFile('path/to/dist/index.html')
501 }
502​
503 const html = ReactDOM.renderToString(
504 <QueryClientProvider client={queryClient}>
505 <App />
506 </QueryClientProvider>,
507 )
508​
509 const dehydratedState = dehydrate(queryClient)
510​
511 res.send(`
512 <html>
513 <body>
514 <div id="root">${html}</div>
515 <script>
516 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
517 </script>
518 </body>
519 </html>
520 `)
521​
522 queryClient.clear()
524```
525​
526### Client
527​
528Make sure to [use suspense in your queries](../guides/suspense).
529​
530## Tips, Tricks and Caveats
531​
532### Only successful queries are included in dehydration
533​
534Any 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.
535​
536Sometimes 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.
537​
538### Staleness is measured from when the query was fetched on the server
539​
540A 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.
541​
542Because `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.
543​
544This 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?
545​
546### High memory consumption on server
547​
548In 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 `cacheTime` period. That may lead to high memory consumption on server in case of high number of requests during that period.
549​
550On the server, `cacheTime` 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 `cacheTime` then you will be responsible for clearing the cache early.
551​
552To 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.
553​
554Alternatively, you can set a smaller `cacheTime`.