Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 32 ยท Data and state

Data fetching with useFetch and useAsyncData

Load data in Nuxt without fetching twice: useFetch, useAsyncData and $fetch compared, keys, status and refresh, lazy and server options, transform, and payload reuse.

Most pages need data, and in a server-rendered app there is a catch. The page is built twice: first on the server, to produce HTML, and then again in the browser, where Vue takes over (this is called hydration, covered in Rendering modes). If you fetch data with a plain fetch call in your component, the request runs on the server and then again in the browser. The page flickers, your API gets double the traffic, and the two answers can even differ.

Nuxt solves this with two composables, useAsyncData and useFetch. They run on the server, save the result into the page, and let the browser reuse it instead of asking again. This lesson shows how they work, which options matter, and the mistakes that cause the double fetch.

Nuxt itself needs a build step and a server, so the Nuxt code below is read-only. The runnable stand-ins are small JavaScript models of the mechanics: the payload, keys, status and refresh. The lesson marks which part is real and which is the model.

Pick the right tool

useFetch Fetch a URL. The usual choice.
useAsyncData Any async work, such as a CMS client.
$fetch Events like a button click or a form post.

Page data goes through useFetch or useAsyncData, never raw $fetch in setup.

1 / 2

useFetch

useFetch is the shortest way to load a URL. It is meant for the top of <script setup>:

VUE
<script setup lang="ts">
// real Nuxt code, read-only
const { data: posts, status, error, refresh } = await useFetch('/api/posts')
</script>

<template>
  <p v-if="status === 'pending'">Loading...</p>
  <p v-else-if="error">Could not load posts: {{ error.message }}</p>
  <ul v-else>
    <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
  </ul>
  <button type="button" @click="refresh()">Reload</button>
</template>

The return value contains:

  • data: a ref with the response. It has no value until the request finishes.
  • status: a ref that is 'idle', 'pending', 'success' or 'error'. A boolean pending ref exists too, but status tells you more.
  • error: a ref that holds the error if the request failed.
  • refresh (and its alias execute): run the request again. clear resets everything.

The URL can be reactive. Pass a function, or put refs in query, and useFetch runs again when they change:

TypeScript
const page = ref(1)
const { data } = await useFetch('/api/posts', { query: { page } })
// changing page.value fetches again; no watcher needed

The related options you will use most often:

Option What it does
key Names the request. Set it by hand when the default is not enough.
lazy: true Do not block navigation; the page renders first, status is 'pending'.
server: false Skip the server, fetch only in the browser.
immediate: false Do not start automatically; call execute() yourself.
default A factory for the value of data before the request finishes.
transform Change the response before it is stored.
pick Keep only some top-level fields of the response.
watch Extra sources that trigger a new request when they change.

useLazyFetch is shorthand for useFetch with lazy: true.

useAsyncData

useFetch is a thin layer on top of useAsyncData. Use useAsyncData directly when the data does not come from a simple URL: a database call in server code, a CMS client, or several requests combined.

TypeScript
// real Nuxt code, read-only
const { data: summary } = await useAsyncData('dashboard-summary', async () => {
  const [users, orders] = await Promise.all([
    $fetch('/api/users/count'),
    $fetch('/api/orders/count'),
  ])
  return { users, orders }
})

The first argument is the key: a unique string that identifies the data. Calling useAsyncData twice with the same key (on one page, or in several components) shares one entry instead of running the handler twice. Nuxt also uses the key to find the saved result in the page payload. With useFetch, Nuxt makes the key for you from the URL and options, so you rarely write one.

$fetch is for events

$fetch is Nuxt's request function. It is built on ofetch and, on the server, it calls your own server routes directly in memory instead of making a network request, which is fast. It does no payload handling and no deduplication, so it belongs in code that runs after a user action:

TypeScript
// real Nuxt code, read-only
async function addComment() {
  await $fetch('/api/comments', { method: 'POST', body: { text: text.value } })
  await refreshNuxtData('comments') // re-run any useAsyncData with that key
}

