Data fetching in Nuxt

Intermediate · 15 min

Why Nuxt has useFetch and useAsyncData, how they fetch on the server once and hand the result to the client, and when plain $fetch is the right tool.

Before thisNuxt fundamentalsData fetching in Vue

Alexander Lichter · 15 min

Data fetching in Nuxt

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Alexander LichterReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Plain `fetch` in `<script setup>` runs twice in a server-rendered app, once on the server and again during hydration, which wastes a request and can cause a hydration mismatch.
  • `useFetch` and `useAsyncData` fetch during server rendering, store the result in the page's payload under a key, and let the client read it from there instead of fetching again.
  • `useFetch(url)` is shorthand for `useAsyncData` wrapping `$fetch(url)`; reach for `useAsyncData` when the data comes from an SDK, a CMS client, or several requests combined.
  • `$fetch` is the right tool for anything triggered by the user, such as form submits and button clicks, because those happen after hydration and have nothing to transfer.
  • Both composables return `data`, `status`, `error`, `refresh`, and `clear`; in Nuxt 4, `data` is a shallow ref that starts as `undefined`, and calls with the same key share the same refs.
  • `await` blocks client-side page changes until the data arrives, while `lazy: true` lets the page render immediately so you show a loading state from `status`.

The double-fetch problem

In a client-rendered Vue app, loading data is simple: call fetch in setup or onMounted, put the result in a ref, render it. Data fetching in Vue covered that pattern. Server rendering breaks it in two ways.

Fetch in onMounted and the server never runs it, because mount hooks are browser-only. The server sends a page with an empty list, and you lose most of the reason for SSR.

Fetch at the top level of setup and the opposite happens. The server fetches, renders the list, and sends the HTML. Then the browser hydrates, runs the same setup, and fetches again. You pay for two requests. Worse, if the second response differs from the first (a new comment arrived, a price changed), the client’s render no longer matches the server’s HTML, which is the hydration mismatch problem.

What you want is for the server to fetch once and hand its answer to the browser along with the HTML. That is what Nuxt’s data composables do.

The payload: fetch once, ship the answer

<!-- app/pages/posts/index.vue -->
<script setup lang="ts">
const { data: posts, status, error } = await useFetch('/api/posts')
</script>

<template>
  <p v-if="error">Couldn't load posts.</p>
  <ul v-else>
    <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
  </ul>
</template>

During server rendering, useFetch makes the request, waits for it, and stores the result under a key in the payload, a serialized object Nuxt embeds in the HTML. When the browser hydrates and reaches the same useFetch call, it finds the key already in the payload and uses that value instead of making a request. One fetch, matching renders on both sides.

A restaurant analogy works here. The kitchen (the server) cooks the dish and sends it out with the order ticket stapled to the tray. The waiter in the dining room (the browser) checks the ticket, sees the dish has been made, and serves it rather than putting the order in again. The key is the ticket number, which is why keys matter so much below.

You can inspect the payload in the Payload tab of Nuxt DevTools, or read it from useNuxtApp().payload.

Three tools: $fetch, useFetch, useAsyncData

Nuxt gives you one fetch function and two composables:

  • $fetch is a globally available fetch function built on the ofetch library. It parses JSON for you, throws on error status codes, and when called during server rendering with a relative URL such as /api/posts, Nuxt handles the request in the same process. On its own it has no payload transfer.
  • useAsyncData(key, handler) runs any async function, stores the result in the payload under key, and returns reactive state.
  • useFetch(url, options) is the common case packaged up. It is close to useAsyncData wrapping $fetch(url), with a key generated from the URL, the options, and where the call sits in your code.
// These two lines do nearly the same thing
const { data } = await useFetch('/api/posts')
const { data } = await useAsyncData('posts', () => $fetch('/api/posts'))

Reach for useAsyncData when the data doesn’t come from a single URL: a CMS or database SDK with its own client, or several requests combined into one result.

const { data } = await useAsyncData('dashboard', async (_nuxtApp, { signal }) => {
  const [stats, alerts] = await Promise.all([
    $fetch('/api/stats', { signal }),
    $fetch('/api/alerts', { signal }),
  ])
  return { stats, alerts }
})

Use plain $fetch for requests the user triggers, such as submitting a form, clicking “load more”, or deleting an item. Those happen after hydration, so there is nothing to transfer, and wrapping them in a composable only adds cached state you don’t want.

<script setup lang="ts">
const email = ref('')

async function subscribe() {
  await $fetch('/api/subscribe', { method: 'POST', body: { email: email.value } })
}
</script>

What you get back

useFetch and useAsyncData return the same object:

  • data: the result.
  • status: 'idle', 'pending', 'success', or 'error'.
  • error: the error if the request failed.
  • refresh() / execute(): run the handler again.
  • clear(): reset data and error to undefined and status to 'idle'.

Nuxt 4 changed some defaults, so older tutorials may show different behaviour:

  • data is a shallow ref by default (deep: false). Replacing data.value triggers updates, but mutating a nested property doesn’t. Pass deep: true if you need that.
  • data and error start as undefined, not null.
  • Calls that share a key share the same refs, so two components asking for 'cart' read one cache entry and stay in sync. Options that shape the data, such as the handler, transform, pick, deep, and default, must then match, or Nuxt warns in development.

