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

ssr.md

500 lines22.5 KB

1---
2id: ssr
3title: Server Rendering & Hydration
4---
5​
6In this guide you'll learn how to use Preact Query with server rendering.
7​
8See the guide on [Prefetching & Router Integration](./prefetching.md) for some background. You might also want to check out the [Performance & Request Waterfalls guide](./request-waterfalls.md) before that.
9​
10## Server Rendering & Preact Query
11​
12So what is server rendering anyway? The rest of this guide will assume you are familiar with the concept, but let's spend some time to look at how it relates to Preact Query. Server rendering is the act of generating the initial html on the server, so that the user has some content to look at as soon as the page loads. This can happen on demand when a page is requested (SSR). It can also happen ahead of time either because a previous request was cached, or at build time (SSG).
13​
14If you've read the [Performance & Request Waterfalls guide](./request-waterfalls.md), you might remember this:
15​
16```
171. |-> Markup (without content)
182. |-> JS
193. |-> Query
20```
21​
22With a client rendered application, these are the minimum 3 server roundtrips you will need to make before getting any content on the screen for the user. One way of viewing server rendering is that it turns the above into this:
23​
24```
251. |-> Markup (with content AND initial data)
262. |-> JS
27```
28​
29As soon as **1.** is complete, the user can see the content and when **2.** finishes, the page is interactive and clickable. Because the markup also contains the initial data we need, step **3.** does not need to run on the client at all, at least until you want to revalidate the data for some reason.
30​
31This is all from the client's perspective. On the server, we need to **prefetch** that data before we generate/render the markup, we need to **dehydrate** that data into a serializable format we can embed in the markup, and on the client we need to **hydrate** that data into a Preact Query cache so we can avoid doing a new fetch on the client.
32​
33Read on to learn how to implement these three steps with Preact Query.
34​
35## A quick note on Suspense
36​
37This guide uses the regular `useQuery` API. While we don't necessarily recommend it, it is possible to replace this with `useSuspenseQuery` instead **as long as you always prefetch all your queries**. The upside is that you get to use `<Suspense>` for loading states on the client.
38​
39If you do forget to prefetch a query when you are using `useSuspenseQuery`, the consequences will depend on your setup. In some cases, the data will Suspend and get fetched on the server but never be hydrated to the client, where it will fetch again. In these cases you will get a markup hydration mismatch, because the server and the client tried to render different things.
40​
41## Initial setup
42​
43The first step of using Preact Query is always to create a `queryClient` and wrap the application in a `<QueryClientProvider>`. When doing server rendering, it's important to create the `queryClient` instance **inside of your app**, in Preact state (an instance ref works fine too). **This ensures that data is not shared between different users and requests**, while still only creating the `queryClient` once per component lifecycle.
44​
45```tsx
46import { QueryClient, QueryClientProvider } from '@tanstack/preact-query'
47import { useState } from 'preact/hooks'
48​
49// NEVER DO THIS ON THE SERVER:
50// const queryClient = new QueryClient()
51//
52// Creating the queryClient at the module root level makes the cache shared
53// between all requests and means _all_ data gets passed to _all_ users.
54// Besides being bad for performance, this also leaks any sensitive data.
55// (On the client this is fine, since there's only ever one visitor per page.)
56​
57export function App({ children }) {
58 // Instead do this, which ensures each request has its own cache:
59 const [queryClient] = useState(
60 () =>
61 new QueryClient({
62 defaultOptions: {
63 queries: {
64 // With SSR, we usually want to set some default staleTime
65 // above 0 to avoid refetching immediately on the client
66 staleTime: 60 * 1000,
67 },
68 },
69 }),
70 )
71​
72 return (
73 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
74 )
76```
77​
78## Get started fast with `initialData`
79​
80The quickest way to get started is to not involve Preact Query at all when it comes to prefetching and not use the `dehydrate`/`hydrate` APIs. What you do instead is passing the raw data in as the `initialData` option to `useQuery`:
81​
82```tsx
83function Posts({ posts }) {
84 const { data } = useQuery({
85 queryKey: ['posts'],
86 queryFn: getPosts,
87 initialData: posts,
88 })
89​
90 // ...
92```
93​
94The 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:
95​
96- If you are calling `useQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
97- If you are calling `useQuery` with the same query in multiple locations, passing `initialData` to only one of them can be brittle and break when your app changes. If you remove or move the component that has the `useQuery` with `initialData`, the more deeply nested `useQuery` might no longer have any data. Passing `initialData` to **all** queries that need it can also be cumbersome.
98- 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
99- If there is already data in the cache for a query, `initialData` will never overwrite this data, **even if the new data is fresher than the old one**.
100​
101Setting up the full hydration solution is straightforward and does not have these drawbacks, this will be the focus for the rest of the documentation.
102​
103## Using the Hydration APIs
104​
105With just a little more setup, you can use a `queryClient` to prefetch queries during a server render pass, serialize that `queryClient` and send it down with the initial markup, then reuse it to hydrate the client render. This avoids the drawbacks above. At a general level these are the extra steps:
106​
107- On the server, create a `const queryClient = new QueryClient(options)`
108- Do `await queryClient.query(...)` for each query you want to prefetch
109 - You want to use `await Promise.all(...)` to fetch the queries in parallel when possible
110 - It's fine to have queries that aren't prefetched. These won't be server rendered, instead they will be fetched on the client after the application is interactive. This can be great for content that is shown only after user interaction, or is far down on the page to avoid blocking more critical content.
111- Call `dehydrate(queryClient)` and embed the result in the markup you send to the client, alongside the html produced by `renderToString`
112- On the client, wrap your tree with `<HydrationBoundary state={dehydratedState}>`, where `dehydratedState` is parsed back out of the embedded markup
113​
114> An interesting detail is that there are actually _two_ `queryClient`s involved on the server: one that prefetches, and one that renders. The prefetching client fetches the queries and gets `dehydrate`d; its dehydrated state is then `hydrate`d into a fresh render client, which is the one you actually pass to `<QueryClientProvider>` for `renderToString`. On the client, a third `queryClient` is created and hydrated with the same dehydrated state via `<HydrationBoundary>`, so all three start from the same data and produce the same markup.
115​
116### Full example with `preact-render-to-string`
117​
118Server entry point:
119​
120```tsx
121import { renderToString } from 'preact-render-to-string'
122import {
123 QueryCache,
124 QueryClient,
125 QueryClientProvider,
126 dehydrate,
127 hydrate,
128 noop,
129} from '@tanstack/preact-query'
130​
131function makeQueryClient() {
132 return new QueryClient({
133 queryCache: new QueryCache(),
134 defaultOptions: {
135 queries: {
136 // With SSR, we usually want to set some default staleTime
137 // above 0 to avoid refetching immediately on the client
138 staleTime: 60 * 1000,
139 },
140 },
141 })
143​
144export async function render(url) {
145 // The prefetching client: only used to fetch and dehydrate
146 const prefetchClient = makeQueryClient()
147​
148 await prefetchClient
149 .query({
150 queryKey: ['posts'],
151 queryFn: getPosts,
152 })
153 .catch(noop)
154​
155 const dehydratedState = dehydrate(prefetchClient)
156​
157 // The render client: hydrated with the same state, used for renderToString
158 const renderClient = makeQueryClient()
159 hydrate(renderClient, dehydratedState)
160​
161 const appHtml = renderToString(
162 <QueryClientProvider client={renderClient}>
163 <App />
164 </QueryClientProvider>,
165 )
166​
167 // Embed both the markup and the dehydrated state in the html you send down.
168 // Use a safe serializer here (see Serialization below), NOT JSON.stringify,
169 // since raw JSON.stringify output can break out of the <script> tag:
170 // e.g. `<div id="app">${appHtml}</div><script>window.__DEHYDRATED_STATE__ = ${serialize(dehydratedState)}</script>`
171 return { appHtml, dehydratedState }
173```
174​
175Client entry point:
176​
177```tsx
178import { hydrate as preactHydrate } from 'preact'
179import { useState } from 'preact/hooks'
180import {
181 HydrationBoundary,
182 QueryClient,
183 QueryClientProvider,
184} from '@tanstack/preact-query'
185​
186function makeQueryClient() {
187 return new QueryClient({
188 defaultOptions: {
189 queries: {
190 // With SSR, we usually want to set some default staleTime
191 // above 0 to avoid refetching immediately on the client
192 staleTime: 60 * 1000,
193 },
194 },
195 })
197​
198function App({ dehydratedState }) {
199 const [queryClient] = useState(() => makeQueryClient())
200​
201 return (
202 <QueryClientProvider client={queryClient}>
203 <HydrationBoundary state={dehydratedState}>
204 <Posts />
205 </HydrationBoundary>
206 </QueryClientProvider>
207 )
209​
210// Read back and deserialize whatever you embedded on the server,
211// e.g. `window.__DEHYDRATED_STATE__`
212preactHydrate(
213 <App dehydratedState={window.__DEHYDRATED_STATE__} />,
214 document.getElementById('app'),
216```
217​
218Anywhere inside the tree:
219​
220```tsx
221function Posts() {
222 // This useQuery could just as well happen in some deeper child to <App>,
223 // data will be available immediately either way
224 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
225​
226 // This query was not prefetched on the server and will not start
227 // fetching until on the client, both patterns are fine to mix
228 const { data: commentsData } = useQuery({
229 queryKey: ['posts-comments'],
230 queryFn: getComments,
231 })
232​
233 // ...
235```
236​
237## Prefetching dependent queries
238​
239Over in the Prefetching guide we learned how to [prefetch dependent queries](./prefetching.md#dependent-queries-code-splitting), but how do we do this on the server? Consider the following code, taken from the [Dependent Queries guide](./dependent-queries.md):
240​
241```tsx
242// Get the user
243const { data: user } = useQuery({
244 queryKey: ['user', email],
245 queryFn: getUserByEmail,
246})
247​
248const userId = user?.id
249​
250// Then get the user's projects
251const {
252 status,
253 fetchStatus,
254 data: projects,
255} = useQuery({
256 queryKey: ['projects', userId],
257 queryFn: getProjectsByUser,
258 // The query will not execute until the userId exists
259 enabled: !!userId,
260})
261```
262​
263How would we prefetch this so it can be server rendered? Here's an example:
264​
265```tsx
266const queryClient = new QueryClient()
267​
268const user = await queryClient.query({
269 queryKey: ['user', email],
270 queryFn: getUserByEmail,
271})
272​
273if (user?.id) {
274 await queryClient.query({
275 queryKey: ['projects', user.id],
276 queryFn: getProjectsByUser,
277 })
279​
280const dehydratedState = dehydrate(queryClient)
281```
282​
283This can get more complex of course, but since prefetching just happens with plain JavaScript, you can use the full power of the language to build your logic. Make sure you prefetch all queries that you want to be server rendered.
284​
285## Error handling
286​
287Preact Query defaults to a graceful degradation strategy. This means:
288​
289- `dehydrate(...)` only includes successful queries, not failed ones
290- We can intentionally ignore the returned promise from `void queryClient.query(...)` and add `.catch(noop)` to swallow any errors, so surrounding server code will not observe query errors
291​
292This will lead to any failed queries being retried on the client and that the server rendered output will include loading states instead of the full content.
293​
294While a good default, sometimes this is not what you want. When critical content is missing, you might want to respond with a 404 or 500 status code depending on the situation. For these cases, use `await queryClient.query(...)` without the noop catch, which will throw errors when it fails, letting you handle things in a suitable way.
295​
296```tsx
297let result
298​
299try {
300 result = await queryClient.query(...)
301} catch (error) {
302 // Handle the error in whatever way fits your server setup
304​
305// You might also want to check and handle any invalid `result` here
306```
307​
308If you for some reason want to include failed queries in the dehydrated state to avoid retries, you can use the option `shouldDehydrateQuery` to override the default function and implement your own logic:
309​
310```tsx
311dehydrate(queryClient, {
312 shouldDehydrateQuery: (query) => {
313 // This will include all queries, including failed ones,
314 // but you can also implement your own logic by inspecting `query`
315 return true
316 },
317})
318```
319​
320## Serialization
321​
322The `dehydrate(queryClient)` result needs to be serialized so it can be embedded into the markup and transported to the client, then parsed back out before being passed to `<HydrationBoundary state={...}>`.
323​
324Your first instinct might be to use `JSON.stringify(dehydratedState)`, but because this doesn't escape things like `<script>alert('Oh no..')</script>` by default, this can easily lead to **XSS-vulnerabilities** in your application. Instead we recommend using a library like [Serialize JavaScript](https://github.com/yahoo/serialize-javascript) or [devalue](https://github.com/Rich-Harris/devalue) which are both safe against XSS injections out of the box.
325​
326By default, plain `JSON.stringify`/`JSON.parse` also do not support `undefined`, `Error`, `Date`, `Map`, `Set`, `BigInt`, `Infinity`, `NaN`, `-0`, regular expressions etc. This also means that you can not return any of these things from your queries unless your serializer supports them. If returning these values is something you want, check out [superjson](https://github.com/blitz-js/superjson) or similar packages (note that superjson **does not** escape values by itself, so you still need an extra step for escaping the output).
327​
328Instead of serializing the whole `dehydratedState` from the outside, you can also let Preact Query do this per-query by configuring `dehydrate.serializeData`/`hydrate.deserializeData` on the `QueryClient`:
329​
330```tsx
331const queryClient = new QueryClient({
332 defaultOptions: {
333 dehydrate: {
334 serializeData: serialize,
335 },
336 hydrate: {
337 deserializeData: deserialize,
338 },
339 },
340})
341```
342​
343This transforms each query's `data` on the way out of `dehydrate` and on the way into `hydrate`, so `serialize`/`deserialize` only ever need to handle the shape of your query data, not the full dehydrated state. As with any custom serializer, make sure it's safe against XSS if you end up embedding its output directly into markup.
344​
345## Streaming
346​
347`preact-render-to-string` can also [stream](https://preactjs.com/guide/v11/server-side-rendering#streaming) the html with `renderToPipeableStream`. It sends `<Suspense>` fallbacks right away and replaces them with the finished content as it resolves, so the parts of the page that are ready can be shown before the slow ones.
348​
349To combine this with `useSuspenseQuery`, the rule from [the note on Suspense](#a-quick-note-on-suspense) still applies: prefetch every query you render. Start all of them before rendering, without awaiting them, so each `<Suspense>` boundary only waits for its own query instead of starting it after the previous boundary resolved:
350​
351```tsx
352void queryClient.query(postsQueries.list()).catch(noop)
353void queryClient.query(commentsQueries.list()).catch(noop)
354```
355​
356Since the html is sent in chunks, there is no single point where you could `dehydrate` the whole cache and embed it. Instead, `dehydrate` each query as soon as it succeeds and send its state along with the next chunk, so that by the time the client hydrates, it has the data of every boundary:
357​
358```tsx
359import { Transform } from 'node:stream'
360import { renderToPipeableStream } from 'preact-render-to-string/stream-node'
361import { uneval } from 'devalue'
362import { QueryClientProvider, dehydrate, noop } from '@tanstack/preact-query'
363​
364export function render({ onShellReady, onError }) {
365 const queryClient = makeQueryClient()
366​
367 void queryClient.query(postsQueries.list()).catch(noop)
368 void queryClient.query(commentsQueries.list()).catch(noop)
369​
370 // Collect each query's state as soon as it succeeds
371 const states = []
372 const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
373 if (event.type === 'updated' && event.action.type === 'success') {
374 states.push(
375 dehydrate(queryClient, {
376 shouldDehydrateQuery: (query) => query === event.query,
377 }),
378 )
379 }
380 })
381​
382 // Send the collected states right before the next chunk
383 const flushStates = () =>
384 states
385 .splice(0)
386 .map(
387 (state) =>
388 `<script>window.__QUERY_STATES__.push(${uneval(state)});document.currentScript.remove()</script>`,
389 )
390 .join('')
391​
392 const injectStates = new Transform({
393 transform(chunk, _encoding, callback) {
394 callback(null, flushStates() + chunk)
395 },
396 flush(callback) {
397 callback(null, flushStates())
398 },
399 })
400​
401 const stream = renderToPipeableStream(
402 <QueryClientProvider client={queryClient}>
403 <App />
404 </QueryClientProvider>,
405 {
406 onShellReady,
407 onAllReady: unsubscribe,
408 onError: (error) => {
409 // The renderer destroys its own stream on errors and aborts,
410 // so end this one as well to let the response finish
411 unsubscribe()
412 injectStates.end()
413 onError(error)
414 },
415 },
416 )
417​
418 return {
419 pipe: (writable) => {
420 injectStates.pipe(writable, { end: false })
421 stream.pipe(injectStates)
422 return injectStates
423 },
424 abort: stream.abort,
425 }
427```
428​
429Define `window.__QUERY_STATES__ = []` in an inline `<script>` in the `<head>` of your html, write the html before the app in `onShellReady`, pipe the app into the response and write the rest of the html once the stream ends:
430​
431```tsx
432const { pipe, abort } = render({
433 onShellReady() {
434 res.statusCode = 200
435 res.setHeader('Content-Type', 'text/html')
436 res.write(htmlStart)
437​
438 const stream = pipe(res)
439 stream.on('end', () => {
440 clearTimeout(abortTimeout)
441 res.end(htmlEnd)
442 })
443 },
444 onError(error) {
445 console.error(error)
446 },
447})
448​
449// Stop streaming and let the client render the rest if it takes too long
450const abortTimeout = setTimeout(abort, 10000)
451```
452​
453On the client, `hydrate` all streamed states into the `queryClient` before hydrating the app. The client entry is a module script, so it only runs once the whole stream has been received:
454​
455```tsx
456import { hydrate as preactHydrate } from 'preact'
457import { QueryClientProvider, hydrate } from '@tanstack/preact-query'
458​
459const queryClient = makeQueryClient()
460​
461for (const state of window.__QUERY_STATES__) {
462 hydrate(queryClient, state)
464​
465preactHydrate(
466 <QueryClientProvider client={queryClient}>
467 <App />
468 </QueryClientProvider>,
469 document.getElementById('root'),
471```
472​
473A few things to keep in mind:
474​
475- The states are embedded directly into the markup, so serialize them with an XSS-safe serializer like `uneval` from [devalue](https://github.com/Rich-Harris/devalue). See [Serialization](#serialization).
476- Middleware that buffers the response, like `compression`, holds back the chunks until the end. Flush it after every chunk, for example with `res.flush()`, to keep the response streaming.
477- Failed queries are not dehydrated, so the client fetches them again. Wrap the boundaries in an error boundary built with [`useErrorBoundary`](https://preactjs.com/guide/v10/hooks/#useerrorboundary) to show an error when that fetch fails as well. Don't use a class component with `getDerivedStateFromError` or `componentDidCatch` together with `options.errorBoundaries` for this: `preact-render-to-string` then also catches the promises of suspending components on the server, which breaks streaming.
478- If a query fails on the server, the streamed content of its boundary ends up as the text `undefined` until the client hydrates and replaces it.
479​
480## Tips, Tricks and Caveats
481​
482### Staleness is measured from when the query was fetched on the server
483​
484A 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.
485​
486Because `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.
487​
488This 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?
489​
490### High memory consumption on server
491​
492In case you are creating the `QueryClient` for every request, Preact 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.
493​
494On 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.
495​
496Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/functions/HydrationBoundary.md) places necessary data into the cache for rendering, but if the garbage collector removes the data before the rendering completes, issues may arise. If you require a shorter `gcTime`, we recommend setting it to `2 * 1000` to allow sufficient time for the app to reference the data.
497​
498To clear the cache after it is not needed and to lower memory consumption, you can add a call to [`queryClient.clear()`](../reference/classes/QueryClient.md#clear) after the request is handled and dehydrated state has been sent to the client.
499​
500Alternatively, you can set a smaller `gcTime`.