useAsyncData and $fetch. It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.
useFetch is a composable meant to be called directly in a setup function, plugin, or route middleware. It returns reactive composables and handles adding responses to the Nuxt payload so they can be passed from server to client without re-fetching the data on client side when the page hydrates.Usage
[app/pages/modules.vue]
data, status, and error are Vue refs, and they should be accessed with .value when used within the <script setup>, while refresh/execute and clear are plain functions.Parameters
The URL or request to fetch. Can be a string, a Request object, a Vue ref, or a function returning a string/Request. Supports reactivity for dynamic endpoints.
Configuration for the fetch request. Extends unjs/ofetch options and AsyncDataOptions. All options can be a static value, a
ref, or a computed value.Unique key for de-duplication. If not provided, generated from URL and options.
HTTP request method.
Query/search params to append to the URL. Objects are automatically stringified. Alias:
params.Request body. Objects are automatically stringified.
Request headers.
Base URL for the request.
Timeout in milliseconds to abort the request.
Whether to fetch on the server.
If true, resolves after route loads (does not block navigation).
If false, prevents request from firing immediately.
Factory for default value of
data before async resolves.Function to transform the result after resolving.
Function to return cached data.
Only pick specified keys from the result.
Array of reactive sources to watch and auto-refresh.
false disables watching.Return data in a deep ref object.
Avoid fetching same key more than once at a time.
cancel cancels existing requests. defer does not make new requests if there is a pending one.Custom $fetch implementation.
Interceptor called before the request. Can modify options.
Interceptor called on request errors.
Interceptor called after successful response.
Interceptor called on response errors.
Return Values
The result of the asynchronous fetch.
Function to manually refresh the data. By default, Nuxt waits until a
refresh is finished before it can be executed again. Also aliased as execute.Error object if the data fetching failed.
Status of the data request:
idle: Request has not started (e.g.{ immediate: false }or{ server: false }on server render)pending: Request is in progresssuccess: Request completed successfullyerror: Request failed
Resets
data to undefined (or the value of options.default() if provided), error to undefined, set status to idle, and cancels any pending requests.Examples
Query Parameters
Using thequery option, you can add search parameters to your query:
Interceptors
You can use interceptors to handle request and response events:Reactive URL
You can use a computed ref or a plain ref as the URL:[app/pages/[id].vue]