Because keys decide sharing and caching, give useAsyncData an explicit key, and make sure keys stay unique when you write a composable that wraps it. Two different queries under the same key will overwrite each other.

Blocking or lazy

Nuxt runs these composables inside Vue’s <Suspense>, so await decides how page changes feel:

  • With await (the default pattern), a client-side page change waits until the data has loaded, then shows the new page fully populated. Server rendering always waits regardless.
  • With lazy: true (or useLazyFetch / useLazyAsyncData), the page changes immediately and the request runs in the background. You handle the loading state yourself.
<script setup lang="ts">
const { data: comments, status } = useFetch('/api/comments', {
  lazy: true,
  server: false, // skip on the server; comments aren't needed for SEO
})
</script>

<template>
  <p v-if="status === 'pending'">Loading comments…</p>
  <CommentList v-else :comments="comments" />
</template>

Three related options are worth knowing. server: false runs the request only in the browser, after hydration. immediate: false doesn’t run it until you call execute(). pick and transform trim the result before it goes into the payload, which keeps the HTML smaller.

Reactive inputs

Pass refs in the options and useFetch refetches when they change:

const page = ref(1)
const { data } = await useFetch('/api/posts', {
  query: { page }, // a ref: changing page.value refetches
})

For a URL built from reactive values, pass a getter:

const route = useRoute()
const { data: post } = await useFetch(() => `/api/posts/${route.params.id}`)

A common slip is building the URL from .value once, as in useFetch(`/api/posts/${id.value}`, { watch: [id] }). The watch option makes it refetch when id changes, but the URL string was fixed when the line ran, so it keeps requesting the original ID. Use the getter form instead.

Shared state that isn’t fetched

Sometimes server-computed state isn’t a fetch at all: a feature flag, a value read from a cookie, a counter. A module-level ref is the wrong home for it on the server, because every request shares it. useState('key', () => initial) is Nuxt’s SSR-safe answer. It creates state per request, and transfers it to the client through the same payload mechanism. For side effects that should run only once across server and client, such as initializing a Pinia store, Nuxt provides callOnce rather than misusing useAsyncData.

What the video covers

Alexander Lichter builds a small demo that uses useFetch with reactive query parameters, then rebuilds the same behaviour with useAsyncData and $fetch to show that useFetch is a convenience layer over the other two (useFetch from 3:20, the rebuild from 7:30). The official Nuxt data-fetching docs embed this video at their useAsyncData section. It was recorded on Nuxt 3, so it doesn’t cover Nuxt 4’s shallow data, undefined defaults, or shared refs per key, and it spends little time on the payload itself. The prose above fills those in. The two “go deeper” videos, both also referenced in Nuxt’s docs or by its team, cover the useFetch-in-an-event-handler mistake and how useState keeps non-fetched state SSR-safe.

Where this fits

This closes the practical Nuxt material in this roadmap. Server-side caching, authentication cookies during SSR, and query libraries are next steps in Nuxt’s own docs. TanStack Query for Vue also supports SSR if you want its caching model inside Nuxt. The last lesson, Vapor mode and the future of Vue, looks at where Vue’s rendering engine itself is heading.

Check yourself

  1. 01Why is `const posts = await $fetch('/api/posts')` at the top level of a Nuxt page's `<script setup>` a problem, when the same line inside `useAsyncData` is fine?

    On its own, the call runs during server rendering and then again in the browser during hydration, so the API is hit twice and the two results may differ, causing a hydration mismatch. Wrapped in `useAsyncData('posts', () => $fetch('/api/posts'))`, the server's result is stored in the payload under that key and the client reuses it instead of running the request again.

  2. 02A form's submit handler calls `useFetch('/api/subscribe', { method: 'POST', body })`. What is wrong, and what should it use instead?

    `useFetch` is meant to run during component setup to load data for rendering; it creates keyed, cached, reactive state and can watch its inputs. Called in an event handler, it adds state on every submit, can reuse a cached result, and may refetch when reactive options change. A user-triggered request should simply call `await $fetch('/api/subscribe', { method: 'POST', body })`.

  3. 03What does `lazy: true` change compared to awaiting `useFetch` normally?

    Without `lazy`, an awaited `useFetch` makes client-side page changes wait until the data has loaded, so the new page appears fully populated. With `lazy: true`, the page changes immediately and the request runs in the background, so `data` starts out `undefined` and you render a loading state using `status === 'pending'`. Server rendering still waits for the data either way.

  4. 04Two components on the same page each call `useAsyncData('cart', fetchCart)`. What happens in Nuxt 4?

    They share one entry keyed `cart`: the same `data`, `status`, and `error` refs, and the result is cached under that one key. Refreshing from either component updates both. Because they share state, options that shape the data, such as the handler, `transform`, `pick`, `deep`, and `default`, must match across both calls, or Nuxt warns in development.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark