Open History to see the last commit
1---
2id: ssr
3title: SSR
4redirect_from:
5 - framework/vue/reference/hydration
6---
7β
8Vue Query supports prefetching multiple queries on the server 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, Vue 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.
9β
10## Using Nuxt.js
11β
12### Nuxt 3
13β
14First create `vue-query.ts` file in your `plugins` directory with the following content:
15β
16```ts
17import type {
18 DehydratedState,
19 VueQueryPluginOptions,
20} from '@tanstack/vue-query'
21import {
22 VueQueryPlugin,
23 QueryClient,
24 hydrate,
25 dehydrate,
26} from '@tanstack/vue-query'
27// Nuxt 3 app aliases
28import { defineNuxtPlugin, useState } from '#imports'
29β
30export default defineNuxtPlugin((nuxt) => {
31 const vueQueryState = useState<DehydratedState | null>('vue-query')
32β
33 // Modify your Vue Query global settings here
34 const queryClient = new QueryClient({
35 defaultOptions: { queries: { staleTime: 5 * 1000 } },
36 })
37 const options: VueQueryPluginOptions = { queryClient }
38β
39 nuxt.vueApp.use(VueQueryPlugin, options)
40β
41 if (import.meta.server) {
42 nuxt.hooks.hook('app:rendered', () => {
43 vueQueryState.value = dehydrate(queryClient)
44 })
45 }
46β
47 if (import.meta.client && vueQueryState.value !== null) {
48 hydrate(queryClient, vueQueryState.value)
49 }
50})
51```
52β
53Now you are ready to prefetch some data in your pages with `onServerPrefetch`.
54β
55- Prefetch all the queries that you need with `queryClient.query`, `queryClient.infiniteQuery`, or `suspense`
56β
57```ts
58export default defineComponent({
59 setup() {
60 const { data, suspense } = useQuery({
61 queryKey: ['test'],
62 queryFn: fetcher,
63 })
64β
65 onServerPrefetch(async () => {
66 await suspense()
67 })
68β
69 return { data }
70 },
71})
72```
73β
74### Nuxt 2
75β
76First create `vue-query.js` file in your `plugins` directory with the following content:
77β
78```js
79import Vue from 'vue'
80import { VueQueryPlugin, QueryClient, hydrate } from '@tanstack/vue-query'
81β
82export default (context) => {
83 // Modify your Vue Query global settings here
84 const queryClient = new QueryClient({
85 defaultOptions: { queries: { staleTime: 5 * 1000 } },
86 })
87β
88 if (process.server) {
89 context.ssrContext.VueQuery = queryClient
90 }
91β
92 if (process.client) {
93 Vue.use(VueQueryPlugin, { queryClient })
94β
95 if (context.nuxtState && context.nuxtState.vueQueryState) {
96 hydrate(queryClient, context.nuxtState.vueQueryState)
97 }
98 }
99}
100```
101β
102Add this plugin to your `nuxt.config.js`
103β
104```js
105module.exports = {
106 ...
107 plugins: ['~/plugins/vue-query.js'],
108}
109```
110β
111Now you are ready to prefetch some data in your pages with `onServerPrefetch`.
112β
113- Use `useContext` to get nuxt context
114- Use `useQueryClient` to get server-side instance of `queryClient`
115- Prefetch all the queries that you need with `queryClient.query`, `queryClient.infiniteQuery`, or `suspense`
116- Dehydrate `queryClient` to the `nuxtContext`
117β
118```vue
119// pages/todos.vue
120<template>
121 <div>
122 <button @click="refetch">Refetch</button>
123 <p>{{ data }}</p>
124 </div>
125</template>
126β
127<script lang="ts">
128import {
129 defineComponent,
130 onServerPrefetch,
131 useContext,
132} from '@nuxtjs/composition-api'
133import { useQuery, useQueryClient, dehydrate } from '@tanstack/vue-query'
134β
135export default defineComponent({
136 setup() {
137 // Get QueryClient either from SSR context, or Vue context
138 const { ssrContext } = useContext()
139 // Make sure to provide `queryClient` as a second parameter to `useQuery` calls
140 const queryClient =
141 (ssrContext != null && ssrContext.VueQuery) || useQueryClient()
142β
143 // This will be prefetched and sent from the server
144 const { data, refetch, suspense } = useQuery(
145 {
146 queryKey: ['todos'],
147 queryFn: getTodos,
148 },
149 queryClient,
150 )
151 // This won't be prefetched, it will start fetching on client side
152 const { data: data2 } = useQuery(
153 {
154 queryKey: ['todos2'],
155 queryFn: getTodos,
156 },
157 queryClient,
158 )
159β
160 onServerPrefetch(async () => {
161 await suspense()
162 ssrContext.nuxt.vueQueryState = dehydrate(queryClient)
163 })
164β
165 return {
166 refetch,
167 data,
168 }
169 },
170})
171</script>
172```
173β
174As 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 `queryClient.query` or `suspense` for a specific query.
175β
176## Using Vite SSR
177β
178Sync VueQuery client state with [vite-ssr](https://github.com/frandiox/vite-ssr) in order to serialize it in the DOM:
179β
180```js
181// main.js (entry point)
182import App from './App.vue'
183import viteSSR from 'vite-ssr/vue'
184import {
185 QueryClient,
186 VueQueryPlugin,
187 hydrate,
188 dehydrate,
189} from '@tanstack/vue-query'
190β
191export default viteSSR(App, { routes: [] }, ({ app, initialState }) => {
192 // -- This is Vite SSR main hook, which is called once per request
193β
194 // Create a fresh VueQuery client
195 const queryClient = new QueryClient()
196β
197 // Sync initialState with the client state
198 if (import.meta.env.SSR) {
199 // Indicate how to access and serialize VueQuery state during SSR
200 initialState.vueQueryState = { toJSON: () => dehydrate(queryClient) }
201 } else {
202 // Reuse the existing state in the browser
203 hydrate(queryClient, initialState.vueQueryState)
204 }
205β
206 // Mount and provide the client to the app components
207 app.use(VueQueryPlugin, { queryClient })
208})
209```
210β
211Then, call VueQuery from any component using Vue's `onServerPrefetch`:
212β
213```vue
214<!-- MyComponent.vue -->
215<template>
216 <div>
217 <button @click="refetch">Refetch</button>
218 <p>{{ data }}</p>
219 </div>
220</template>
221β
222<script setup>
223import { useQuery } from '@tanstack/vue-query'
224import { onServerPrefetch } from 'vue'
225β
226// This will be prefetched and sent from the server
227const { refetch, data, suspense } = useQuery({
228 queryKey: ['todos'],
229 queryFn: getTodos,
230})
231β
232onServerPrefetch(suspense)
233</script>
234```
235β
236## Tips, Tricks and Caveats
237β
238### Only successful queries are included in dehydration
239β
240Any 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.
241β
242Sometimes 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 `queryClient.query` and catch any errors to handle those manually.
243β
244### Staleness is measured from when the query was fetched on the server
245β
246A 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.
247β
248Because `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.
249β
250This 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?
251β
252### `suspense()` of a query that stays disabled blocks the render on the server
253β
254`suspense()` waits until the query is enabled, so it never resolves for a query that stays disabled. On the server, awaiting it in `onServerPrefetch` for such a query (for example, a dependent query whose dependency failed) blocks the render. Skip it when the query is disabled:
255β
256```vue
257<script setup>
258import { computed, onServerPrefetch } from 'vue'
259import { useQuery } from '@tanstack/vue-query'
260β
261const { data: user, suspense: userSuspense } = useQuery({
262 queryKey: ['user'],
263 queryFn: getUser,
264})
265β
266const userId = computed(() => user.value?.id)
267const enabled = computed(() => !!user.value?.id)
268const { data: projects, suspense: projectsSuspense } = useQuery({
269 queryKey: ['projects', userId],
270 queryFn: () => getProjectsByUser(userId.value),
271 enabled,
272})
273β
274onServerPrefetch(async () => {
275 await userSuspense()
276 if (enabled.value) {
277 await projectsSuspense()
278 }
279})
280</script>
281```
282β
283### High memory consumption on server
284β
285In case you are creating the `QueryClient` for every request, Vue 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.
286β
287On 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.
288β
289To 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.
290β
291## `dehydrate`/`hydrate` options
292β
293`dehydrate` and `hydrate` are re-exported from `@tanstack/query-core`, so they're available directly from `@tanstack/vue-query` β as used throughout this guide.
294β
295`dehydrate(client, options?)` accepts a `DehydrateOptions` object:
296β
297- `shouldDehydrateMutation: (mutation) => boolean` β whether to dehydrate a given mutation. Called for each mutation in the cache; defaults to only including paused mutations. To extend the default behavior instead of replacing it, import and call `defaultShouldDehydrateMutation` as part of your return statement.
298- `shouldDehydrateQuery: (query) => boolean` β whether to dehydrate a given query. Called for each query in the cache; defaults to only including successful queries (see [above](#only-successful-queries-are-included-in-dehydration)). Extend it the same way, with `defaultShouldDehydrateQuery`.
299- `serializeData?: (data) => any` β transforms (serializes) data during dehydration.
300- `shouldRedactErrors?: (error) => boolean` β only applies to queries still `pending` at dehydration time, whose promise is dehydrated too: decides whether to redact the error if that promise later rejects. Defaults to redacting all such errors. Does **not** apply to `query.state.error` on already-settled queries β that error is included in the dehydrated state as-is, so sanitize it yourself via `shouldDehydrateQuery` if it may contain sensitive data.
301β
302`hydrate(client, dehydratedState, options?)` accepts a `HydrateOptions` object:
303β
304- `defaultOptions.mutations` β default mutation options for the hydrated mutations.
305- `defaultOptions.queries` β default query options for the hydrated queries.
306- `defaultOptions.deserializeData?: (data) => any` β transforms (deserializes) data before it's put into the cache.
307β
308One caveat with `hydrate`: if a query being hydrated already exists in the cache, it's only overwritten when the incoming data is newer than what's already there β otherwise it's silently skipped.
309β
310Alternatively, you can set a smaller `gcTime`.