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

ssr.md

261 lines12.2 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### Using `initialData`
24​
25Together 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:
26​
27```tsx
28export async function getStaticProps() {
29 const posts = await getPosts()
30 return { props: { posts } }
32​
33function Posts(props) {
34 const { data } = useQuery(['posts'], getPosts, { initialData: props.posts })
35​
36 // ...
38```
39​
40The 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:
41​
42- If you are calling `useQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
43- If you are calling `useQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
44- 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
45​
46### Using Hydration
47​
48React 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.
49​
50To support caching queries on the server and set up hydration:
51​
52- 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.**
53- Wrap your app component with `<QueryClientProvider>` and pass it the client instance
54- Wrap your app component with `<Hydrate>` and pass it the `dehydratedState` prop from `pageProps`
55​
56```tsx
57// _app.jsx
58import { Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query'
59​
60export default function MyApp({ Component, pageProps }) {
61 const [queryClient] = React.useState(() => new QueryClient())
62​
63 return (
64 <QueryClientProvider client={queryClient}>
65 <Hydrate state={pageProps.dehydratedState}>
66 <Component {...pageProps} />
67 </Hydrate>
68 </QueryClientProvider>
69 )
71```
72​
73Now 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.
74​
75- Create a new `QueryClient` instance **for each page request. This ensures that data is not shared between users and requests.**
76- Prefetch the data using the clients `prefetchQuery` method and wait for it to complete
77- 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`
78​
79```tsx
80// pages/posts.jsx
81import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query';
82​
83export async function getStaticProps() {
84 const queryClient = new QueryClient()
85​
86 await queryClient.prefetchQuery(['posts'], getPosts)
87​
88 return {
89 props: {
90 dehydratedState: dehydrate(queryClient),
91 },
92 }
94​
95function Posts() {
96 // This useQuery could just as well happen in some deeper child to
97 // the "Posts"-page, data will be available immediately either way
98 const { data } = useQuery(['posts'], getPosts)
99​
100 // This query was not prefetched on the server and will not start
101 // fetching until on the client, both patterns are fine to mix
102 const { data: otherData } = useQuery(['posts-2'], getPosts)
103​
104 // ...
106```
107​
108As 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.
109​
110### Caveat for Next.js rewrites
111​
112There'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`.
113​
114The 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.
115​
116## Using Other Frameworks or Custom SSR Frameworks
117​
118This 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.
119​
120> If you can, please contribute your findings back to this page for any framework specific guidance!
121​
122### On the Server
123​
124- Create a new `QueryClient` instance **inside of your request handler. This ensures that data is not shared between different users and requests.**
125- Using the client, prefetch any data you need
126- Dehydrate the client
127- 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.**
128- Serialize and embed the dehydrated cache to be sent to the client with the HTML
129- Clear the React Query caches after the dehydrated state has been sent by calling [`queryClient.clear()`](../reference/QueryClient#queryclientclear)
130​
131> 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)
132​
133```tsx
134import { dehydrate, Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query';
135​
136async function handleRequest (req, res) {
137 const queryClient = new QueryClient()
138 await queryClient.prefetchQuery(['key'], fn)
139 const dehydratedState = dehydrate(queryClient)
140​
141 const html = ReactDOM.renderToString(
142 <QueryClientProvider client={queryClient}>
143 <Hydrate state={dehydratedState}>
144 <App />
145 </Hydrate>
146 </QueryClientProvider>
147 )
148​
149 res.send(`
150 <html>
151 <body>
152 <div id="root">${html}</div>
153 <script>
154 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
155 </script>
156 </body>
157 </html>
158 `)
159​
160 queryClient.clear()
162```
163​
164### Client
165​
166- Parse the dehydrated cache state that was sent to the client with the HTML
167- Create a new `QueryClient` instance
168- 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.**
169​
170```tsx
171import { Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query'
172​
173const dehydratedState = window.__REACT_QUERY_STATE__
174​
175const queryClient = new QueryClient()
176​
177ReactDOM.hydrate(
178 <QueryClientProvider client={queryClient}>
179 <Hydrate state={dehydratedState}>
180 <App />
181 </Hydrate>
182 </QueryClientProvider>,
183 document.getElementById('root')
185```
186​
187## Custom SSR with suspense
188​
189If you do not want to provide `prefetchQuery()` for all your queries in the SSR you can use suspense.
190​
191### Server
192​
193```tsx
194import { dehydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query';
195import ssrPrepass from 'react-ssr-prepass'
196​
197async function handleRequest (req, res) {
198 const queryClient = new QueryClient()
199​
200 // React SSR does not support ErrorBoundary
201 try {
202 // Traverse the tree and fetch all Suspense data (thrown promises)
203 await ssrPrepass(<App />);
204 } catch (e) {
205 console.error(e);
206 // Send the index.html (without SSR) on error, so user can try to recover and see something
207 return res.sendFile('path/to/dist/index.html');
208 }
210 const html = ReactDOM.renderToString(
211 <QueryClientProvider client={queryClient}>
212 <App />
213 </QueryClientProvider>
214 )
215​
216 const dehydratedState = dehydrate(queryClient);
218 res.send(`
219 <html>
220 <body>
221 <div id="root">${html}</div>
222 <script>
223 window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};
224 </script>
225 </body>
226 </html>
227 `)
228​
229 queryClient.clear()
231```
232​
233### Client
234​
235Make sure to [use suspense in your queries](./suspense.md).
236​
237## Tips, Tricks and Caveats
238​
239### Only successful queries are included in dehydration
240​
241Any 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.
242​
243Sometimes 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.
244​
245### Staleness is measured from when the query was fetched on the server
246​
247A 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.
248​
249Because `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.
250​
251This 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?
252​
253### High memory consumption on server
254​
255In 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.
256​
257On 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.
258​
259To 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.
260​
261Alternatively, you can set a smaller `cacheTime`.