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

advanced-ssr.md

389 lines19.0 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](../guides/ssr) before this one as it teaches the basics for using React Query with SSR, and [Performance & Request Waterfalls](../guides/request-waterfalls) as well as [Prefetching & Router Integration](../guides/prefetching) 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](../guides/ssr#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.jsx
30'use client'
31​
32// We can not useState or useRef in a server component, which is why we are
33// extracting this part out into it's own file with 'use client' on top
34import { useState } from 'react'
35import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
36​
37export default function Providers({ children }) {
38 const [queryClient] = useState(
39 () =>
40 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 }),
49 )
50​
51 return (
52 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
53 )
55```
56​
57```tsx
58// In Next.js, this file would be called: app/layout.jsx
59import Providers from './providers'
60​
61export default function RootLayout({ children }) {
62 return (
63 <html lang="en">
64 <head />
65 <body>
66 <Providers>{children}</Providers>
67 </body>
68 </html>
69 )
71```
72​
73This part is pretty similar to what we did in the SSR guide, we just need to split things up into two different files.
74​
75### Prefetching and de/hydrating data
76​
77Let's next look at how to actually prefetch data and dehydrate and hydrate it. This is what it looked like using the **Next.js pages router**:
78​
79```tsx
80// pages/posts.jsx
81import { dehydrate, HydrationBoundary, QueryClient, useQuery } from '@tanstack/react-query'
82​
83// This could also be getServerSideProps
84export async function getStaticProps() {
85 const queryClient = new QueryClient()
86​
87 await queryClient.prefetchQuery({
88 queryKey: ['posts'],
89 queryFn: getPosts,
90 })
91​
92 return {
93 props: {
94 dehydratedState: dehydrate(queryClient),
95 },
96 }
98​
99function Posts() {
100 // This useQuery could just as well happen in some deeper child to
101 // the <PostsRoute>, data will be available immediately either way
102 //
103 // Note that we are using useQuery here instead of useSuspenseQuery.
104 // Because this data has already been prefetched, there is no need to
105 // ever suspend in the component itself. If we forget or remove the
106 // prefetch, this will instead fetch the data on the client, while
107 // using useSuspenseQuery would have had worse side effects.
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: commentsData } = useQuery({
113 queryKey: ['posts-comments'],
114 queryFn: getComments,
115 })
116​
117 // ...
119​
120export default PostsRoute({ dehydratedState }) {
121 return (
122 <HydrationBoundary state={dehydratedState}>
123 <Posts />
124 </HydrationBoundary>
125 )
127```
128​
129Converting 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:
130​
131```tsx
132// app/posts/page.jsx
133import {
134 dehydrate,
135 HydrationBoundary,
136 QueryClient,
137} from '@tanstack/react-query'
138import Posts from './posts'
139​
140export default async function PostsPage() {
141 const queryClient = new QueryClient()
142​
143 await queryClient.prefetchQuery({
144 queryKey: ['posts'],
145 queryFn: getPosts,
146 })
147​
148 return (
149 // Neat! Serialization is now as easy as passing props.
150 // HydrationBoundary is a Client Component, so hydration will happen there.
151 <HydrationBoundary state={dehydrate(queryClient)}>
152 <Posts />
153 </HydrationBoundary>
154 )
156```
157​
158Next, we'll look at what the Client Component part looks like:
159​
160```tsx
161// app/posts/posts.jsx
162'use client'
163​
164export default function Posts() {
165 // This useQuery could just as well happen in some deeper
166 // child to <Posts>, data will be available immediately either way
167 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
168​
169 // This query was not prefetched on the server and will not start
170 // fetching until on the client, both patterns are fine to mix.
171 const { data: commentsData } = useQuery({
172 queryKey: ['posts-comments'],
173 queryFn: getComments,
174 })
175​
176 // ...
178```
179​
180One 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.
181​
182In 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.
183​
184> 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.
185​
186### Nesting Server Components
187​
188A 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):
189​
190```tsx
191// app/posts/page.jsx
192import {
193 dehydrate,
194 HydrationBoundary,
195 QueryClient,
196} from '@tanstack/react-query'
197import Posts from './posts'
198import CommentsServerComponent from './comments-server'
199​
200export default async function PostsPage() {
201 const queryClient = new QueryClient()
202​
203 await queryClient.prefetchQuery({
204 queryKey: ['posts'],
205 queryFn: getPosts,
206 })
207​
208 return (
209 <HydrationBoundary state={dehydrate(queryClient)}>
210 <Posts />
211 <CommentsServerComponent />
212 </HydrationBoundary>
213 )
215​
216// app/posts/comments-server.jsx
217import {
218 dehydrate,
219 HydrationBoundary,
220 QueryClient,
221} from '@tanstack/react-query'
222import Comments from './comments'
223​
224export default async function CommentsServerComponent() {
225 const queryClient = new QueryClient()
226​
227 await queryClient.prefetchQuery({
228 queryKey: ['posts-comments'],
229 queryFn: getComments,
230 })
231​
232 return (
233 <HydrationBoundary state={dehydrate(queryClient)}>
234 <Comments />
235 </HydrationBoundary>
236 )
238```
239​
240As you can see, it's perfectly fine to use `<HydrationBoundary>` in multiple places, and create and dehydrate multiple `queryClient` for prefetching.
241​
242Note that because we are awaiting `getPosts` before rendering `CommentsServerComponent` this would lead to a server side waterfall:
243​
244```
2451. |> getPosts()
2462. |> getComments()
247```
248​
249If the server latency to the data is low, this might not be a huge issue, but is still worth pointing out.
250​
251In 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.
252​
253As more frameworks start supporting Server Components, they might have other routing conventions. Read your framework docs for details.
254​
255### Alternative: Use a single `queryClient` for prefetching
256​
257In 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:
258​
259```tsx
260// app/getQueryClient.jsx
261import { QueryClient } from '@tanstack/react-query'
262import { cache } from 'react'
263​
264// cache() is scoped per request, so we don't leak data between requests
265const getQueryClient = cache(() => new QueryClient())
266export default getQueryClient
267```
268​
269The 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.
270​
271Next.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.
272​
273> 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!
274​
275### Data ownership and revalidation
276​
277With Server Components, it's important to think about data ownership and revalidation. To explain why, let's look at a modified example from above:
278​
279```tsx
280// app/posts/page.jsx
281import {
282 dehydrate,
283 HydrationBoundary,
284 QueryClient,
285} from '@tanstack/react-query'
286import Posts from './posts'
287​
288export default async function PostsPage() {
289 const queryClient = new QueryClient()
290​
291 // Note we are now using fetchQuery()
292 const posts = await queryClient.fetchQuery({
293 queryKey: ['posts'],
294 queryFn: getPosts,
295 })
296​
297 return (
298 <HydrationBoundary state={dehydrate(queryClient)}>
299 {/* This is the new part */}
300 <div>Nr of posts: {posts.length}</div>
301 <Posts />
302 </HydrationBoundary>
303 )
305```
306​
307We 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?
308​
309React 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.
310​
311This 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.
312​
313Using React Query with Server Components makes most sense if:
314​
315- You have an app using React Query and want to migrate to Server Components without rewriting all the data fetching
316- You want a familiar programming paradigm, but want to still sprinkle in the benefits of Server Components where it makes most sense
317- You have some use case that React Query covers, but that your framework of choice does not cover
318​
319It'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!
320​
321If 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.
322​
323From the React Query perspective, treat Server Components as a place to prefetch data, nothing more.
324​
325Of 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.
326​
327## Streaming with Server Components
328​
329The 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.
330​
331With 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.
332​
333Note that right now, you have to await all prefetches for this to work. This means all prefetches are considered critical content and will block that Suspense boundary.
334​
335As an aside, in the future it might be possible to skip the await for "optional" prefetches that are not critical for this Suspense boundary. This would let you kick off prefetches as early as possible without letting them block an entire Suspense boundary, and streaming the _data_ to the client as the query finishes. This could 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.
336​
337## Experimental streaming without prefetching in Next.js
338​
339While 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`
340​
341This 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. Note that all calls to `useSuspenseQuery` must be wrapped in a `<Suspense>` boundary somewhere further up the tree to work.
342​
343To achieve this, wrap your app in the `ReactQueryStreamedHydration` component:
344​
345```tsx
346// app/providers.tsx
347'use client'
348​
349import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
350import * as React from 'react'
351import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
352​
353export function Providers(props: { children: React.ReactNode }) {
354 const [queryClient] = React.useState(() => new QueryClient())
355​
356 return (
357 <QueryClientProvider client={queryClient}>
358 <ReactQueryStreamedHydration>
359 {props.children}
360 </ReactQueryStreamedHydration>
361 </QueryClientProvider>
362 )
364```
365​
366For more information, check out the [NextJs Suspense Streaming Example](../examples/react/nextjs-suspense-streaming).
367​
368The 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.
369​
370The downside is easiest to explain if we look back at [the complex request waterfall example](../guides/request-waterfalls#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:
371​
372```
3731. |> JS for <Feed>
3742. |> getFeed()
3753. |> JS for <GraphFeedItem>
3764. |> getGraphDataById()
377```
378​
379This is even worse than with `getServerSideProps`/`getStaticProps`, since with those we could at least parallelize data- and code-fetching.
380​
381If you value DX, iteration/shipping speed and low code complexity over performance, or don't have deeply nested queries and you know you are on top of your request waterfalls anyway, this can be a good tradeoff.
382​
383> 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!
384​
385## Final words
386​
387Server 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!
388​
389Similarly, 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.