tezvyn:

Nuxt Server Data Fetching: useAsyncData & useFetch

AI-drafted, machine-checkedSource: nuxt-nuxt.mintlify.appintermediate

Avoid client-side request waterfalls by fetching data on the server and embedding it in the page. Nuxt's `useAsyncData` and `useFetch` handle this SSR hydration for you. The main footgun: not providing a stable key, leading to re-fetches.

WHY IT EXISTS In a typical Server-Side Rendering (SSR) setup, the server fetches data to build the HTML. When the client-side app loads, it often re-fetches that same data, causing a delay and potential layout shifts. Nuxt's data fetching composables solve this "double fetch" problem by embedding the server-fetched data into the initial page payload for the client to use immediately.

THE MENTAL MODEL Think of useAsyncData as a state manager for an async call that works across server and client. On the server, it runs your fetch function and waits for the result before sending the final HTML. It then serializes the data. On the client, it first checks for this serialized data before even considering making a new network request, effectively "rehydrating" the server state.

HOW IT WORKS useAsyncData takes two main arguments: a unique key and an async handler function. The key is a string used to deduplicate requests across your app; if you make two calls with the same key, the handler only runs once. The handler is where you perform your data fetch. The composable returns reactive refs like data, pending, error, and status, plus a refresh function to re-trigger the fetch manually. useFetch is a popular convenience wrapper around useAsyncData that is pre-configured to use Nuxt's $fetch utility.

WHEN TO USE IT Use useAsyncData or useFetch whenever a page or component needs data from an API to render. It's the standard approach in Nuxt for fetching data that's critical for the initial page load and for SEO, as it ensures the content is present in the server-rendered HTML.

WHEN NOT TO USE IT Avoid it for data that is purely client-side and not needed for the initial render, like fetching user settings after they've already logged in. In such cases, a simple fetch in an onMounted hook can be simpler. You can also use useAsyncData with the server: false option to make it a client-only fetcher. It must be called within the Nuxt context (pages, components, plugins).

ONE CANONICAL EXAMPLE In a page component, you can fetch a list of mountains and wait for the result before the page renders on the server. The code looks like this: const { data, pending, error } = await useAsyncData('mountains', () => $fetch('https://api.nuxtjs.dev/mountains')). Here, 'mountains' is the unique key. The data ref will contain the fetched array, and await ensures the server-side render waits for the fetch to complete.

Read the original → nuxt-nuxt.mintlify.app

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.