The classic mistake is calling $fetch at the top level of setup:

TypeScript
const posts = await $fetch('/api/posts') // runs on the server AND again in the browser

Nothing carries the server result across to the browser, so the browser asks again. Replace it with useFetch('/api/posts').

The payload: how the double fetch is avoided

When Nuxt renders a page on the server, every useAsyncData and useFetch result is collected into the payload. The payload is serialized into the HTML (in a script tag, or as a separate JSON file for prerendered pages). When the browser hydrates the page, each call looks its key up in the payload, finds the value, and skips the request. That is why the data must be serializable, and why a unique key matters.

sequenceDiagram
    participant B as Browser
    participant S as Nuxt server
    participant A as API
    B->>S: GET /posts
    S->>A: useFetch runs the request
    A-->>S: posts
    S-->>B: HTML plus payload (posts under its key)
    Note over B: hydration: useFetch finds the key in the payload
    Note over B: no second request

The server fetches once and ships the result inside the page.

The stand-in below models this with a context object. Real parts: the idea of a key, a payload object that travels with the HTML, and reuse during hydration. Stand-in parts: the api function that counts requests, and the context itself (the real one is inside Nuxt). It renders the same page three ways and counts the API requests.

Node.js Payload reuse versus a naive double fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The raw version makes two requests per page view, the keyed one makes one, and a later request after hydration works normally.

Keys, status and refresh in action

The second stand-in models what happens inside one running page: two components with the same key share one request, status moves through its states, transform shapes the stored data, and refresh runs the handler again. As before, the semantics follow Nuxt and the implementation is a small model.

Node.js Shared keys, status, transform and refresh

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the transform function is applied only by the call that created the entry here, which mirrors an important real-world rule: calls that share a key should use the same options, or the result depends on which component ran first. Nuxt warns about mismatched options in development.

Practical advice

  • Block or not. With await useFetch(...), navigation waits for the data, so the new page always appears complete. With lazy: true, the page appears at once and you show a loading state from status. Blocking is simpler and better for SEO-critical content; lazy suits secondary panels.
  • Server-only data. Add server: false for data that only makes sense in the browser, and expect it to be empty in the server HTML.
  • Keep the payload small. Everything you return is serialized into the page. Use pick or transform to drop fields you do not display (for example, a large body text on a list page). See Performance and Core Web Vitals.
  • Do not call these in event handlers or after an await. They need the Nuxt context that exists during setup. For clicks, use $fetch, then refresh() or refreshNuxtData().
  • Errors are values. useFetch does not throw for HTTP errors. Check error, or render the error page (see Nested routes and layouts).
  • Your own routes. The URLs you fetch are often the server routes you write in Server routes and the Nitro engine.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does const posts = await $fetch('/api/posts') at the top of setup cause a double fetch?

    $fetch has no payload handling. The server runs it, the browser runs it again, and useFetch or useAsyncData exist to stop that.
  2. 2. What is the key in useAsyncData('dashboard', handler) used for?

    The key names the entry. Calls with the same key share it, and hydration looks the saved value up by that key.
  3. 3. When should you use $fetch instead of useFetch?

    $fetch is for work triggered by the user after the page is running. Page data belongs to useFetch or useAsyncData.
  4. 4. What does lazy: true change?

    A lazy request does not block navigation, so your template must handle the pending state.
  5. 5. A list page returns 200 posts with full bodies but shows only titles. How do you keep the payload small?

    Everything in data is serialized into the HTML. transform or pick drops what you do not need.

Summary

  • useFetch and useAsyncData run on the server, store their result in the payload and let the browser reuse it, so the page does not fetch twice.
  • Use useFetch for URLs, useAsyncData for custom async work, and $fetch for actions after a click or submit.
  • The result gives you data, status, error, refresh, execute and clear.
  • The key identifies the data; calls with the same key share one entry, so keep their options identical.
  • lazy, server, immediate, default, transform, pick and watch tune when and how the request runs.
  • A raw $fetch in setup is the usual cause of double fetching.

Next: State with useState and Pinia