| | |

Vue Query 12 ⚡ Prefetching, SSR & Nuxt Integration — Improving perceived performance with prefetchQuery and dehydrate/hydrate in SSR

⏱️ Estimated read: 11 min | |

In a standard Single Page Application (SPA), the browser downloads a nearly empty HTML file, fetches JavaScript, and only then starts requesting data from the API. This results in the ubiquitous “loading spinner” experience. To move beyond this, Vue Query provides powerful tools for prefetching data and integrating with Server-Side Rendering (SSR). By fetching data before it is strictly needed—either on the server or on the client during user idle time—applications can render content immediately, providing a seamless transition from the initial request to a fully interactive state.

The core of this capability lies in the “Dehydration” and “Hydration” cycle. On the server, Vue Query populates a cache, “dehydrates” it into a serializable JSON object, and embeds it into the HTML. When the client-side JavaScript takes over, it “hydrates” this data back into its own memory cache. This allows the useQuery hooks in your components to find the data they need instantly, preventing unnecessary network calls and layout shifts during the initial page load.

This chapter covers the implementation of prefetchQuery for anticipatory fetching, the architecture of SSR data transfer using the QueryClient, and the specific patterns required for Nuxt 3 integration. We will explore how to manage cache consistency across the network boundary and how to use prefetching to create “instant-feel” navigation by loading data as users hover over links.

Key point: SSR and prefetching in Vue Query work by transferring a serialized snapshot of the server-side cache to the client-side QueryClient, allowing components to skip their initial loading states and render with data immediately upon hydration.


Why exists

The Empty Shell problem. Standard SPAs show a blank screen or a spinner while waiting for the first API call. This is bad for user retention and even worse for perceived performance. SSR ensures the user sees the actual content in the very first byte of HTML.

The SEO and Crawlability problem. Search engine bots and social media crawlers often struggle with JavaScript-heavy applications. By prefetching and rendering on the server, you ensure that the HTML contains the actual data (titles, descriptions, product info), which is essential for indexing.

The Hover-to-Load strategy. Users often signal intent before they click. If a user hovers over a link, prefetching that data during those few hundred milliseconds of idle time can make the subsequent page transition feel instantaneous.

The Data-Double-Fetch problem. Without a hydration strategy, the server would fetch the data to render the HTML, and then the client would fetch the exact same data again once the component mounts. Hydration allows the client to “take over” where the server left off.

The Latency Gap. Mobile users on high-latency networks suffer most from waterfalls (requesting JS, then requesting data). Prefetching and SSR collapse these steps, delivering data and structure in a single round trip.


a. Anticipatory Fetching with prefetchQuery

Prefetching is the act of fetching data before it is requested by a component via useQuery. This is typically done in response to a user action (like hovering over a link) or as a background task. The prefetchQuery method lives on the QueryClient instance. If the data is already in the cache and not stale, it won’t fetch it again; otherwise, it will trigger a network request and store the result.

const queryClient = useQueryClient();

const prefetchUser = async (id: string) => {
  // Data will be fetched and stored in the cache
  await queryClient.prefetchQuery({
    queryKey: ['user', id],
    queryFn: () => fetchUser(id),
    staleTime: 60 * 1000, // Optional: consider data fresh for 1 min
  });
};

In a component, you can trigger this during an @mouseenter event. Because useQuery and prefetchQuery share the same cache key, when the user finally clicks the link and the new component calls useQuery(['user', id]), the data is already waiting for them in the cache, resulting in an immediate render.


b. SSR Architecture: Dehydration and Hydration

To support SSR, Vue Query uses a two-step process to sync state between the server and the client. First, the server-side QueryClient fetches data. Once the fetches are complete, we use the dehydrate function to create a “frozen” version of the cache. This snapshot is injected into the HTML (usually as a global variable like window.__QUERY_STATE__).

// On the Server
import { dehydrate, QueryClient } from '@tanstack/vue-query';

