---
title: "useApiFetch"
description: "An API request composable built on Nuxt useFetch, providing automatic authentication, business status code checking and Toast notifications."
canonical_url: "https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch"
---
# useApiFetch

> An API request composable built on Nuxt useFetch, providing automatic authentication, business status code checking and Toast notifications.

## Usage

Use the auto-imported `useApiFetch` composable for API requests. Built on top of Nuxt [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch), it provides automatic authentication, data unwrapping, business status code checking and unified error handling.

```vue
<script setup lang="ts">
interface User {
  id: number
  name: string
  email: string
}

// Basic usage (automatically unwraps the data field)
const { data, pending, error, refresh } = await useApiFetch<User[]>('/users')

// POST request
const { data } = await useApiFetch('/users', {
  method: 'POST',
  body: { name: 'test', email: 'test@example.com' }
})

// Use a different endpoint
const { data } = await useApiFetch('/users', { endpoint: 'v2' })
</script>
```

- `useApiFetch` inherits all features of Nuxt [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch) while providing additional API integration.
- Automatically retrieves the token from the session and adds it to request headers (via the `$api` instance).
- Automatically checks business status codes and throws errors.
- Built-in Toast notifications with customizable configuration.

## Data Request Patterns

Movk Nuxt provides three data request composables with identical signatures — choose based on execution timing:

