# Data Fetching Nuxt provides `useFetch`, `useLazyFetch`, `useAsyncData` and `useLazyAsyncData` to handle data fetching within your application. ::alert{icon=👉} **`useFetch`, `useLazyFetch`, `useAsyncData` and `useLazyAsyncData` only work during `setup` or `Lifecycle Hooks`** :: ## `useAsyncData` Within your pages, components and plugins you can use `useAsyncData` to get access to data that resolves asynchronously. ### Usage ```ts const { data: Ref, pending: Ref, refresh: (force?: boolean) => Promise, error?: any } = useAsyncData( key: string, handler: (ctx?: NuxtApp) => Promise, options?: { lazy: boolean, server: boolean, watch: WatchSource[] } ) ``` ### Params * **key**: a unique key to ensure that data fetching can be properly de-duplicated across requests * **handler**: an asynchronous function that returns a value * **options**: * _lazy_: whether to resolve the async function after loading the route, instead of blocking navigation (defaults to `false`) * _default_: a factory function to set the default value of the data, before the async function resolves - particularly useful with the `lazy: true` option * _server_: whether to fetch the data on server-side (defaults to `true`) * _transform_: a function that can be used to alter `handler` function result after resolving * _pick_: only pick specified keys in this array from `handler` function result * _watch_: watch reactive sources to auto refresh Under the hood, `lazy: false` uses `` to block the loading of the route before the data has been fetched. Consider using `lazy: true` and implementing a loading state instead for a snappier user experience. ### Return values * **data**: the result of the asynchronous function that is passed in * **pending**: a boolean indicating whether the data is still being fetched * **refresh**: a function that can be used to refresh the data returned by the `handler` function * **error**: an error object if the data fetching failed By default, Nuxt waits until a `refresh` is finished before it can be executed again. Passing `true` as parameter skips that wait. ### Example ```ts [server/api/count.ts] let counter = 0 export default () => { counter++ return JSON.stringify(counter) } ``` ```vue [app.vue] ``` ## `useLazyAsyncData` This composable behaves identically to `useAsyncData` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function). ### Example ```vue ``` ## `useFetch` Within your pages, components and plugins you can use `useFetch` to universally fetch from any URL. This composable provides a convenient wrapper around `useAsyncData` and `$fetch`. It automatically generates a key based on URL and fetch options, as well as infers API response type. ### Usage ```ts const { data: Ref, pending: Ref, refresh: (force?: boolean) => Promise, error?: any } = useFetch(url: string, options?) ``` Available options: * `key`: Provide a custom key * Options from [ohmyfetch](https://github.com/unjs/ohmyfetch) * `method`: Request method * `params`: Query params * `headers`: Request headers * `baseURL`: Base URL for the request * Options from `useAsyncData` * `lazy` * `server` * `default` * `pick` * `transform` The object returned by `useFetch` has the same properties as that returned by `useAsyncData` ([see above](#useasyncdata)). ### Example ```vue [app.vue] ``` ## `useLazyFetch` This composable behaves identically to `useFetch` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function). ### Example ```vue ``` ## `refreshNuxtData` Invalidate the cache of `useAsyncData`, `useLazyAsyncData`, `useFetch` and `useLazyFetch` and trigger the refetch. This method is useful if you want to refresh all the data fetching for a current page. ### Usage ```ts refreshNuxtData(keys?: string | string[]) ``` Available options: * `keys`: Provides an array of keys that used in `useAsyncData` to refetch. When it's not specified, all `useAsyncData` and `useFetch` will be refetched. ### Example ```vue ``` ## Isomorphic fetch 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. ### Example: Bypass API headers to client We can use [`useRequestHeaders`](/docs/usage/ssr) 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 ``` ::alert{type="warning"} 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` :: ### Example: Pass on 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] export const fetchWithCookie = async (url: string, cookieName: string) => { const response = await $fetch.raw(url) if (process.server) { const cookies = Object.fromEntries( response.headers.get('set-cookie')?.split(',').map((a) => a.split('=')) ) if (cookieName in cookies) { useCookie(cookieName).value = cookies[cookieName] } } return response._data } ``` ```vue ``` ## Best practices The data returned by these composables will be stored inside the page payload. This means that every key returned that is not used in your component will be added to the payload. ::alert{icon=👉} **We strongly recommend you only select the keys that you will use in your component.** :: Imagine that `/api/mountains/everest` returns the following object: ```json { "title": "Mount Everest", "description": "Mount Everest is Earth's highest mountain above sea level, located in the Mahalangur Himal sub-range of the Himalayas. The China–Nepal border runs across its summit point", "height": "8,848 m", "countries": [ "China", "Nepal" ], "continent": "Asia", "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Everest_kalapatthar.jpg/600px-Everest_kalapatthar.jpg" } ``` If you plan to only use `title` and `description` in your component, you can select the keys by chaining the result of `$fetch` or `pick` option: ```vue ``` ## Using async setup If you are using `async setup()`, the current component instance will be lost after the first `await`. (This is a Vue 3 limitation.) If you want to use multiple async operations, such as multiple calls to `useFetch`, you will need to use ` ```