--- title: 'Data fetching' description: Nuxt provides composables to handle data fetching within your application. navigation.icon: i-ph-plugs-connected-duotone --- Nuxt comes with two composables and a built-in library to perform data-fetching in browser or server environments: `useFetch`, [`useAsyncData`](/docs/api/composables/use-async-data) and `$fetch`. In a nutshell: - [`useFetch`](/docs/api/composables/use-fetch) is the most straightforward way to handle data fetching in a component setup function. - [`$fetch`](/docs/api/utils/dollarfetch) is great to make network requests based on user interaction. - [`useAsyncData`](/docs/api/composables/use-async-data), combined with `$fetch`, offers more fine-grained control. Both `useFetch` and `useAsyncData` share a common set of options and patterns that we will detail in the last sections. Before that, it's imperative to know why these composables exist in the first place. ## Why use specific composables for data fetching? Nuxt is a framework which can run isomorphic (or universal) code in both server and client environments. If the [`$fetch` function](/docs/api/utils/dollarfetch) is used to perform data fetching in the setup function of a Vue component, this may cause data to be fetched twice, once on the server (to render the HTML) and once again on the client (when the HTML is hydrated). This is why Nuxt offers specific data fetching composables so data is fetched only once. ### Network calls duplication The [`useFetch`](/docs/api/composables/use-fetch) and [`useAsyncData`](/docs/api/composables/use-async-data) composables ensure that once an API call is made on the server, the data is properly forwarded to the client in the payload. The payload is a JavaScript object accessible through [`useNuxtApp().payload`](/docs/api/composables/use-nuxt-app#payload). It is used on the client to avoid refetching the same data when the code is executed in the browser [during hydration](/docs/guide/concepts/rendering#universal-rendering). ::tip Use the [Nuxt DevTools](https://devtools.nuxt.com) to inspect this data in the **Payload tab**. :: ### Suspense Nuxt uses Vue’s [``](https://vuejs.org/guide/built-ins/suspense) component under the hood to prevent navigation before every async data is available to the view. The data fetching composables can help you leverage this feature and use what suits best on a per-calls basis. ::note You can add the [``](/docs/api/components/nuxt-loading-indicator) to add a progress bar between page navigations. :: ## `useFetch` The [`useFetch`](/docs/api/composables/use-fetch) composable is the most straightforward way to perform data fetching. ```vue twoslash [app.vue] ``` This composable is a wrapper around the [`useAsyncData`](/docs/api/composables/use-async-data) composable and `$fetch` utility. ::tip{icon="i-ph-video-duotone" to="https://www.youtube.com/watch?v=njsGVmcWviY" target="_blank"} Watch the video from Alexander Lichter to avoid using `useFetch` the wrong way! :: :read-more{to="/docs/api/composables/use-fetch"} :link-example{to="/docs/examples/features/data-fetching"} ## `$fetch` Nuxt includes the [ofetch](https://github.com/unjs/ofetch) library, and is auto-imported as the `$fetch` alias globally across your application. It's what `useFetch` uses behind the scenes. ```vue twoslash [pages/todos.vue] ``` ::warning Beware that using only `$fetch` will not provide [network calls de-duplication and navigation prevention](#why-use-specific-composables-for-data-fetching). :br It is recommended to use `$fetch` for client-side interactions (event based) or combined with [`useAsyncData`](#useasyncdata) when fetching the initial component data. :: ::read-more{to="/docs/api/utils/dollarfetch"} Read more about `$fetch`. :: ## `useAsyncData` The `useAsyncData` composable is responsible for wrapping async logic and returning the result once it is resolved. ::tip `useFetch(url)` is nearly equivalent to `useAsyncData(url, () => $fetch(url))`. :br It's developer experience sugar for the most common use case. :: ::tip{icon="i-ph-video-duotone" to="https://www.youtube.com/watch?v=0X-aOpSGabA" target="_blank"} Watch a video from Alexander Lichter to dig deeper into the difference between `useFetch` and `useAsyncData`. :: There are some cases when using the [`useFetch`](/docs/api/composables/use-fetch) composable is not appropriate, for example when a CMS or a third-party provide their own query layer. In this case, you can use [`useAsyncData`](/docs/api/composables/use-async-data) to wrap your calls and still keep the benefits provided by the composable. ```vue [pages/users.vue] ``` ::note The first argument of [`useAsyncData`](/docs/api/composables/use-async-data) is a unique key used to cache the response of the second argument, the querying function. This key can be ignored by directly passing the querying function, the key will be auto-generated. :br :br Since the autogenerated key only takes into account the file and line where `useAsyncData` is invoked, it is recommended to always create your own key to avoid unwanted behavior, like when you are creating your own custom composable wrapping `useAsyncData`. :br :br Setting a key can be useful to share the same data between components using [`useNuxtData`](/docs/api/composables/use-nuxt-data) or to [refresh specific data](/docs/api/utils/refresh-nuxt-data#refresh-specific-data). :: ```vue [pages/users/[id\\].vue] ``` The `useAsyncData` composable is a great way to wrap and wait for multiple `$fetch` requests to be completed, and then process the results. ```vue ``` ::read-more{to="/docs/api/composables/use-async-data"} Read more about `useAsyncData`. :: ## Return Values `useFetch` and `useAsyncData` have the same return values listed below. - `data`: the result of the asynchronous function that is passed in. - `pending`: a boolean indicating whether the data is still being fetched. - `refresh`/`execute`: a function that can be used to refresh the data returned by the `handler` function. - `clear`: a function that can be used to set `data` to undefined, set `error` to `null`, set `pending` to `false`, set `status` to `idle`, and mark any currently pending requests as cancelled. - `error`: an error object if the data fetching failed. - `status`: a string indicating the status of the data request (`"idle"`, `"pending"`, `"success"`, `"error"`). ::note `data`, `pending`, `error` and `status` are Vue refs accessible with `.value` in ` ``` You can alternatively use [`useLazyFetch`](/docs/api/composables/use-lazy-fetch) and `useLazyAsyncData` as convenient methods to perform the same. ```vue twoslash ``` ::read-more{to="/docs/api/composables/use-lazy-fetch"} Read more about `useLazyFetch`. :: ::read-more{to="/docs/api/composables/use-lazy-async-data"} Read more about `useLazyAsyncData`. :: ### Client-only fetching By default, data fetching composables will perform their asynchronous function on both client and server environments. Set the `server` option to `false` to only perform the call on the client-side. On initial load, the data will not be fetched before hydration is complete so you have to handle a pending state, though on subsequent client-side navigation the data will be awaited before loading the page. Combined with the `lazy` option, this can be useful for data that is not needed on the first render (for example, non-SEO sensitive data). ```ts twoslash /* This call is performed before hydration */ const articles = await useFetch('/api/article') /* This call will only be performed on the client */ const { pending, data: comments } = useFetch('/api/comments', { lazy: true, server: false }) ``` The `useFetch` composable is meant to be invoked in setup method or called directly at the top level of a function in lifecycle hooks, otherwise you should use [`$fetch` method](#fetch). ### Minimize payload size The `pick` option helps you to minimize the payload size stored in your HTML document by only selecting the fields that you want returned from the composables. ```vue ``` If you need more control or map over several objects, you can use the `transform` function to alter the result of the query. ```ts const { data: mountains } = await useFetch('/api/mountains', { transform: (mountains) => { return mountains.map(mountain => ({ title: mountain.title, description: mountain.description })) } }) ``` ::note Both `pick` and `transform` don't prevent the unwanted data from being fetched initially. But they will prevent unwanted data from being added to the payload transferred from server to client. :: ### Caching and refetching #### Keys [`useFetch`](/docs/api/composables/use-fetch) and [`useAsyncData`](/docs/api/composables/use-async-data) use keys to prevent refetching the same data. - [`useFetch`](/docs/api/composables/use-fetch) uses the provided URL as a key. Alternatively, a `key` value can be provided in the `options` object passed as a last argument. - [`useAsyncData`](/docs/api/composables/use-async-data) uses its first argument as a key if it is a string. If the first argument is the handler function that performs the query, then a key that is unique to the file name and line number of the instance of `useAsyncData` will be generated for you. ::tip To get the cached data by key, you can use [`useNuxtData`](/docs/api/composables/use-nuxt-data) :: #### Refresh and execute If you want to fetch or refresh data manually, use the `execute` or `refresh` function provided by the composables. ```vue twoslash ``` The `execute` function is an alias for `refresh` that works in exactly the same way but is more semantic for cases when the fetch is [not immediate](#not-immediate). ::tip To globally refetch or invalidate cached data, see [`clearNuxtData`](/docs/api/utils/clear-nuxt-data) and [`refreshNuxtData`](/docs/api/utils/refresh-nuxt-data). :: #### Clear If you want to clear the data provided, for whatever reason, without needing to know the specific key to pass to `clearNuxtData`, you can use the `clear` function provided by the composables. ```vue twoslash ``` #### Watch To re-run your fetching function each time other reactive values in your application change, use the `watch` option. You can use it for one or multiple _watchable_ elements. ```vue twoslash ``` Note that **watching a reactive value won't change the URL fetched**. For example, this will keep fetching the same initial ID of the user because the URL is constructed at the moment the function is invoked. ```vue ``` If you need to change the URL based on a reactive value, you may want to use a [computed URL](#computed-url) instead. #### Computed URL Sometimes you may need to compute an URL from reactive values, and refresh the data each time these change. Instead of juggling your way around, you can attach each param as a reactive value. Nuxt will automatically use the reactive value and re-fetch each time it changes. ```vue ``` In the case of more complex URL construction, you may use a callback as a [computed getter](https://vuejs.org/guide/essentials/computed.html) that returns the URL string. Every time a dependency changes, the data will be fetched using the newly constructed URL. Combine this with [not-immediate](#not-immediate), and you can wait until the reactive element changes before fetching. ```vue ``` If you need to force a refresh when other reactive values change, you can also [watch other values](#watch). ### Not immediate The `useFetch` composable will start fetching data the moment is invoked. You may prevent this by setting `immediate: false`, for example, to wait for user interaction. With that, you will need both the `status` to handle the fetch lifecycle, and `execute` to start the data fetch. ```vue ``` For finer control, the `status` variable can be: - `idle` when the fetch hasn't started - `pending` when a fetch has started but not yet completed - `error` when the fetch fails - `success` when the fetch is completed successfully ## Passing Headers and cookies When we call `$fetch` in the browser, user headers like `cookie` will be directly sent to the API. But during server-side-rendering, since the `$fetch` request takes place 'internally' within the server, it doesn't include the user's browser cookies, nor does it pass on cookies from the fetch response. ### Pass Client Headers to the API We can use [`useRequestHeaders`](/docs/api/composables/use-request-headers) to access and proxy cookies to the API from server-side. The example below adds the request headers to an isomorphic `$fetch` call to ensure that the API endpoint has access to the same `cookie` header originally sent by the user. ```vue ``` ::caution Be very careful before proxying headers to an external API and just include headers that you need. Not all headers are safe to be bypassed and might introduce unwanted behavior. Here is a list of common headers that are NOT to be proxied: - `host`, `accept` - `content-length`, `content-md5`, `content-type` - `x-forwarded-host`, `x-forwarded-port`, `x-forwarded-proto` - `cf-connecting-ip`, `cf-ray` :: ### Pass Cookies From Server-side API Calls on SSR Response If you want to pass on/proxy cookies in the other direction, from an internal request back to the client, you will need to handle this yourself. ```ts [composables/fetch.ts] import { appendResponseHeader, H3Event } from 'h3' export const fetchWithCookie = async (event: H3Event, url: string) => { /* Get the response from the server endpoint */ const res = await $fetch.raw(url) /* Get the cookies from the response */ const cookies = (res.headers.get('set-cookie') || '').split(',') /* Attach each cookie to our incoming Request */ for (const cookie of cookies) { appendResponseHeader(event, 'set-cookie', cookie) } /* Return the data of the response */ return res._data } ``` ```vue ``` ## Options API support Nuxt 3 provides a way to perform `asyncData` fetching within the Options API. You must wrap your component definition within `defineNuxtComponent` for this to work. ```vue ``` ::note Using ` ``` ### Custom serializer function To customize the serialization behavior, you can define a `toJSON` function on your returned object. If you define a `toJSON` method, Nuxt will respect the return type of the function and will not try to convert the types. ```ts [server/api/bar.ts] export default defineEventHandler(() => { const data = { createdAt: new Date(), toJSON() { return { createdAt: { year: this.createdAt.getFullYear(), month: this.createdAt.getMonth(), day: this.createdAt.getDate(), }, } }, } return data }) ``` ```vue [app.vue] ``` ### Using an alternative serializer Nuxt does not currently support an alternative serializer to `JSON.stringify`. However, you can return your payload as a normal string and utilize the `toJSON` method to maintain type safety. In the example below, we use [superjson](https://github.com/blitz-js/superjson) as our serializer. ```ts [server/api/superjson.ts] import superjson from 'superjson' export default defineEventHandler(() => { const data = { createdAt: new Date(), // Workaround the type conversion toJSON() { return this } } // Serialize the output to string, using superjson return superjson.stringify(data) as unknown as typeof data }) ``` ```vue [app.vue] ``` ## Recipes ### Consuming SSE (Server Sent Events) via POST request ::tip If you're consuming SSE via GET request, you can use [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or VueUse composable [`useEventSource`](https://vueuse.org/core/useEventSource/). :: When consuming SSE via POST request, you need to handle the connection manually. Here's how you can do it: ```ts // Make a POST request to the SSE endpoint const response = await $fetch('/chats/ask-ai', { method: 'POST', body: { query: "Hello AI, how are you?", }, responseType: 'stream', }) // Create a new ReadableStream from the response with TextDecoderStream to get the data as text const reader = response.pipeThrough(new TextDecoderStream()).getReader() // Read the chunk of data as we get it while (true) { const { value, done } = await reader.read() if (done) break console.log('Received:', value) } ```