Nuxt 06 ๐ Data Fetching โ useFetch, useAsyncData, and $fetch
Nuxt runs your component code twice: once on the server to produce HTML, and once in the browser during hydration. Data fetching in Nuxt is built around that fact. The framework does not just give you a fetch function โ it gives you a data layer that runs on the server, serializes the result into the HTML payload, and replays it in the browser so the second run costs nothing. Understanding which of the three primitives does that replay, and which one does not, is the entire subject of this chapter.
There are three primitives, and they form a hierarchy. $fetch is the raw request function, built on ofetch โ it knows nothing about SSR, payloads, keys, or hydration. useAsyncData is the composable that wraps any async handler with a unique key, server execution, payload serialization, deduplication, and caching. useFetch is a thin convenience wrapper that combines useAsyncData with $fetch and generates the key for you from the URL and options.
The chapter walks through $fetch and why it double-fetches, then useAsyncData and the key that makes it a cache entry, then useFetch and its option surface. After that it covers the two features that make the layer genuinely productive โ deduplication and singleton cache sharing โ and finally the reactivity knobs, especially the deep option, which is the difference between a 40 ms and a 400 ms update on a large payload.
Key point: useFetch and useAsyncData are the only two that are SSR-safe. They run the handler on the server, write the result into the Nuxt payload, and reuse it during hydration under a cache key โ so a component that awaits useAsyncData costs one request total, while the same component calling $fetch in setup costs two.
Why SSR-safe data fetching exists
The hydration problem. In a plain Vue SPA, onMounted(() => fetch(...)) runs once, in the browser, and the page is blank until it resolves. In Nuxt the same code runs on the server, must resolve before the HTML is produced, and then runs again in the browser when the component hydrates. If nothing bridges the two runs, every page load and every client-side navigation issues two requests for the same data. The bridge is the payload: a JSON blob Nuxt writes into the HTML and reads back during hydration so the second run of your setup sees data that is already there.
The key problem. For the payload to work, the framework has to know that the data requested by component A on the server is the same data component A is asking for in the browser. A URL alone is not enough โ two components can hit the same URL with different options, and the same component can hit a different URL after a route change. So useAsyncData requires you to supply a key, and useFetch derives one by hashing the URL plus the options object. The key is not a performance detail; it is the identity of the cache entry, and getting it wrong is the most common source of stale or duplicated data in a Nuxt app.
The deduplication problem. A key creates a second problem: if three components share the key "cart", and a watcher fires a refetch, and the user navigates back, you can end up with four in-flight requests for one entry. Nuxt solves this with the dedupe option โ when a request for a key is already in flight, a new trigger either cancels it ("cancel", the default) or waits for it and skips the duplicate ("defer"). This is per-key deduplication, not per-URL, which is why the key must be unique.
The payload-size problem. Everything returned by useAsyncData is serialized into the payload and shipped inside the HTML. A 500-record list of users, each with an embedded avatar object and 30 fields, is a megabyte of HTML. The pick option trims the response to named fields, and transform lets you reshape before serialization. Neither is about correctness; both are about shipping less.
The reactivity problem. data is a ref, and a ref on a large array is deeply reactive โ Vue walks the whole structure and installs proxies on every nested object. For a payload of a few hundred items that is measurable in milliseconds and in memory. The deep: false option returns a shallow ref instead, and Vue stops walking. The trade-off is that mutating a nested field no longer triggers an update, so deep: false is for data you read but replace wholesale.
The trade-off. Every one of these mechanisms adds a line of API surface and a way to get it wrong. $fetch has no key to invent, no cache to invalidate, no payload to bloat โ and that is exactly why it is still the right tool for mutations, form submissions, and event handlers, where the data is not needed for hydration and a duplicate request is not possible. Using useFetch for a POST is as wrong as using $fetch in setup for the page’s primary data.
a. $fetch โ the universal request function
$fetch is Nuxt’s global alias for ofetch. It works in components, in composables, in plugins, and in Nitro server routes. On the server it uses the runtime’s native fetch; in the browser it uses the browser’s. It has no SSR awareness whatsoever: no key, no payload, no deduplication, no cache.
// A plain request. On the server this runs during SSR,
// and again in the browser during hydration. Two requests.
const user = await $fetch("/api/user/1");
// ofetch options are passed through unchanged
const created = await $fetch("/api/todos", {
method: "POST", // any HTTP method
body: { title: "Buy milk" }, // serialized to JSON automatically
headers: { Authorization: `Bearer ${token}` }, // plain object, merged in
query: { draft: true }, // becomes ?draft=true
});
The double-request behaviour is the thing to internalise. If you call $fetch at the top level of a setup block, the server runs it to render the HTML, then the browser runs it again once the component mounts, because nothing told the client that the server already had this data. The page renders correctly and the network tab shows two identical requests. That is the signature bug of this chapter.
$fetch throws on non-2xx responses. It does not return an error object; it rejects with a FetchError carrying a status, a statusText, and the parsed data body. That makes it natural inside try/catch, and it is why useFetch needs its own error handling โ it catches that rejection and exposes it as a ref instead of throwing.
// $fetch rejects; the caller owns the error path
try {
await $fetch("/api/orders", { method: "POST", body: order });
await refreshNuxtData("orders"); // invalidate the cache entry, see section d
} catch (error) {
// error.data holds the parsed error body from the server
console.error(error.data?.message ?? "Order failed");
}
For application-wide behaviour โ auth headers, base URLs, logging, retry โ you do not wrap every call site. You create a configured instance with $fetch.create inside a plugin and expose it through nuxtApp.
// plugins/api.ts โ one configured client for the whole app
export default defineNuxtPlugin((nuxtApp) => {
const api = $fetch.create({
baseURL: useRuntimeConfig().public.apiBase, // from nuxt.config runtimeConfig
onRequest({ options }) { // runs before every request
const token = useCookie("token").value;
if (token) options.headers.set("Authorization", `Bearer ${token}`);
},
onResponseError({ response }) { // runs on every failure
if (response.status === 401) nuxtApp.runWithContext(() => navigateTo("/login"));
},
});
return { provide: { api } }; // available as nuxtApp.$api and in templates
});
The rule that follows from all of this is narrow and absolute: $fetch is for work that happens after the page is interactive โ a click, a submit, a websocket message. useFetch and useAsyncData are for work that must be ready when the page renders.
b. useAsyncData โ the key, the handler, and the payload
useAsyncData is the real data layer. It takes a key, a handler, and an options object, and returns refs. The handler can do anything asynchronous โ an HTTP request, a database read through a server route, an SDK call, a file read. That generality is why the composable exists separately from useFetch.
const { data, pending, error, status, refresh, execute } = await useAsyncData(
"current-user", // the cache key: unique per distinct data
() => $fetch("/api/user/1"), // the handler: awaited on the server
{
default: () => null, // value of `data` before the handler resolves
transform: (user) => ({ // applied before the payload is serialized
...user,
displayName: user.name.trim(),
}),
},
);
The key is the contract. On the server, useAsyncData runs the handler, stores the result under "current-user" in the Nuxt payload, and renders the component with data already populated. On the client, hydration reads the payload first: if "current-user" is there, the handler never runs and no request is made. Any other component that also calls useAsyncData("current-user", ...) gets the same ref โ the handler runs once for the whole app, not once per component. That sharing is the subject of section d.
Because the handler is arbitrary, useAsyncData is the right choice whenever the data does not come from an HTTP endpoint you can describe as a URL.
// The handler is not required to be a fetch call
const { data: flags } = await useAsyncData("feature-flags", async () => {
const store = useFeatureStore();
await store.hydrate(); // read from localStorage / a cookie
return store.flags; // whatever it returns becomes the payload
});
The status ref is a string with four values: "idle" before the first run, "pending" while the handler is in flight, "success" after it resolves, and "error" if it throws. It is more useful than pending alone for building a UI that distinguishes “never asked” from “asking” from “failed” โ for example, showing a skeleton on "pending" and an empty state only on "success".
<template>
<!-- three distinct states, three distinct affordances -->
<Skeleton v-if="status === 'pending'" />
<ErrorBox v-else-if="status === 'error'" :error="error" @retry="refresh" />
<UserCard v-else-if="data" :user="data" />
<EmptyState v-else />
</template>
One option deserves separate mention: immediate: false. It tells useAsyncData not to run the handler on mount at all, producing an "idle" status, and leaves it to you to call execute() when the data is actually needed โ behind a click, after a filter is chosen, when a tab becomes visible.
// Nothing happens until the user asks for it
const { data: report, status, execute } = await useAsyncData(
"report",
() => $fetch("/api/report"),
{ immediate: false }, // status starts as "idle"
);
// Later, from a button handler
async function loadReport() {
await execute(); // runs the handler now, updates `data`
}
c. useFetch โ the wrapper and the derived key
useFetch is sugar. Internally it calls useAsyncData with a key generated from the URL and the options, and a handler that calls $fetch with the same arguments. Everything useAsyncData does โ server execution, payload serialization, deduplication, caching โ happens identically. The convenience is that you do not have to name the key and you get request options in the same object.
const { data: posts, pending } = await useFetch("/api/posts", {
query: { page: 1, limit: 20 }, // serialized to the query string
method: "GET", // any ofetch option is accepted
headers: { "X-Tenant": "acme" },// merged into the $fetch call
key: "posts-page-1", // override the generated key when you must
});
The URL can be reactive, and this is where useFetch earns its place. Pass a ref, a computed, or a function, and the composable re-runs whenever the resolved URL or any watched option changes โ the old request is discarded, the new one becomes the cache entry.
const page = ref(1); // a reactive page number
const search = ref(""); // a reactive search term
const { data, status } = await useFetch("/api/posts", {
query: { page, q: search }, // refs inside `query` are unwrapped and watched
watch: [page, search], // explicitly watch the sources that must refetch
});
pick and transform shape the data before it enters the payload, which is the only point at which you can reduce what ships to the browser.
const { data: catalog } = await useFetch("/api/products", {
// Only these fields survive into the payload and the client
pick: ["id", "title", "price"],
// Reshape after picking, still before serialization
transform: (products) =>
products.map((p) => ({ ...p, price: `$${p.price.toFixed(2)}` })),
});
Note what useFetch does not do: it does not turn an endpoint into an action. There is no “revalidate on mutation”, no optimistic update, no cache invalidation. Those are $fetch plus refreshNuxtData, as shown in section d.
d. Deduplication, singleton caching, and the cache tools
Two components asking for the same key get the same data from a single request. That is the singleton behaviour, and it applies to useFetch exactly as it does to useAsyncData โ the generated keys just happen to match when the URLs and options match.
// In the header component
const { data: cart } = await useAsyncData("cart", () => $fetch("/api/cart"));
// In the drawer component โ no second request, same ref
const { data: cart } = await useAsyncData("cart", () => $fetch("/api/cart"));
// After adding an item, invalidate once and every consumer updates
await $fetch("/api/cart", { method: "POST", body: item });
await refreshNuxtData("cart"); // refetch all components using "cart"
dedupe controls what happens when a second trigger arrives while a request for the same key is still in flight. The default is "cancel": the in-flight request is aborted and replaced. "defer" is the alternative: the new trigger is dropped and the in-flight request’s result is reused, which is what you want for a search input where typing fast should not produce a request per keystroke that cancels the previous one.
const q = ref("");
// "defer" means: while a request is running, further triggers are ignored
const { data: results } = await useFetch("/api/search", {
query: { q },
dedupe: "defer", // "cancel" (default) aborts; "defer" skips the new trigger
});
Caching on the client is governed by getCachedData. Its default implementation returns nuxtApp.payload.data[key] ?? nuxtApp.static.data[key], and it is consulted before every run, including on client-side navigation. Returning a value (even an old one) skips the request; returning undefined allows it.
const { data: catalog } = await useFetch("/api/catalog", {
key: "catalog",
getCachedData: (key, nuxtApp, { cause }) => {
// `cause` is "initial" | "refresh" | "watch" โ you can treat them differently
const fresh = nuxtApp.payload.data[key]; // data from this request cycle
const prerendered = nuxtApp.static.data[key]; // data baked in at build time
return cause === "refresh" ? undefined : fresh ?? prerendered;
},
});
The nuxtApp.static.data half is what makes prerendered content priceless: when a route is prerendered or served with a cache or swr route rule, its data is emitted as static JSON, and getCachedData reuses it on every client-side navigation instead of refetching. With experimental.payloadExtraction enabled, that payload also stops being shipped to the client when the HTML already contains everything.
Three utilities complete the toolkit, and they are all keyed:
// Read a cache entry without triggering a fetch
const { data: cachedCart } = useNuxtData("cart");
// Refetch one key, or every registered key when called with no argument
await refreshNuxtData("cart");
// Drop an entry: its data, its error, and any in-flight promise
clearNuxtData("cart");
clearNuxtData is the invalidation primitive. refreshNuxtData is the revalidation primitive. Neither reaches into components โ they mutate the shared payload, and because data is the same ref in every consumer, every consumer re-renders.
e. Reactivity knobs โ lazy, server, immediate, default, watch, deep
Five options change when the handler runs, and one changes how reactive the result is. They are independent, so a table is not enough; each has a distinct failure mode.
lazy: true means “do not block navigation, resolve whenever you can”. The page renders immediately with data at its default and status: "pending", and the data arrives after hydration. It is the correct choice for below-the-fold sections and secondary panels, and the wrong choice for anything that determines the page’s title, canonical URL, or SEO metadata.
// Navigation is not blocked; data arrives after hydration
const { data: recommendations, status } = await useFetch("/api/recommendations", {
lazy: true, // alias composable: useLazyFetch
default: () => [], // so the template has an array, never null
});
server: false means “do not run during SSR”. The server renders the component with pending: true and no data; the request happens in the browser only. This is for data that depends on client-only state โ localStorage, navigator, the user’s timezone โ and it carries an SEO and layout-shift cost, because the HTML has an empty slot.
// Nothing runs on the server: this needs the browser
const { data: timezone } = await useFetch("/api/tz", {
server: false, // SSR renders with `pending: true`
default: () => "UTC", // keeps the markup stable until it resolves
});
deep is the performance option and the one most often missed. By default data is a deeply reactive ref. On a payload of a few thousand records, that means Vue’s reactivity system proxies every object and every array index in it. Setting deep: false makes data a shallow ref: assigning a new array or object still triggers updates, but mutating a nested field does not.
// 5,000 rows: skip deep proxying, replace the array instead of mutating it
const { data: rows } = await useFetch("/api/rows", {
deep: false, // shallow ref โ `rows.value[0].name = x` will NOT update
});
// Do this instead: replace the value wholesale
rows.value = rows.value.map((row) => ({ ...row, selected: true }));
The remaining options are smaller but common. default supplies the value before the handler resolves, which removes null checks from templates. watch adds sources that force a refetch beyond the reactive props inside the URL and query. And for a shared cache entry you can pre-fill data so the component renders meaningful markup before the handler has ever run.
// Seed the shared entry from a store, fetch only if it is empty
const { data: profile } = await useAsyncData("profile", () => $fetch("/api/profile"), {
default: () => userStore.cachedProfile ?? null, // used until the handler resolves
watch: [() => userStore.accountId], // refetch when the account changes
});
Complete Example Session
// ============================================
// PART 1: useAsyncData WITH A KEY AND A TRANSFORM
// ============================================
const { data: user, status, error, refresh } = await useAsyncData(
"current-user", // cache key, shared app-wide
() => $fetch("/api/user/1"), // handler, awaited during SSR
{
default: () => null, // no null checks for `undefined`
transform: (u) => ({ ...u, name: u.name.trim() }), // shaped before serialization
},
);
// ============================================
// PART 2: THE SINGLETON โ ONE KEY, ONE REQUEST
// ============================================
// components/CartBadge.vue
const { data: cart } = await useAsyncData("cart", () => $fetch("/api/cart"));
// components/CartDrawer.vue โ same key, no second request
const { data: cart } = await useAsyncData("cart", () => $fetch("/api/cart"));
// ============================================
// PART 3: useFetch WITH REACTIVE PARAMETERS
// ============================================
const page = ref(1);
const search = ref("");
const { data: posts, pending } = await useFetch("/api/posts", {
query: { page, q: search }, // refs are unwrapped into the query string
watch: [page, search], // refetch whenever either changes
key: "posts-list", // stable key across page changes
});
// ============================================
// PART 4: TRIMMING THE PAYLOAD
// ============================================
const { data: products } = await useFetch("/api/products", {
pick: ["id", "title", "price"], // only these fields reach the payload
transform: (list) => list.sort((a, b) => a.price - b.price), // sort server-side
});
// ============================================
// PART 5: lazy AND server FLAGS
// ============================================
const { data: related } = await useFetch("/api/related", {
lazy: true, // navigation is not blocked
default: () => [], // template always has an array
});
const { data: locale } = await useFetch("/api/locale", {
server: false, // client-only: reads navigator.language
default: () => "en",
});
// ============================================
// PART 6: DEDUPLICATION
// ============================================
const q = ref("");
const { data: results } = await useFetch("/api/search", {
query: { q },
dedupe: "defer", // ignore triggers while a request is in flight
});
// ============================================
// PART 7: A CUSTOM getCachedData
// ============================================
const { data: catalog } = await useFetch("/api/catalog", {
key: "catalog",
getCachedData: (key, nuxtApp, { cause }) => {
if (cause === "refresh") return undefined; // always refetch on demand
return nuxtApp.payload.data[key] ?? nuxtApp.static.data[key]; // else reuse
},
});
// ============================================
// PART 8: THE CACHE UTILITIES
// ============================================
const { data: cachedCart } = useNuxtData("cart"); // peek at the cache, no request
await refreshNuxtData("cart"); // revalidate one key
clearNuxtData("cart"); // drop the entry entirely
// ============================================
// PART 9: MUTATIONS GO THROUGH $fetch
// ============================================
async function addToCart(item: CartItem) {
await $fetch("/api/cart", { method: "POST", body: item }); // action, not SSR data
await refreshNuxtData("cart"); // update every consumer
}
// ============================================
// PART 10: SERVER ROUTES AND FORWARDED HEADERS
// ============================================
// server/api/me.get.ts
export default defineEventHandler(async (event) => {
const headers = getRequestHeaders(event); // the incoming request's headers
return await $fetch("/api/private/profile", { headers }); // forward cookies + auth
});
The ten parts covered the keyed composable, the shared cache entry, reactive parameters, payload trimming, the timing flags, deduplication, custom caching, the invalidation utilities, mutations, and the server-route case where headers must be forwarded explicitly.
Quick Reference
The Three Primitives
| Primitive | SSR payload | Auto key | Use for |
|---|---|---|---|
$fetch | no | no | actions, submits, server routes |
useAsyncData | yes | no | any async source, custom keys |
useFetch | yes | yes | HTTP endpoints in setup |
Options That Change Timing
| Option | Effect | Cost |
|---|---|---|
lazy: true | does not block navigation | empty slot until hydration |
server: false | never runs during SSR | no SEO, layout shift |
immediate: false | waits for execute() | status starts "idle" |
default | value before resolution | none |
watch | extra refetch sources | extra requests if wrong |
Shape and Cache Options
| Option | Effect |
|---|---|
transform | reshapes before serialization |
pick | keeps only named fields in the payload |
deep: false | shallow ref, no nested proxying |
getCachedData | decides whether to skip the request |
dedupe: "cancel" | aborts the in-flight request (default) |
dedupe: "defer" | reuses the in-flight request |
Cache Utilities
| Utility | Purpose |
|---|---|
refreshNuxtData(key) | refetch one key or all keys |
clearNuxtData(key) | drop data, error, and pending promise |
useNuxtData(key) | read a cached entry without fetching |
prerenderRoutes + route rules | serve and reuse static payload data |
Best Practices
โ Do This:
// Fetch page data with the keyed composables
const { data } = await useFetch("/api/posts"); // โ
// Use $fetch for actions and invalidate afterwards
await $fetch("/api/cart", { method: "POST", body: item });
await refreshNuxtData("cart"); // โ
// Give shared data a stable, shared key
useAsyncData("profile", () => $fetch("/api/profile")); // โ
// Trim the payload before it ships
useFetch("/api/products", { pick: ["id", "title", "price"] }); // โ
// Shallow-ref large lists
useFetch("/api/rows", { deep: false }); // โ
// Use "defer" for keystroke-driven requests
useFetch("/api/search", { query: { q }, dedupe: "defer" }); // โ
โ Don’t Do This:
// $fetch in setup: double fetch, no payload
const user = await $fetch("/api/user"); // โ
// Signalling a mutation with useFetch
await useFetch("/api/orders", { method: "POST", body: order }); // โ
// A key that changes on every render
useAsyncData(`user-${Math.random()}`, () => $fetch("/api/user")); // โ
// deep: false and then mutating nested fields
rows.value[0].selected = true; // โ
// Lazy on the data that drives SEO metadata
useFetch("/api/post", { lazy: true }); // โ
// Assuming $fetch nulls out on failure
const res = await $fetch("/api/x").catch(() => null); // โ (loses the error)
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Two identical requests per page | $fetch used in setup | Switch to useFetch |
| Data never updates after a mutation | Cache entry not invalidated | refreshNuxtData(key) |
| Stale data after route change | Key does not include the route param | Put the param in the key |
null in the template on first render | No default provided | default: () => [] |
| SEO tags empty in the HTML | lazy: true on the primary data | Remove lazy |
| Huge HTML payload | Whole response serialized | pick and transform |
| Nested edits do not re-render | deep: false | Replace the value wholesale |
| Cancelled requests on typing | Default dedupe: "cancel" | dedupe: "defer" |
Real-World Examples
1. Page data with a route parameter
const route = useRoute();
const { data: post } = await useFetch(`/api/posts/${route.params.slug}`, {
key: `post-${route.params.slug}`, // one key per post
});
2. Shared navigation data
// Any component can read the same entry
const { data: config } = await useAsyncData("site-config", () => $fetch("/api/config"));
3. Client-only personalisation
const { data: theme } = await useFetch("/api/theme", {
server: false, default: () => "light",
});
4. Load on demand
const { data, execute } = await useAsyncData("report", () => $fetch("/api/report"), {
immediate: false,
});
5. Debounce-friendly search
useFetch("/api/search", { query: { q }, dedupe: "defer", lazy: true });
6. Trim heavy responses
useFetch("/api/users", { pick: ["id", "name", "avatarUrl"] });
7. Shallow list for virtual scrolling
const { data: rows } = await useFetch("/api/rows", { deep: false });
8. Prerendered data reused on navigation
defineNuxtConfig({
routeRules: { "/catalog": { swr: 3600 } },
experimental: { payloadExtraction: true },
});
9. Invalidate every entry after a bulk action
await $fetch("/api/reset", { method: "POST" });
await refreshNuxtData(); // no argument: refresh all active keys
10. Forward auth to an internal endpoint
export default defineEventHandler(async (event) => {
const headers = getRequestHeaders(event);
return await $fetch("/api/private/stats", { headers });
});
Visual
The SSR Payload Round Trip
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SSR REQUEST FLOW โ
โ โ
โ 1. browser requests the page โ
โ 2. setup() runs on the server โ
โ 3. useFetch calls $fetch and awaits โ
โ 4. the result goes into the payload โ
โ 5. HTML plus payload reaches the browser โ
โ 6. hydration reads it, no second request โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
$fetch in setup Versus useFetch
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ $fetch IN setup() VS useFetch โ
โ โ
โ setup() โโโบ $fetch โโโบ data โโโบ HTML โ
โ hydration โโโบ $fetch AGAIN โโโบ refetch โ
โ โ
โ setup() โโโบ useFetch โโโบ payload โโโบ HTML โ
โ hydration โโโบ read payload โโโบ no request โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
One Key, One Request
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SHARED KEY = SHARED CACHE ENTRY โ
โ โ
โ <CartBadge> useAsyncData("cart") โโโ โ
โ <CartDrawer> useAsyncData("cart") โโโผโโบ 1 request โ
โ <CartTotal> useAsyncData("cart") โโโ 3 consumers โ
โ โ
โ a different key โโโบ a different request โ
โ refreshNuxtData("cart") โโโบ all three update โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Dedupe Modes
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ dedupe: "cancel" โ
โ request 1 โโโบ aborted โ
โ request 2 โโโบ resolves โโโบ data โ
โ โ
โ dedupe: "defer" โ
โ request 1 โโโบ resolves โโโบ data โ
โ request 2 โโโบ skipped, reuses the first โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| SSR-safe primitives | useAsyncData, useFetch |
| Raw request function | $fetch (ofetch) |
| Cache identity | the key |
| Auto key | useFetch, hashed from URL + options |
| Default dedupe | "cancel" |
| Alternative dedupe | "defer" |
| Revalidate | refreshNuxtData(key) |
| Invalidate | clearNuxtData(key) |
| Deep reactivity | on by default, off with deep: false |
| Status values | idle, pending, success, error |
Key takeaways:
$fetchis not SSR-safe, and that is by design. It has no key and no payload, so calling it insetupruns once on the server and again in the browser. Use it for actions, submits, and server routes; use the keyed composables for anything the first render depends on.- The key is the cache entry, not a detail. Two components with the same key share one request and one ref; two components with keys that differ only by accident produce duplicated requests and duplicated payload entries. Put route parameters inside the key.
useFetchis sugar overuseAsyncDataplus$fetch. It generates the key from the URL and options, which is convenient right up until you need a stable key across a changing query โ then you passkeyexplicitly.dedupedecides what a second trigger does."cancel"aborts the in-flight request and replaces it;"defer"ignores the new trigger and reuses the running one. Keystroke-driven search wants"defer".pickandtransformrun before serialization. They are the only place where you can reduce what ships to the browser, and they matter more than any client-side memoisation.deep: falsetrades mutation for speed. Vue stops proxying every nested object in a large list, which is a real win, but nested assignment no longer triggers an update โ replace the array instead.- Invalidation is keyed and global.
refreshNuxtDataandclearNuxtDatamutate the shared payload, and every consumer of that key re-renders without any prop plumbing.
Remember: Nuxt’s data layer exists to make one request serve two runtimes. The server runs the handler, the payload carries the result, and hydration reads it back under a key โ so the three primitives are really one rule: anything needed for the first paint goes through useAsyncData or useFetch, and anything that happens after the user acts goes through $fetch followed by a keyed invalidation. Everything else in this chapter โ deduplication, singleton sharing, pick, deep โ is tuning around that single contract.
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!