const queryClient = new QueryClient();
await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: fetchPosts });
const dehydratedState = dehydrate(queryClient);

On the client side, during the application initialization, we check for this state and use the hydrate function to “melt” it back into the client-side QueryClient. This must happen before the app is mounted to ensure components find the data during their first render cycle.

// On the Client
import { hydrate, QueryClient } from '@tanstack/vue-query';

const queryClient = new QueryClient();
if (window.__QUERY_STATE__) {
  hydrate(queryClient, window.__QUERY_STATE__);
}

This synchronization is transparent to the components. A component using useQuery(['posts']) doesn’t know if the data came from a fresh network request or from a hydrated server cache; it simply receives the data and moves from a pending state to success.


c. Nuxt 3 Integration

Nuxt 3 simplifies the SSR process significantly by providing built-in composables for server-side execution. When using @tanstack/vue-query with Nuxt, we typically use a plugin to manage the QueryClient lifecycle and ensure that the state is properly serialized across the nitro server and the browser.

In a Nuxt page, you can use onServerPrefetch (a Vue 3 lifecycle hook) to ensure the server waits for the data before sending the HTML response.

// pages/posts.vue
import { useQuery, useQueryClient } from '@tanstack/vue-query';

const queryClient = useQueryClient();

// Ensure server waits for this fetch
onServerPrefetch(async () => {
  await queryClient.prefetchQuery({ 
    queryKey: ['posts'], 
    queryFn: () => $fetch('/api/posts') 
  });
});

const { data } = useQuery({ 
  queryKey: ['posts'], 
  queryFn: () => $fetch('/api/posts') 
});

Nuxt handles the dehydration and hydration automatically if the @tanstack/vue-query plugin is configured to use Nuxt’s useState or useNuxtApp payload. This ensures that the QueryClient is unique to every request on the server, preventing data leakage between different users, while remaining persistent on the client.


Complete Example Session

// ============================================
// PART 1: THE SHARED FETCH LOGIC
// ============================================
export const getProduct = (id: string) => 
  fetch(`https://api.example.com/products/${id}`).then(res => res.json());

// ============================================
// PART 2: NUXT/SSR PLUGIN SETUP (Simplified)
// ============================================
// plugins/vue-query.ts
import { VueQueryPlugin, QueryClient, dehydrate, hydrate } from '@tanstack/vue-query';

export default defineNuxtPlugin((nuxtApp) => {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { staleTime: 5000 } }
  });

  nuxtApp.vueApp.use(VueQueryPlugin, { queryClient });

  if (process.server) {
    nuxtApp.hooks.hook('app:rendered', () => {
      nuxtApp.payload.queryState = dehydrate(queryClient);
    });
  }

  if (process.client) {
    hydrate(queryClient, nuxtApp.payload.queryState);
  }
});

// ============================================
// PART 3: PAGE COMPONENT WITH SERVER PREFETCH
// ============================================
// pages/products/[id].vue
/*
<script setup>
import { useQuery, useQueryClient } from '@tanstack/vue-query';
const route = useRoute();
const queryClient = useQueryClient();

// Trigger on server
onServerPrefetch(async () => {
  await queryClient.prefetchQuery({
    queryKey: ['product', route.params.id],
    queryFn: () => getProduct(route.params.id)
  });
});

// useQuery picks up server data instantly on client
const { data: product } = useQuery({
  queryKey: ['product', route.params.id],
  queryFn: () => getProduct(route.params.id)
});
</script>
*/

// ============================================
// PART 4: HOVER PREFETCHING (Anticipatory)
// ============================================
/*
<template>
  <NuxtLink 
    to="/products/123" 
    @mouseenter="prefetchProduct('123')"
  >
    View Detail
  </NuxtLink>
</template>

<script setup>
const prefetchProduct = (id) => {
  queryClient.prefetchQuery({
    queryKey: ['product', id],
    queryFn: () => getProduct(id)
  });
};
</script>
*/

