Data Fetching
🎯 Introduction
By the end of this article, you will be able to fetch API data in Nuxt. You will understand the differences between useFetch, useAsyncData, and $fetch, when to use each, how they work with server-side rendering, and how to avoid duplicate requests.
🧱 Why Data Fetching Matters in Nuxt
Standard Vue projects often fetch data with fetch or Axios in onMounted, leaving the initial page empty while data loads.
Nuxt supports server-side rendering (SSR): the server can fetch data before returning the HTML to the browser. This makes initial content available sooner and helps SEO.
Nuxt provides three core tools for SSR and CSR:
| Tool | Purpose | Common use case |
|---|---|---|
useFetch | A composable that handles SSR/CSR data fetching | Data needed when a page initializes |
useAsyncData | A lower-level composable used with $fetch | Custom request logic or multiple combined requests |
$fetch | Performs HTTP requests | Fetching data in event handlers |
🚀 useFetch: The Standard Approach to Data Fetching
useFetch is a Nuxt composable that fetches data on the server and passes the result to the client to avoid duplicate requests.
<template>
<div>
<h1>Posts</h1>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
<script setup>
const { data: posts } = await useFetch('https://jsonplaceholder.typicode.com/posts');
</script>
data returned by useFetch is a ref that you can use directly in templates. await waits for the data before rendering the page.⚡ useAsyncData + $fetch: A More Flexible Combination
Use useAsyncData with $fetch for more complex request logic, such as combining API calls or preparing parameters before a request.
<!-- app/pages/posts/[id].vue -->
<template>
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
</div>
</template>
<script setup>
const route = useRoute();
const { data: post } = await useAsyncData('post-detail', () => {
return $fetch(`https://jsonplaceholder.typicode.com/posts/${route.params.id}`);
});
</script>
useAsyncData is a unique key for caching and deduplication. Use different keys for distinct requests on the same page.🆚 Choosing Between useFetch and useAsyncData
| Scenario | Recommended approach |
|---|---|
| Simple GET requests for API data | useFetch |
| Combining requests or handling complex logic | useAsyncData + $fetch |
| Requests triggered by button clicks or form submissions | $fetch |
useFetch provides an integrated solution, useAsyncData lets you customize the logic, and $fetch performs the request itself.🖱 Use $fetch for Event-driven Requests
For requests triggered by user interaction rather than page initialization, use $fetch directly.
<template>
<div>
<input v-model="keyword" placeholder="Enter a keyword" />
<button @click="handleSearch">Search</button>
<ul>
<li v-for="item in results" :key="item.id">{{ item.title }}</li>
</ul>
</div>
</template>
<script setup>
const keyword = ref('');
const results = ref([]);
async function handleSearch() {
results.value = await $fetch(`https://api.example.com/search?q=${keyword.value}`);
}
</script>
$fetch in event handlers. Initialize useFetch in the appropriate setup context rather than invoking it repeatedly from an event handler.🪤 Avoiding Duplicate Requests with SSR
Why use useFetch instead of fetching directly in onMounted?
useFetch fetches data on the server first and includes it in the page payload. During hydration, Nuxt reuses that data without fetching it again.
A fetch call in onMounted does not run on the server. It runs after the client loads the page, leaving the initial content empty and losing the benefit of SSR for that data.
🛠 Common Options
lazy: Non-blocking Data Fetching
By default, useFetch waits for data before completing page navigation. Add lazy: true to avoid blocking navigation:
const { data: posts, pending } = await useFetch('/api/posts', {
lazy: true,
});
Use pending to display a loading state:
<template>
<div>
<p v-if="pending">Loading...</p>
<ul v-else>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
❓ Questions and Answers
Q1: Why use useFetch for initial data instead of fetching in onMounted?
onMounted runs only on the client, so the server does not fetch the data. Initial content remains empty, losing the benefits of SSR.
Q2: How are useFetch and $fetch related?
useFetch uses $fetch to perform requests and also handles SSR payload transfer, client-side data reuse, and key-based caching.
Q3: Can I omit the useAsyncData key?
You can omit it and let Nuxt generate a key automatically. For complex request logic or requests to the same URL with different parameters, specify a key explicitly to avoid conflicts.
Q4: How does lazy: true differ from the default behavior?
The default behavior waits for data before completing navigation. With lazy: true, navigation proceeds and the page updates when data arrives, which suits secondary data.
🧪 Practice
Build a post detail page:
- Create
app/pages/posts/[id].vue. - Use
useFetchto requesthttps://jsonplaceholder.typicode.com/posts/${id}. - Display the post title and body.
- Add a link back to
/posts(createapp/pages/posts/index.vueas the list page first if needed).
<!-- app/pages/posts/[id].vue -->
<template>
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
<NuxtLink to="/posts">Back to list</NuxtLink>
</div>
</template>
<script setup>
const route = useRoute();
// Use useFetch here to fetch the post details
const { data: post } = await useFetch(
// Build the API URL here
);
</script>
🎉 You now understand data fetching in Nuxt! Next, we will explore state management and the roles of useState and Pinia.
