Skip to content

Composables

The useFetch and useAsyncData generators create type-safe composables for your Nuxt application. These composables wrap Nuxt's built-in data fetching composables with additional features.

What the CLI Adds

Generated composables enhance Nuxt's useFetch and useAsyncData with:

  • Type Safety: Request parameters and responses are fully typed from OpenAPI schemas
  • Lifecycle Callbacks: onRequest, onSuccess, onError, onFinish
  • Global Callbacks: Define callbacks once in a plugin, apply to all requests
  • Request Interception: Modify headers, body, query params before sending
  • SSR Compatible: Works seamlessly with Nuxt's server-side rendering
  • Zero Dependencies: Only uses Nuxt built-in APIs

Nuxt Documentation

Generated composables wrap Nuxt's built-in composables. For complete documentation on standard options like immediate, watch, server, lazy, transform, see:

Two Composable Types

useFetch Composables

Generated when using --generator useFetch:

typescript
const { data, pending, error, refresh } = useFetchGetPets()

Best for: Simple API calls, basic CRUD operations

Learn more about useFetch →

useAsyncData Composables

Generated when using --generator useAsyncData:

typescript
const { data, pending, error, refresh } = useAsyncDataGetPets()

Best for: Complex logic, data transformations, raw responses

Learn more about useAsyncData →

Shared Features

Both composable types share the same powerful features:

Callbacks

Execute code at different stages of the request lifecycle:

typescript
useFetchGetPet(
  { petId: 123 },
  {
    onRequest: () => console.log('Starting...'),
    onSuccess: (data) => console.log('Success!', data),
    onError: (error) => console.error('Failed!', error),
    onFinish: ({ success }) => console.log('Done!', success ? '✓' : '✗')
  }
)

Learn more about callbacks →

Global Callbacks

Define callbacks once in a plugin, apply them everywhere:

typescript
// plugins/api.ts
useGlobalCallbacks({
  onRequest: ({ headers }) => {
    headers['Authorization'] = `Bearer ${getToken()}`
  }
})

Learn more about global callbacks →

Request Interception

Modify requests before they're sent:

typescript
useFetchGetUsers({}, {
  onRequest: ({ headers, query }) => {
    headers['X-Custom'] = 'value'
    query.limit = 100
  }
})

Learn more about request interception →

Data Transformation

Transform response data with transform option:

typescript
useAsyncDataGetPets({}, {
  transform: (pets) => pets.map(p => ({ ...p, displayName: p.name.toUpperCase() }))
})

Learn more about data transformation →

Authentication

Add auth tokens and handle unauthorized responses:

typescript
useGlobalCallbacks({
  onRequest: ({ headers }) => {
    headers['Authorization'] = `Bearer ${getToken()}`
  },
  onError: (error) => {
    if (error.status === 401) {
      navigateTo('/login')
    }
  }
})

Learn more about authentication →

Error Handling

Centralized error handling with global callbacks:

typescript
useGlobalCallbacks({
  onError: (error) => {
    if (error.status === 404) {
      showToast('Resource not found', 'error')
    } else if (error.status >= 500) {
      showToast('Server error, please try again', 'error')
    }
  }
})

Learn more about error handling →

Quick Comparison

FeatureuseFetchuseAsyncData
CLI Features
Type Safety (from OpenAPI)✅ Full✅ Full
Callbacks (CLI adds)✅ Full✅ Full
Global Callbacks (CLI adds)✅ Full✅ Full
Nuxt Features
SSR Compatible✅ Yes✅ Yes
Raw Response❌ No✅ Yes
Data Transform✅ Yes✅ Yes
Cache KeyAutoAuto (custom optional)
Best ForSimple callsComplex logic

Architecture

      ┌───────────────────┐
      │  Your Component   │
      └─────────┬─────────┘


      ┌───────────────────────────┐
      │  Generated Composable     │  useFetchGetPets()
      └─────────┬─────────────────┘


      ┌───────────────────────────┐
      │useApiRequest /            │  Runtime helper
      │useApiAsyncData            │
      └─────────┬─────────────────┘


      ┌───────────────────────────┐
      │   Execute Callbacks       │  onRequest, onSuccess, etc.
      └─────────┬─────────────────┘


      ┌───────────────────────────┐
      │Nuxt useFetch /            │  Built-in Nuxt composables
      │useAsyncData               │
      └─────────┬─────────────────┘


      ┌───────────────────────────┐
      │      API Server           │
      └───────────────────────────┘
  1. Your Component calls the generated composable
  2. Generated Composable wraps request with type safety
  3. Runtime Helper executes callbacks and delegates to Nuxt
  4. Nuxt Composable makes the actual HTTP request
  5. API Server responds with data

Next Steps

Released under the Apache-2.0 License.