// ============================================
// PART 5: ERROR HANDLING IN PREFETCH
// ============================================
// prefetchQuery does not throw errors by default, it just fails silently
// to prevent crashing the server/app.

// ============================================
// PART 6: DEHYDRATE OPTIONS
// ============================================
// dehydrate(queryClient, { 
//   shouldDehydrateQuery: (query) => query.state.status === 'success' 
// })

// ============================================
// PART 7: STALE TIME DURING HYDRATION
// ============================================
// If staleTime is 0, client will refetch immediately after hydration.
// Always set a staleTime > 0 for SSR data.

// ============================================
// PART 8: PERSISTENCE (Experimental)
// ============================================
// Combining dehydration with localStorage for offline support.

// ============================================
// PART 9: MULTIPLE PREFETCHES
// ============================================
// await Promise.all([ q.prefetchQuery(...), q.prefetchQuery(...) ])

// ============================================
// PART 10: HYDRATION COMPONENT (Vue Alternative)
// ============================================
// Using <VueQueryHydration :state="dehydratedState">

The sequence above illustrates setting up the bridge between server and client, using lifecycle hooks for prefetching, and implementing UX improvements via hover-based loading.


Quick Reference

Key Methods

MethodSourcePurpose
prefetchQueryQueryClientFetch data into cache before it’s needed
fetchQueryQueryClientFetch data and return the result (throws on error)
dehydrate@tanstack/vue-queryConvert cache to a serializable object
hydrate@tanstack/vue-queryInject serialized object into a cache

SSR Process Flow

StepEnvironmentAction
1. RequestServerRoute is matched
2. PrefetchServerprefetchQuery hits API and stores in cache
3. RenderServerVue renders HTML using cache data
4. DehydrateServerCache converted to JSON and sent in HTML
5. HydrateClientClient QueryClient parses JSON into memory
6. RenderClientComponents find data in cache instantly

Best Practices

✅ Do This:

// Set a staleTime for SSR queries to avoid immediate refetch
queryClient.prefetchQuery({ ..., staleTime: 10000 });          // ✅

// Use onServerPrefetch for data essential to SEO
onServerPrefetch(async () => { await prefetch(); });           // ✅

// Trigger prefetch on Hover/Focus for faster transitions
<button @focus="prefetch" @mouseenter="prefetch">              // ✅

// Create a new QueryClient per request on the server
const queryClient = new QueryClient();                         // ✅

❌ Don’t Do This:

// Don't share a single QueryClient across server requests
// (Data leakage risk between users!)                            // ❌

// Don't prefetch huge datasets on hover
// (Waste of user bandwidth if they don't click)               // ❌

// Don't forget to handle hydration on the client
// (App will fetch data again, negating SSR benefits)           // ❌

// Don't prefetch private user data for SSR if not authenticated
// (Security risk)                                             // ❌

Common Pitfalls

PitfallWhy It HappensFix
Client refetches immediatelystaleTime is set to 0 (default)Set staleTime to a reasonable value (e.g. 5m)
Data leakageGlobal QueryClient used on serverInstantiate new QueryClient() inside request scope
Hydration MismatchServer data doesn’t match client HTMLEnsure keys and fetch logic are identical
Server hangsprefetchQuery hanging or too many requestsSet timeouts and limit critical prefetches
Dehydration errorCircular references in API dataEnsure API returns clean JSON

Real-World Examples

1. Hover Prefetch

<a @mouseenter="queryClient.prefetchQuery({ queryKey, queryFn })">Link</a>

2. Nuxt SSR Setup

onServerPrefetch(async () => await queryClient.prefetchQuery(...))

3. Selective Dehydration

dehydrate(client, { shouldDehydrateQuery: q => q.meta.public })

4. Prefetching Next Page

const prefetchNextPage = () => queryClient.prefetchQuery(['posts', page + 1])

5. Nuxt Plugin Hydration

if (process.client) hydrate(queryClient, nuxtApp.payload.queryState)

6. Stale Time for SSR

queryClient.setDefaultOptions({ queries: { staleTime: 1000 * 60 } })