| Composable | Execution | Blocks Navigation | Use Case |
| --- | --- | --- | --- |
| [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch) | SSR + CSR | Yes | Above-the-fold core data |
| [`useLazyApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#uselazyapifetch) | SSR + CSR | No | Secondary / non-above-the-fold data |
| [`useClientApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#useclientapifetch) | CSR only | No | Non-SEO-sensitive data |

`useApiFetch` fires the request during SSR, delivering data on first render:

```vue [ApiQuickstartSsrExample.vue]
<script setup lang="ts">
interface Profile {
  id: string
  name: string
  email: string
  role: string
}

const { data, pending, error, refresh } = await useApiFetch<Profile>('/profile')
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2 flex-wrap">
      <UBadge v-if="pending" color="warning" variant="subtle">
        pending
      </UBadge>
      <UBadge v-else-if="error" color="error" variant="subtle">
        error
      </UBadge>
      <UBadge v-else color="success" variant="subtle">
        ready
      </UBadge>
      <UButton size="sm" variant="outline" icon="i-lucide-refresh-cw" @click="refresh()">
        刷新
      </UButton>
    </div>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ error ? { error: error.message } : data }}</pre>
  </div>
</template>
```

## Data Unwrapping and Transformation

`useApiFetch` already receives the business data unwrapped by [`$api`](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#data-unwrapping-and-business-validation); the generic `T` directly declares that data type. `transform` receives the unwrapped data for a secondary transformation:

```ts
// Generic T directly declares the business data type (the type of the data field)
const { data } = await useApiFetch<User>('/user')
// data.value = { id: 1, name: 'test' }

// Combine with transform for a secondary transformation
const { data } = await useApiFetch<{ content: User[] }, SelectItem[]>('/users', {
  transform: ({ content }) => content.map(u => ({ label: u.name, value: u.id }))
})
```

> [!TIP]
> See: /en/docs/api/api-plugin#data-unwrapping-and-business-validation
> 
> See the 
> 
> $api
> 
>  page for interactive examples of the unwrapping mechanism and 
> 
> unwrap
> 
>  / 
> 
> businessCheck

## Business Status Code Checking

The `$api` interceptor automatically checks the business status code and throws an `ApiError` (see [Error Classification](#error-classification) below) when the code is not in `successCodes`. Pass `businessCheck: false` to disable validation, while the `dataKey` field is still unwrapped:

```ts
const { data } = await useApiFetch('/external', {
  businessCheck: false
})
```

When a whole endpoint returns no envelope, declare it on the endpoint `response` instead of passing options per request:

```ts
const { data } = await useApiFetch<SensorPoint[]>('/point-numbers', { endpoint: 'sensor' })
```

> [!TIP]
> See: /en/docs/api/api-plugin#endpoint-level-declaration
> 
> See the 
> 
> $api
> 
>  page for endpoint-level declaration and precedence

## Error Classification

Every failure becomes an [`ApiError`](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#apierror) (`NuxtError<ApiErrorData>`), kept intact by `useAsyncData`; distinguish scenarios with `error.value.data.kind`. Select an error type in the dropdown to observe the shape of `error.value`:

- `business`: HTTP 200 but `code` not in `successCodes`; `data.code` keeps the original business code.
- `http-400` / `http-500`: `kind` is `http` and `statusCode` the corresponding code; a GET 5xx is retried once by ofetch's default and reported only once.
- `http-422`: `data.response` carries additional server information.
- `network`: Connection forcibly cut; the request received no response.
- `timeout`: Exceeded the milliseconds set by `timeout`.

```vue [ApiErrorsExample.vue]
<script setup lang="ts">
const props = defineProps<{
  mode: 'business' | 'http-400' | 'http-422' | 'http-500' | 'network' | 'timeout'
}>()

const urlMap: Record<typeof props.mode, string> = {
  'business': '/demo/errors?type=business',
  'http-400': '/profile?fail=1',
  'http-422': '/demo/errors?type=422',
  'http-500': '/demo/errors?type=500',
  'network': '/demo/errors?type=network',
  'timeout': '/demo/errors?type=slow'
}

const { error, execute } = useApiFetch(() => urlMap[props.mode], {
  immediate: false,
  toast: false,
  retry: 0,
  timeout: 500
})

const info = computed(() => {
  const err = error.value
  if (!err) return null
  return {
    kind: err.data?.kind,
    statusCode: err.statusCode,
    message: err.message,
    code: err.data?.code ?? null,
    response: err.data?.response ?? null
  }
})
</script>

<template>
  <div class="flex flex-col gap-3">
    <UButton size="sm" color="error" variant="outline" icon="i-lucide-circle-alert" @click="execute()">
      触发 {{ mode }}
    </UButton>
    <p class="text-xs text-muted">
      所有失败统一为 <code>ApiError</code>（NuxtError），按 <code>error.data.kind</code> 区分场景。
    </p>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ info }}</pre>
  </div>
</template>
```

## Toast Notifications

The `toast` option supports per-request configuration: `false` to disable all, `{ success: false }` to keep only errors, `successMessage` / `errorMessage` for quick text, or a full set of [`Toast`](https://ui.nuxt.com/components/toast) props (`color`, `icon`, `duration`, etc.):

```ts
// Disable Toast / keep error only / quick text
await useApiFetch('/users', { toast: false })
await useApiFetch('/users', { toast: { success: false } })
await useApiFetch('/users', {
  toast: { successMessage: 'Created!', errorMessage: 'Failed, please retry' }
})

// Full Toast props
await useApiFetch('/users', {
  toast: {
    success: { title: 'Created', color: 'success', icon: 'i-lucide-circle-check' },
    error: { title: 'Failed', color: 'error', duration: 5000 }
  }
})

// Re-enable a globally disabled toast for one request
await useApiFetch('/users', { toast: { success: { show: true } } })

// Custom text counts as the same intent: it shows even when the toast is
// globally disabled or the method misses the whitelist
await useApiFetch('/users', { toast: { successMessage: 'Created!' } })
```

> [!NOTE]
> 
> Precedence: request-level 
> 
> show
> 
>  > request-level 
> 
> successMessage
> 
>  / 
> 
> errorMessage
> 
>  > global 
> 
> success.show
> 
>  / 
> 
> error.show
> 
>  / 
> 
> methods
> 
>  > global 
> 
> enabled
> 
> . With 
> 
> toast.success.show: false
> 
>  set globally, both 
> 
> { success: { show: true } }
> 
>  and 
> 
> { successMessage: '...' }
> 
>  still show the toast; pass 
> 
> { success: false }
> 
>  or 
> 
> { success: { show: false } }
> 
>  to stay silent.

> [!TIP]
> See: /en/docs/getting-started/configuration#toast-options
> 
> To notify only on POST / PUT / PATCH / DELETE, set 
> 
> toast.success.methods
> 
>  in the global or endpoint config — the field is not accepted per request

> [!TIP]
> See: /en/docs/api/api-plugin#toast-notifications
> 
> See interactive examples for five Toast modes on the 
> 
> $api
> 
>  page

## API

### useApiFetch()

`useApiFetch<T = unknown, DataT = T>(url: string | (() => string), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>`{lang="ts-type"}

Creates an API request.

#### Parameters

**url** (`string | (() => string)`) *required*: Request URL or a function returning the URL. Supports reactive URLs.

**options** (`UseApiFetchOptions<T, DataT>`): Request configuration options. Supports all Nuxt useFetch options plus additional API integration options.API Integration OptionsUse the specified endpoint configuration. Defaults to the default endpoint of $api.Toast notification configuration. Set to false to disable Toast.Success notification configuration. Can be a full Toast props object or false to disable success notifications.Error notification configuration. Can be a full Toast props object or false to disable error notifications.Quick text for success notifications. Equivalent to success: { title: '...' }.Quick text for error notifications. Equivalent to error: { title: '...' }.Whether to validate the business status code. Inherits the endpoint / global response.businessCheck when omitted; when false, no business ApiError is thrown but the dataKey field is still unwrapped.Whether to unwrap by dataKey. Inherits the endpoint / global response.unwrap when omitted; when false, returns the raw response body. Orthogonal to businessCheck.Request Options (inherited from useFetch)HTTP method. Defaults to 'GET'.URL query parameters, automatically serialized into the URL.Alias for query.Request body. Automatically serialized to JSON for POST/PUT/PATCH requests.Request headers.Base URL. Usually configured via the endpoint option; no need to set manually.Response HandlingFunction to transform response data. Receives the unwrapped business data and returns the final data.Select only the specified fields from the response data.Factory function to set a default value.Execution OptionsWhether to execute the request immediately. Set to false to call execute() manually. Defaults to true.Whether to use lazy mode. In lazy mode, client-side navigation is not blocked and data loads in the background. Defaults to false.Whether to execute the request on the server. Defaults to true.Reactive sources to watch; the request re-fires automatically on change. Can be a ref, reactive object or array.Whether to deep-watch the watch objects. Defaults to true.Caching and DeduplicationCustom cache key. Used for sharing data between requests or deduplication.Strategy for handling duplicate requests. Defaults to cancel.'cancel' — Cancel the pending request'defer' — Do not initiate a new requestFunction to retrieve data from cache. The return value is used as the initial data.Request HooksHook called before the request is sent. Merged with built-in hooks.onRequest({ request, options }) {
  console.log('Sending request:', request.url)
}
Hook called on request error. Merged with built-in hooks.onRequestError({ request, error }) {
  console.error('Request error:', error)
}
Hook called when a response is received. Built-in hooks run first, so response._data is already the unwrapped business data (unless unwrap is false); only fires on business success. Return values are ignored by ofetch — use transform for output transformations.onResponse({ response }) {
  console.log('Unwrapped data:', response._data)
}
Hook called on response error (4xx/5xx). Passed to ofetch as-is and fires on every failed attempt, including retries; use the movk:api:error hook for unified error handling.onResponseError({ response }) {
  console.error('Response error:', response.status)
}

#### Type Parameters

**T** (`type`): Business data type (already automatically unwrapped by $api). This is the data type of the data field in the API response.

**DataT** (`type`): The final type after transform conversion. Defaults to T.

#### Returns

Returns the response object of [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch#return-values), including:

**data** (`Ref<DataT | null>`): Response data (unwrapped and transformed). Initially null; updated to the actual data after a successful request.

**error** (`Ref<ApiError | null>`): Error object. Every failure is an ApiError; distinguish business, HTTP, network and timeout errors via data.kind.

**status** (`Ref<'idle' | 'pending' | 'success' | 'error'>`): Request status.'idle' — Not yet started (only when immediate: false)'pending' — Request in progress'success' — Request succeeded'error' — Request failed

**pending** (`Ref<boolean>`): Whether a request is in progress. Equivalent to status.value === 'pending'.

**refresh** (`(opts?: { dedupe?: boolean }) => Promise<void>`): Refresh data by re-executing the request. Alias: execute.// Refresh data
await refresh()

// Skip deduplication check and force refresh
await refresh({ dedupe: false })

**execute** (`(opts?: { dedupe?: boolean }) => Promise<void>`): Alias for refresh. Manually execute the request (commonly used with immediate: false).

**clear** (`() => void`): Clear state: sets data to null, error to null and status to 'idle'.

## useLazyApiFetch

### Usage

Use the auto-imported `useLazyApiFetch` composable for API requests. Equivalent to `useApiFetch(url, { ...options, lazy: true })`. In lazy mode the request does not block client-side navigation; the page renders immediately and data loads in the background.

```vue
<script setup lang="ts">
interface User {
  id: number
  name: string
  email: string
}

// Lazy-load user data
const { data, status } = useLazyApiFetch<User[]>('/users')
</script>

<template>
  <div>
    <div v-if="status === 'pending'">
      Loading...
    </div>
    <div v-else-if="status === 'error'">
      Failed to load
    </div>
    <div v-else-if="data">
      <div v-for="user in data" :key="user.id">
        {{ user.name }}
      </div>
    </div>
  </div>
</template>
```

- `useLazyApiFetch` does not block client-side navigation, making it suitable for non-critical data (user lists, comments, etc.).
- During client-side navigation `data` is initially `null` and `status` is `'pending'`; you must handle the loading state.
- Inherits all features of `useApiFetch` (auth, Toast, business status code checking, etc.).

> [!NOTE]
> 
> For data that is required on first render, use 
> 
> useApiFetch
> 
>  (non-lazy mode) to block navigation and ensure data is ready.

> [!TIP]
> See: /en/docs/api/use-api-fetch
> 
> See the 
> 
> useApiFetch
> 
>  documentation for full API options and feature descriptions

### Example

The page renders first, then enters the pending state. `data` is `null` until the response arrives; pair with `pending` / `status` to handle the loading state:

```vue [ApiQuickstartLazyExample.vue]
<script setup lang="ts">
interface Profile {
  id: string
  name: string
  email: string
}

const { data, pending, error, refresh } = useLazyApiFetch<Profile>('/profile')
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2 flex-wrap">
      <UBadge v-if="pending" color="warning" variant="subtle">
        pending
      </UBadge>
      <UBadge v-else-if="error" color="error" variant="subtle">
        error
      </UBadge>
      <UBadge v-else color="success" variant="subtle">
        ready
      </UBadge>
      <UButton size="sm" variant="outline" icon="i-lucide-refresh-cw" @click="refresh()">
        刷新
      </UButton>
    </div>
    <p class="text-xs text-muted">
      lazy 模式：页面先渲染再进入 pending；data 在拿到响应前为 null
    </p>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ error ? { error: error.message } : data }}</pre>
  </div>
</template>
```

### API

#### useLazyApiFetch()

`useLazyApiFetch<T = unknown, DataT = T>(url: string | (() => string), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>`{lang="ts-type"}

Creates a lazy API request.

##### Parameters

**url** (`string | (() => string)`) *required*: Request URL or a function returning the URL. Supports reactive URLs.

**options** (`UseApiFetchOptions<T, DataT>`): Request configuration options. Supports all options of useApiFetch.[!NOTE]The lazy option is forced to true; no need to specify it manually.

##### Type Parameters

**T** (`type`): Business data type (already automatically unwrapped by $api).

**DataT** (`type`): The final type after transform conversion. Defaults to T.

##### Returns

Same return value as [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#returns).

### Changelog

See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts).

## useClientApiFetch

### Usage

Use the auto-imported `useClientApiFetch` composable for client-only API requests. Equivalent to `useApiFetch(url, { ...options, server: false, lazy: true })`.

```vue
<script setup lang="ts">
interface UserPreferences {
  theme: 'light' | 'dark'
  language: string
  notifications: boolean
}

// Auto-execute on the client (request fires automatically after hydration)
const { data, pending } = useClientApiFetch<UserPreferences>('/user/preferences')

// Manually control execution timing (with immediate: false)
const { data: profile, execute } = useClientApiFetch<User>('/user/profile', {
  immediate: false
})
onMounted(() => execute())
</script>

<template>
  <div v-if="pending">Loading...</div>
  <div v-else>{{ data }}</div>
</template>
```

- `useClientApiFetch` inherits all features of [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch) (auth, Toast, business status code checking, etc.).
- Presets `server: false` + `lazy: true` — requests do not block navigation and execute only on the client.
- By default, fires automatically after hydration. Pass `immediate: false` for manual control.

> [!WARNING]
> 
> Due to 
> 
> server: false
> 
> , there is no data during SSR. On initial render 
> 
> data
> 
>  is 
> 
> null
> 
> ; use 
> 
> pending
> 
>  or 
> 
> status
> 
>  to manage the loading state.

### Example

Skips SSR; the request fires only after browser hydration. `data` is `null` on initial render during SSR:

```vue [ApiQuickstartClientExample.vue]
<script setup lang="ts">
interface Profile {
  id: string
  name: string
  email: string
}

const { data, pending, error, refresh } = useClientApiFetch<Profile>('/profile')
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2 flex-wrap">
      <UBadge v-if="pending" color="warning" variant="subtle">
        pending
      </UBadge>
      <UBadge v-else-if="error" color="error" variant="subtle">
        error
      </UBadge>
      <UBadge v-else color="success" variant="subtle">
        ready
      </UBadge>
      <UButton size="sm" variant="outline" icon="i-lucide-refresh-cw" @click="refresh()">
        刷新
      </UButton>
    </div>
    <p class="text-xs text-muted">
      client 模式：跳过 SSR，仅在浏览器挂载后发起请求
    </p>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ error ? { error: error.message } : data }}</pre>
  </div>
</template>
```

### API

#### useClientApiFetch()

`useClientApiFetch<T = unknown, DataT = T>(url: string | (() => string), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>`{lang="ts-type"}

Creates a client-only API request.

##### Parameters

**url** (`string | (() => string)`) *required*: Request URL or a function returning the URL.

**options** (`UseApiFetchOptions<T, DataT>`): Request configuration options. See useApiFetch for the full option reference.The following options are forced and cannot be overridden via options:server: false — Disables server-side executionlazy: true — Enables lazy mode (does not block navigation)

##### Type Parameters

Same as [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#type-parameters).

##### Returns

Same return value as [`useApiFetch`](https://nuxt.mhaibaraai.me/en/docs/api/use-api-fetch#returns).

### Changelog

See commit history for [src/runtime/composables/useApiFetch.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useApiFetch.ts).


## Sitemap

See the full [sitemap](https://nuxt.mhaibaraai.me/sitemap.md) for all pages.
