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

advanced-ssr.md

623 lines26.3 KB

1---
2id: advanced-ssr
3title: Advanced Server Rendering
4---
5​
6Welcome to the Advanced Server Rendering guide, where you will learn all about using React Query with streaming, Server Components and the Next.js app router.
7​
8You might want to read the [Server Rendering & Hydration guide](../ssr.md) before this one as it teaches the basics for using React Query with SSR, and [Performance & Request Waterfalls](../request-waterfalls.md) as well as [Prefetching & Router Integration](../prefetching.md) also contains valuable background.
9​
10Before we start, let's note that while the `initialData` approach outlined in the SSR guide also works with Server Components, we'll focus this guide on the hydration APIs.
11​
12## Server Components & Next.js app router
13​
14We won't cover Server Components in depth here, but the short version is that they are components that are guaranteed to _only_ run on the server, both for the initial page view and **also on page transitions**. This is similar to how Next.js `getServerSideProps`/`getStaticProps` and Remix `loader` works, as these also always run on the server but while those can only return data, Server Components can do a lot more. The data part is central to React Query however, so let's focus on that.
15​
16How do we take what we learned in the Server Rendering guide about [passing data prefetched in framework loaders to the app](../ssr.md#using-the-hydration-apis) and apply that to Server Components and the Next.js app router? The best way to start thinking about this is to consider Server Components as "just" another framework loader.
17​
18### A quick note on terminology
19​
20So far in these guides, we've been talking about the _server_ and the _client_. It's important to note that confusingly enough this does not match 1-1 with _Server Components_ and _Client Components_. Server Components are guaranteed to only run on the server, but Client Components can actually run in both places. The reason for this is that they can also render during the initial _server rendering_ pass.
21​
22One way to think of this is that even though Server Components also _render_, they happen during a "loader phase" (always happens on the server), while Client Components run during the "application phase". That application can run both on the server during SSR, and in for example a browser. Where exactly that application runs and if it runs during SSR or not might differ between frameworks.
23​
24### Initial setup
25​
26The first step of any React Query setup is always to create a `queryClient` and wrap your application in a `QueryClientProvider`. With Server Components, this looks mostly the same across frameworks, one difference being the filename conventions:
27​
28```tsx
29// In Next.js, this file would be called: app/providers.tsx
30'use client'
31​
32// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top
33import {
34 isServer,
35 QueryClient,
36 QueryClientProvider,
37} from '@tanstack/react-query'
38​
39function makeQueryClient() {
40 return new QueryClient({
41 defaultOptions: {
42 queries: {
43 // With SSR, we usually want to set some default staleTime
44 // above 0 to avoid refetching immediately on the client
45 staleTime: 60 * 1000,
46 },
47 },
48 })
50​
51let browserQueryClient: QueryClient | undefined = undefined
52​
53function getQueryClient() {
54 if (isServer) {
55 // Server: always make a new query client
56 return makeQueryClient()
57 } else {
58 // Browser: make a new query client if we don't already have one
59 // This is very important, so we don't re-make a new client if React
60 // suspends during the initial render. This may not be needed if we
61 // have a suspense boundary BELOW the creation of the query client
62 if (!browserQueryClient) browserQueryClient = makeQueryClient()
63 return browserQueryClient
64 }
66​
67export default function Providers({ children }: { children: React.ReactNode }) {
68 // NOTE: Avoid useState when initializing the query client if you don't
69 // have a suspense boundary between this and the code that may
70 // suspend because React will throw away the client on the initial
71 // render if it suspends and there is no boundary
72 const queryClient = getQueryClient()
73​
74 return (
75 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
76 )
78```
79​
80```tsx
81// In Next.js, this file would be called: app/layout.tsx
82import Providers from './providers'
83​
84export default function RootLayout({
85 children,
86}: {
87 children: React.ReactNode
88}) {
89 return (
90 <html lang="en">
91 <head />
92 <body>
93 <Providers>{children}</Providers>
94 </body>
95 </html>
96 )
98```
99​
100This part is pretty similar to what we did in the SSR guide, we just need to split things up into two different files.
101​
102### Prefetching and de/hydrating data
103​
104Next, let’s look at how to actually prefetch data, then dehydrate and hydrate it. This is what it looked like using the **Next.js Pages Router**:
105​
106```tsx
107// pages/posts.tsx
108import {
109 dehydrate,
110 HydrationBoundary,
111 QueryClient,
112 useQuery,
113} from '@tanstack/react-query'
114​
115// This could also be getServerSideProps
116export async function getStaticProps() {
117 const queryClient = new QueryClient()
118​
119 await queryClient.prefetchQuery({
120 queryKey: ['posts'],
121 queryFn: getPosts,
122 })
123​
124 return {
125 props: {
126 dehydratedState: dehydrate(queryClient),
127 },
128 }
130​
131function Posts() {
132 // This useQuery could just as well happen in some deeper child to
133 // the <PostsRoute>, data will be available immediately either way
134 //
135 // Note that we are using useQuery here instead of useSuspenseQuery.
136 // Because this data has already been prefetched, there is no need to
137 // ever suspend in the component itself. If we forget or remove the
138 // prefetch, this will instead fetch the data on the client, while
139 // using useSuspenseQuery would have had worse side effects.
140 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
141​
142 // This query was not prefetched on the server and will not start
143 // fetching until on the client, both patterns are fine to mix
144 const { data: commentsData } = useQuery({
145 queryKey: ['posts-comments'],
146 queryFn: getComments,
147 })
148​
149 // ...
151​
152export default function PostsRoute({ dehydratedState }) {
153 return (
154 <HydrationBoundary state={dehydratedState}>
155 <Posts />
156 </HydrationBoundary>
157 )
159```
160​
161Converting this to the app router actually looks pretty similar, we just need to move things around a bit. First, we'll create a Server Component to do the prefetching part:
162​
163```tsx
164// app/posts/page.tsx
165import {
166 dehydrate,
167 HydrationBoundary,
168 QueryClient,
169} from '@tanstack/react-query'
170import Posts from './posts'
171​
172export default async function PostsPage() {
173 const queryClient = new QueryClient()
174​
175 await queryClient.prefetchQuery({
176 queryKey: ['posts'],
177 queryFn: getPosts,
178 })
179​
180 return (
181 // Neat! Serialization is now as easy as passing props.
182 // HydrationBoundary is a Client Component, so hydration will happen there.
183 <HydrationBoundary state={dehydrate(queryClient)}>
184 <Posts />
185 </HydrationBoundary>
186 )
188```
189​
190Next, we'll look at what the Client Component part looks like:
191​
192```tsx
193// app/posts/posts.tsx
194'use client'
195​
196export default function Posts() {
197 // This useQuery could just as well happen in some deeper
198 // child to <Posts>, data will be available immediately either way
199 const { data } = useQuery({
200 queryKey: ['posts'],
201 queryFn: () => getPosts(),
202 })
203​
204 // This query was not prefetched on the server and will not start
205 // fetching until on the client, both patterns are fine to mix.
206 const { data: commentsData } = useQuery({
207 queryKey: ['posts-comments'],
208 queryFn: getComments,
209 })
210​
211 // ...
213```
214​
215One neat thing about the examples above is that the only thing that is Next.js-specific here are the file names, everything else would look the same in any other framework that supports Server Components.
216​
217In the SSR guide, we noted that you could get rid of the boilerplate of having `<HydrationBoundary>` in every route. This is not possible with Server Components.
218​
219> NOTE: If you encounter a type error while using async Server Components with TypeScript versions lower than `5.1.3` and `@types/react` versions lower than `18.2.8`, it is recommended to update to the latest versions of both. Alternatively, you can use the temporary workaround of adding `{/* @ts-expect-error Server Component */}` when calling this component inside another. For more information, see [Async Server Component TypeScript Error](https://nextjs.org/docs/app/building-your-application/configuring/typescript#async-server-component-typescript-error) in the Next.js 13 docs.
220​
221> NOTE: If you encounter an error `Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.` make sure that you're **not** passing to queryFn a function reference, instead call the function because queryFn args has a bunch of properties and not all of it would be serializable. see [Server Action only works when queryFn isn't a reference](https://github.com/TanStack/query/issues/6264).
222​
223### Nesting Server Components
224​
225A nice thing about Server Components is that they can be nested and exist on many levels in the React tree, making it possible to prefetch data closer to where it's actually used instead of only at the top of the application (just like Remix loaders). This can be as simple as a Server Component rendering another Server Component (we'll leave the Client Components out in this example for brevity):
226​
227```tsx
228// app/posts/page.tsx
229import {
230 dehydrate,
231 HydrationBoundary,
232 QueryClient,
233} from '@tanstack/react-query'
234import Posts from './posts'
235import CommentsServerComponent from './comments-server'
236​
237export default async function PostsPage() {
238 const queryClient = new QueryClient()
239​
240 await queryClient.prefetchQuery({
241 queryKey: ['posts'],
242 queryFn: getPosts,
243 })
244​
245 return (
246 <HydrationBoundary state={dehydrate(queryClient)}>
247 <Posts />
248 <CommentsServerComponent />
249 </HydrationBoundary>
250 )
252​
253// app/posts/comments-server.tsx
254import {
255 dehydrate,
256 HydrationBoundary,
257 QueryClient,
258} from '@tanstack/react-query'
259import Comments from './comments'
260​
261export default async function CommentsServerComponent() {
262 const queryClient = new QueryClient()
263​
264 await queryClient.prefetchQuery({
265 queryKey: ['posts-comments'],
266 queryFn: getComments,
267 })
268​
269 return (
270 <HydrationBoundary state={dehydrate(queryClient)}>
271 <Comments />
272 </HydrationBoundary>
273 )
275```
276​
277As you can see, it's perfectly fine to use `<HydrationBoundary>` in multiple places, and create and dehydrate multiple `queryClient` for prefetching.
278​
279Note that because we are awaiting `getPosts` before rendering `CommentsServerComponent` this would lead to a server side waterfall:
280​
281```
2821. |> getPosts()
2832. |> getComments()
284```
285​
286If the server latency to the data is low, this might not be a huge issue, but is still worth pointing out.
287​
288In Next.js, besides prefetching data in `page.tsx`, you can also do it in `layout.tsx`, and in [parallel routes](https://nextjs.org/docs/app/building-your-application/routing/parallel-routes). Because these are all part of the routing, Next.js knows how to fetch them all in parallel. So if `CommentsServerComponent` above was instead expressed as a parallel route, the waterfall would be flattened automatically.
289​
290As more frameworks start supporting Server Components, they might have other routing conventions. Read your framework docs for details.
291​
292### Alternative: Use a single `queryClient` for prefetching
293​
294In the example above, we create a new `queryClient` for each Server Component that fetches data. This is the recommended approach, but if you want to, you can alternatively create a single one that is reused across all Server Components:
295​
296```tsx
297// app/getQueryClient.tsx
298import { QueryClient } from '@tanstack/react-query'
299import { cache } from 'react'
300​
301// cache() is scoped per request, so we don't leak data between requests
302const getQueryClient = cache(() => new QueryClient())
303export default getQueryClient
304```
305​
306The benefit of this is that you can call `getQueryClient()` to get a hold of this client anywhere that gets called from a Server Component, including utility functions. The downside is that every time you call `dehydrate(getQueryClient())`, you serialize _the entire_ `queryClient`, including queries that have already been serialized before and are unrelated to the current Server Component which is unnecessary overhead.
307​
308Next.js already dedupes requests that utilize `fetch()`, but if you are using something else in your `queryFn`, or if you use a framework that does _not_ dedupe these requests automatically, using a single `queryClient` as described above might make sense, despite the duplicated serialization.
309​
310> As a future improvement, we might look into creating a `dehydrateNew()` function (name pending) that only dehydrate queries that are _new_ since the last call to `dehydrateNew()`. Feel free to get in touch if this sounds interesting and like something you want to help out with!
311​
312### Data ownership and revalidation
313​
314With Server Components, it's important to think about data ownership and revalidation. To explain why, let's look at a modified example from above:
315​
316```tsx
317// app/posts/page.tsx
318import {
319 dehydrate,
320 HydrationBoundary,
321 QueryClient,
322} from '@tanstack/react-query'
323import Posts from './posts'
324​
325export default async function PostsPage() {
326 const queryClient = new QueryClient()
327​
328 // Note we are now using fetchQuery()
329 const posts = await queryClient.fetchQuery({
330 queryKey: ['posts'],
331 queryFn: getPosts,
332 })
333​
334 return (
335 <HydrationBoundary state={dehydrate(queryClient)}>
336 {/* This is the new part */}
337 <div>Nr of posts: {posts.length}</div>
338 <Posts />
339 </HydrationBoundary>
340 )
342```
343​
344We are now rendering data from the `getPosts` query both in a Server Component and in a Client Component. This will be fine for the initial page render, but what happens when the query revalidates on the client for some reason when `staleTime` has been passed?
345​
346React Query has no idea of how to _revalidate the Server Component_, so if it refetches the data on the client, causing React to rerender the list of posts, the `Nr of posts: {posts.length}` will end up out of sync.
347​
348This is fine if you set `staleTime: Infinity`, so that React Query never revalidates, but this is probably not what you want if you are using React Query in the first place.
349​
350Using React Query with Server Components makes most sense if:
351​
352- You have an app using React Query and want to migrate to Server Components without rewriting all the data fetching
353- You want a familiar programming paradigm, but want to still sprinkle in the benefits of Server Components where it makes most sense
354- You have some use case that React Query covers, but that your framework of choice does not cover
355​
356It's hard to give general advice on when it makes sense to pair React Query with Server Components and not. **If you are just starting out with a new Server Components app, we suggest you start out with any tools for data fetching your framework provides you with and avoid bringing in React Query until you actually need it.** This might be never, and that's fine, use the right tool for the job!
357​
358If you do use it, a good rule of thumb is to avoid `queryClient.fetchQuery` unless you need to catch errors. If you do use it, don't render its result on the server or pass the result to another component, even a Client Component one.
359​
360From the React Query perspective, treat Server Components as a place to prefetch data, nothing more.
361​
362Of course, it's fine to have Server Components own some data, and Client Components own other, just make sure those two realities don't get out of sync.
363​
364## Streaming with Server Components
365​
366The Next.js app router automatically streams any part of the application that is ready to be displayed to the browser as soon as possible, so finished content can be displayed immediately without waiting for still pending content. It does this along `<Suspense>` boundary lines. Note that if you create a file `loading.tsx`, this automatically creates a `<Suspense>` boundary behind the scenes.
367​
368With the prefetching patterns described above, React Query is perfectly compatible with this form of streaming. As the data for each Suspense boundary resolves, Next.js can render and stream the finished content to the browser. This works even if you are using `useQuery` as outlined above because the suspending actually happens when you `await` the prefetch.
369​
370As of React Query v5.40.0, you don't have to `await` all prefetches for this to work, as `pending` Queries can also be dehydrated and sent to the client. This lets you kick off prefetches as early as possible without letting them block an entire Suspense boundary, and streams the _data_ to the client as the query finishes. This can be useful for example if you want to prefetch some content that is only visible after some user interaction, or say if you want to `await` and render the first page of an infinite query, but start prefetching page 2 without blocking rendering.
371​
372To make this work, we have to instruct the `queryClient` to also `dehydrate` pending Queries. We can do this globally, or by passing that option directly to `dehydrate`.
373​
374We will also need to move the `getQueryClient()` function out of our `app/providers.tsx` file as we want to use it in our server component and our client provider.
375​
376```tsx
377// app/get-query-client.ts
378import {
379 isServer,
380 QueryClient,
381 defaultShouldDehydrateQuery,
382} from '@tanstack/react-query'
383​
384function makeQueryClient() {
385 return new QueryClient({
386 defaultOptions: {
387 queries: {
388 staleTime: 60 * 1000,
389 },
390 dehydrate: {
391 // include pending queries in dehydration
392 shouldDehydrateQuery: (query) =>
393 defaultShouldDehydrateQuery(query) ||
394 query.state.status === 'pending',
395 shouldRedactErrors: (error) => {
396 // We should not catch Next.js server errors
397 // as that's how Next.js detects dynamic pages
398 // so we cannot redact them.
399 // Next.js also automatically redacts errors for us
400 // with better digests.
401 return false
402 },
403 },
404 },
405 })
407​
408let browserQueryClient: QueryClient | undefined = undefined
409​
410export function getQueryClient() {
411 if (isServer) {
412 // Server: always make a new query client
413 return makeQueryClient()
414 } else {
415 // Browser: make a new query client if we don't already have one
416 // This is very important, so we don't re-make a new client if React
417 // suspends during the initial render. This may not be needed if we
418 // have a suspense boundary BELOW the creation of the query client
419 if (!browserQueryClient) browserQueryClient = makeQueryClient()
420 return browserQueryClient
421 }
423```
424​
425> Note: This works in NextJs and Server Components because React can serialize Promises over the wire when you pass them down to Client Components.
426​
427Then, all we need to do is provide a `HydrationBoundary`, but we don't need to `await` prefetches anymore:
428​
429```tsx
430// app/posts/page.tsx
431import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
432import { getQueryClient } from './get-query-client'
433import Posts from './posts'
434​
435// the function doesn't need to be `async` because we don't `await` anything
436export default function PostsPage() {
437 const queryClient = getQueryClient()
438​
439 // look ma, no await
440 queryClient.prefetchQuery({
441 queryKey: ['posts'],
442 queryFn: getPosts,
443 })
444​
445 return (
446 <HydrationBoundary state={dehydrate(queryClient)}>
447 <Posts />
448 </HydrationBoundary>
449 )
451```
452​
453On the client, the Promise will be put into the QueryCache for us. That means we can now call `useSuspenseQuery` inside the `Posts` component to "use" that Promise (which was created on the Server):
454​
455```tsx
456// app/posts/posts.tsx
457'use client'
458​
459export default function Posts() {
460 const { data } = useSuspenseQuery({ queryKey: ['posts'], queryFn: getPosts })
461​
462 // ...
464```
465​
466> Note that you could also `useQuery` instead of `useSuspenseQuery`, and the Promise would still be picked up correctly. However, NextJs won't suspend in that case and the component will render in the `pending` status, which also opts out of server rendering the content.
467​
468If you're using non-JSON data types and serialize the query results on the server, you can specify the `dehydrate.serializeData` and `hydrate.deserializeData` options to serialize and deserialize the data on each side of the boundary to ensure the data in the cache is the same format both on the server and the client:
469​
470```tsx
471// app/get-query-client.ts
472import { QueryClient, defaultShouldDehydrateQuery } from '@tanstack/react-query'
473import { deserialize, serialize } from './transformer'
474​
475function makeQueryClient() {
476 return new QueryClient({
477 defaultOptions: {
478 // ...
479 hydrate: {
480 deserializeData: deserialize,
481 },
482 dehydrate: {
483 serializeData: serialize,
484 },
485 },
486 })
488​
489// ...
490```
491​
492```tsx
493// app/posts/page.tsx
494import {
495 dehydrate,
496 HydrationBoundary,
497 QueryClient,
498} from '@tanstack/react-query'
499import { getQueryClient } from './get-query-client'
500import { serialize } from './transformer'
501import Posts from './posts'
502​
503export default function PostsPage() {
504 const queryClient = getQueryClient()
505​
506 // look ma, no await
507 queryClient.prefetchQuery({
508 queryKey: ['posts'],
509 queryFn: () => getPosts().then(serialize), // <-- serialize the data on the server
510 })
511​
512 return (
513 <HydrationBoundary state={dehydrate(queryClient)}>
514 <Posts />
515 </HydrationBoundary>
516 )
518```
519​
520```tsx
521// app/posts/posts.tsx
522'use client'
523​
524export default function Posts() {
525 const { data } = useSuspenseQuery({ queryKey: ['posts'], queryFn: getPosts })
526​
527 // ...
529```
530​
531Now, your `getPosts` function can return e.g. `Temporal` datetime objects and the data will be serialized and deserialized on the client, assuming your transformer can serialize and deserialize those data types.
532​
533For more information, check out the [Next.js App with Prefetching Example](../../examples/nextjs-app-prefetching).
534​
535## Experimental streaming without prefetching in Next.js
536​
537While we recommend the prefetching solution detailed above because it flattens request waterfalls both on the initial page load **and** any subsequent page navigation, there is an experimental way to skip prefetching altogether and still have streaming SSR work: `@tanstack/react-query-next-experimental`
538​
539This package will allow you to fetch data on the server (in a Client Component) by just calling `useSuspenseQuery` in your component. Results will then be streamed from the server to the client as SuspenseBoundaries resolve. If you call `useSuspenseQuery` without wrapping it in a `<Suspense>` boundary, the HTML response won't start until the fetch resolves. This can be when you want depending on the situation, but keep in mind that this will hurt your TTFB.
540​
541To achieve this, wrap your app in the `ReactQueryStreamedHydration` component:
542​
543```tsx
544// app/providers.tsx
545'use client'
546​
547import {
548 isServer,
549 QueryClient,
550 QueryClientProvider,
551} from '@tanstack/react-query'
552import * as React from 'react'
553import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
554​
555function makeQueryClient() {
556 return new QueryClient({
557 defaultOptions: {
558 queries: {
559 // With SSR, we usually want to set some default staleTime
560 // above 0 to avoid refetching immediately on the client
561 staleTime: 60 * 1000,
562 },
563 },
564 })
566​
567let browserQueryClient: QueryClient | undefined = undefined
568​
569function getQueryClient() {
570 if (isServer) {
571 // Server: always make a new query client
572 return makeQueryClient()
573 } else {
574 // Browser: make a new query client if we don't already have one
575 // This is very important, so we don't re-make a new client if React
576 // suspends during the initial render. This may not be needed if we
577 // have a suspense boundary BELOW the creation of the query client
578 if (!browserQueryClient) browserQueryClient = makeQueryClient()
579 return browserQueryClient
580 }
582​
583export function Providers(props: { children: React.ReactNode }) {
584 // NOTE: Avoid useState when initializing the query client if you don't
585 // have a suspense boundary between this and the code that may
586 // suspend because React will throw away the client on the initial
587 // render if it suspends and there is no boundary
588 const queryClient = getQueryClient()
589​
590 return (
591 <QueryClientProvider client={queryClient}>
592 <ReactQueryStreamedHydration>
593 {props.children}
594 </ReactQueryStreamedHydration>
595 </QueryClientProvider>
596 )
598```
599​
600For more information, check out the [NextJs Suspense Streaming Example](../../examples/nextjs-suspense-streaming).
601​
602The big upside is that you no longer need to prefetch queries manually to have SSR work, and it even still streams in the result! This gives you phenomenal DX and lower code complexity.
603​
604The downside is easiest to explain if we look back at [the complex request waterfall example](../request-waterfalls.md#code-splitting) in the Performance & Request Waterfalls guide. Server Components with prefetching effectively eliminates the request waterfalls both for the initial page load **and** any subsequent navigation. This prefetch-less approach however will only flatten the waterfalls on the initial page load but ends up the same deep waterfall as the original example on page navigations:
605​
606```
6071. |> JS for <Feed>
6082. |> getFeed()
6093. |> JS for <GraphFeedItem>
6104. |> getGraphDataById()
611```
612​
613This is even worse than with `getServerSideProps`/`getStaticProps`, since with those we could at least parallelize data- and code-fetching.
614​
615If you value DX/iteration/shipping speed with low code complexity over performance, don't have deeply nested queries, or are on top of your request waterfalls with parallel fetching using tools like `useSuspenseQueries`, this can be a good tradeoff.
616​
617> It might be possible to combine the two approaches, but even we haven't tried that out yet. If you do try this, please report back your findings, or even update these docs with some tips!
618​
619## Final words
620​
621Server Components and streaming are still fairly new concepts and we are still figuring out how React Query fits in and what improvements we can make to the API. We welcome suggestions, feedback and bug reports!
622​
623Similarly, it would be impossible to teach all the intricacies of this new paradigm all in one guide, on the first try. If you are missing some piece of information here or have suggestions on how to improve this content, also get in touch, or even better, click the "Edit on GitHub" button below and help us out.