7. Prefetching on Focus

<input @focus="queryClient.prefetchQuery(...)">

8. Loading state avoidance

Prefetching keeps status at success immediately upon component mount.

9. Sequential Prefetch

await q.prefetchQuery(A); await q.prefetchQuery(B);

10. Manual Serialization

const json = JSON.stringify(dehydrate(queryClient));

Visual

Dehydration / Hydration Bridge

SERVER                                          CLIENT
┌──────────────────────────┐                    ┌──────────────────────────┐
│  QueryClient (Memory)    │                    │  QueryClient (Memory)    │
│  { key: 'posts', data }  │                    │  (Initialy Empty)        │
└────────────┬─────────────┘                    └────────────▲─────────────┘
             │                                               │
             │  dehydrate()                                  │ hydrate()
             ▼                                               │
┌──────────────────────────┐                    ┌────────────┴─────────────┐
│  JSON State Snapshot     │                    │  Parsed State Object     │
│  [Serialized Object]     │ ─────────────────► │  [Serialized Object]     │
└────────────┬─────────────┘      Network       └────────────▲─────────────┘
             │                    Transfer                   │
             ▼                                               │
┌──────────────────────────┐                    ┌────────────┴─────────────┐
│  HTML Output             │                    │  Window Object           │
│  <script>window.state... │ ─────────────────► │  window.__QUERY_STATE__  │
└──────────────────────────┘                    └──────────────────────────┘

The Hover UX Loop

┌─────────────────────────────────────────────────────────────┐
│ 1. User hovers over <NuxtLink>                              │
│ 2. @mouseenter triggers queryClient.prefetchQuery()         │
│ 3. API Request happens in background                        │
│ 4. User clicks Link 200ms later                             │
│ 5. Component mounts -> useQuery('key')                      │
│ 6. Data found in cache! -> Render instantly (No Spinner)    │
└─────────────────────────────────────────────────────────────┘

Server-Side Prefetch Timing

┌─────────────────────────────────────────────────────────────┐
│ [SERVER START]                                              │
│   │                                                         │
│   ├──► 1. Run onServerPrefetch hooks (Fetch Data)           │
│   ├──► 2. Wait for Promises to resolve                      │
│   ├──► 3. dehydrate(queryClient)                            │
│   ├──► 4. Render Vue App to String                          │
│   └──► 5. Send HTML + Serialized State to Browser           │
│                                                             │
│ [SERVER FINISH]                                             │
└─────────────────────────────────────────────────────────────┘

Summary

ItemValue
Prefetch ToolqueryClient.prefetchQuery
Serializationdehydrate
Re-initializationhydrate
Lifecycle HookonServerPrefetch
PersistencenuxtApp.payload or window
Cache BenefitInstant Client-Side Hydration
UX BenefitHover-to-Load
Default staleTime0 (Must be increased for SSR)

Key takeaways:

  • PrefetchQuery is for anticipation. It allows you to populate the cache before a component is rendered, which is perfect for hover events or server-side rendering .
  • Dehydration serializes the cache. On the server, we take a snapshot of the QueryClient memory and turn it into a JSON string that can be sent in the HTML .
  • Hydration restores the cache. Once the browser receives the HTML, it parses the JSON and populates the client-side QueryClient, effectively “sharing” the work done by the server .
  • StaleTime is critical. If staleTime is not set, the client will see the hydrated data as “old” and refetch it immediately, defeating the purpose of SSR .
  • Nuxt integration automates the plumbing. By using the Nuxt payload system, you can ensure that each request has its own fresh QueryClient while keeping the client cache in sync .
  • Perceived performance > Actual performance. Even if the network speed is the same, an application that shows data immediately (via SSR) or predicts user clicks (via hover) feels significantly faster .

Remember: SSR and Prefetching turn “Wait for Data” into “Data is Ready.” By bridging the gap between server memory and client memory, Vue Query allows you to build lightning-fast applications that satisfy both users and search engines.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!