Open History to see the last commit
1---
2id: ssr
3title: SSR
4---
5β
6Vue 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.
7β
8## Using Nuxt.js
9β
10### Nuxt 3
11β
12First create `vue-query.ts` file in your `plugins` directory with the following content:
13β
14```ts
15import type {
16 DehydratedState,
17 VueQueryPluginOptions,
18} from '@tanstack/vue-query'
19import {
20 VueQueryPlugin,
21 QueryClient,
22 hydrate,
23 dehydrate,
24} from '@tanstack/vue-query'
25// Nuxt 3 app aliases
26import { defineNuxtPlugin, useState } from '#imports'
27β
28export default defineNuxtPlugin((nuxt) => {
29 const vueQueryState = useState<DehydratedState | null>('vue-query')
30β
31 // Modify your Vue Query global settings here
32 const queryClient = new QueryClient({
33 defaultOptions: { queries: { staleTime: 5000 } },
34 })
35 const options: VueQueryPluginOptions = { queryClient }
36β
37 nuxt.vueApp.use(VueQueryPlugin, options)
38β
39 if (import.meta.server) {
40 nuxt.hooks.hook('app:rendered', () => {
41 vueQueryState.value = dehydrate(queryClient)
42 })
43 }
44β
45 if (import.meta.client) {
46 hydrate(queryClient, vueQueryState.value)
47 }
48})
49```
50β
51Now you are ready to prefetch some data in your pages with `onServerPrefetch`.
52β
53- Prefetch all the queries that you need with `queryClient.prefetchQuery` or `suspense`
54β
55```ts
56export default defineComponent({
57 setup() {
58 const { data, suspense } = useQuery({
59 queryKey: ['test'],
60 queryFn: fetcher,
61 })
62β
63 onServerPrefetch(async () => {
64 await suspense()
65 })
66β
67 return { data }
68 },
69})
70```
71β
72### Nuxt 2
73β
74First create `vue-query.js` file in your `plugins` directory with the following content:
75β
76```js
77import Vue from 'vue'
78import { VueQueryPlugin, QueryClient, hydrate } from '@tanstack/vue-query'
79β
80export default (context) => {
81 // Modify your Vue Query global settings here
82 const queryClient = new QueryClient({
83 defaultOptions: { queries: { staleTime: 5000 } },
84 })
85β
86 if (process.server) {
87 context.ssrContext.VueQuery = queryClient
88 }
89β
90 if (process.client) {
91 Vue.use(VueQueryPlugin, { queryClient })
92β
93 if (context.nuxtState && context.nuxtState.vueQueryState) {
94 hydrate(queryClient, context.nuxtState.vueQueryState)
95 }
96 }
97}
98```
99β
100Add this plugin to your `nuxt.config.js`
101β
102```js
103module.exports = {
104 ...
105 plugins: ['~/plugins/vue-query.js'],
106}
107```
108β
109Now you are ready to prefetch some data in your pages with `onServerPrefetch`.
110β
111- Use `useContext` to get nuxt context
112- Use `useQueryClient` to get server-side instance of `queryClient`
113- Prefetch all the queries that you need with `queryClient.prefetchQuery` or `suspense`
114- Dehydrate `queryClient` to the `nuxtContext`
115β
116```vue
117// pages/todos.vue
118<template>
119 <div>
120 <button @click="refetch">Refetch</button>
121 <p>{{ data }}</p>
122 </div>
123</template>
124β
125<script lang="ts">
126import {
127 defineComponent,
128 onServerPrefetch,
129 useContext,
130} from '@nuxtjs/composition-api'
131import { useQuery, useQueryClient, dehydrate } from '@tanstack/vue-query'
132β
133export default defineComponent({
134 setup() {
135 // Get QueryClient either from SSR context, or Vue context
136 const { ssrContext } = useContext()
137 // Make sure to provide `queryClient` as a second parameter to `useQuery` calls
138 const queryClient =
139 (ssrContext != null && ssrContext.VueQuery) || useQueryClient()
140β
141 // This will be prefetched and sent from the server
142 const { data, refetch, suspense } = useQuery(
143 {
144 queryKey: ['todos'],
145 queryFn: getTodos,
146 },
147 queryClient,
148 )
149 // This won't be prefetched, it will start fetching on client side
150 const { data2 } = useQuery(
151 {
152 queryKey: 'todos2',
153 queryFn: getTodos,
154 },
155 queryClient,
156 )
157β
158 onServerPrefetch(async () => {
159 await suspense()
160 ssrContext.nuxt.vueQueryState = dehydrate(queryClient)
161 })
162β
163 return {
164 refetch,
165 data,
166 }
167 },
168})
169</script>
170```
171β
172As 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` or `suspense` for a specific query.
173β
174## Using Vite SSR
175β
176Sync VueQuery client state with [vite-ssr](https://github.com/frandiox/vite-ssr) in order to serialize it in the DOM:
177β
178```js
179// main.js (entry point)
180import App from './App.vue'
181import viteSSR from 'vite-ssr/vue'
182import {
183 QueryClient,
184 VueQueryPlugin,
185 hydrate,
186 dehydrate,
187} from '@tanstack/vue-query'
188β
189export default viteSSR(App, { routes: [] }, ({ app, initialState }) => {
190 // -- This is Vite SSR main hook, which is called once per request
191β
192 // Create a fresh VueQuery client
193 const queryClient = new QueryClient()
194β
195 // Sync initialState with the client state
196 if (import.meta.env.SSR) {
197 // Indicate how to access and serialize VueQuery state during SSR
198 initialState.vueQueryState = { toJSON: () => dehydrate(queryClient) }
199 } else {
200 // Reuse the existing state in the browser
201 hydrate(queryClient, initialState.vueQueryState)
202 }
203β
204 // Mount and provide the client to the app components
205 app.use(VueQueryPlugin, { queryClient })
206})
207```
208β
209Then, call VueQuery from any component using Vue's `onServerPrefetch`:
210β
211```html
212<!-- MyComponent.vue -->
213<template>
214 <div>
215 <button @click="refetch">Refetch</button>
216 <p>{{ data }}</p>
217 </div>
218</template>
219β
220<script setup>
221 import { useQuery } from '@tanstack/vue-query'
222 import { onServerPrefetch } from 'vue'
223β
224 // This will be prefetched and sent from the server
225 const { refetch, data, suspense } = useQuery({
226 queryKey: ['todos'],
227 queryFn: getTodos,
228 })
229β
230 onServerPrefetch(suspense)
231</script>
232```
233β
234## Tips, Tricks and Caveats
235β
236### Only successful queries are included in dehydration
237β
238Any 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.
239β
240Sometimes 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.
241β
242### Staleness is measured from when the query was fetched on the server
243β
244A 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.
245β
246Because `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.
247β
248This 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?
249β
250### High memory consumption on server
251β
252In 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.
253β
254On 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.
255β
256To 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.
257β
258Alternatively, you can set a smaller `gcTime`.