Skip to content

Shared Features ​

Both useFetch and useAsyncData wrappers share the same generated runtime features.

Overview ​

Generated composables currently support:

  • Nuxt module configuration through openapi in nuxt.config.ts
  • Lifecycle callbacks for each request
  • Global callback rules from a Nuxt plugin
  • Global headers from a composable or Nuxt plugin
  • pick and transform
  • Request interception through onRequest
  • Optional pagination helpers
  • Full type safety from the generated OpenAPI SDK

Features comparison ​

FeatureuseFetchuseAsyncDataSource
Module configurationYesYesNuxt module
Lifecycle callbacksYesYesGenerated runtime
Global callbacksYesYesGenerated runtime
Global headersYesYesGenerated runtime
Pick fieldsYesYesGenerated runtime
Request interceptionYesYesGenerated runtime
Pagination helpersYesYesGenerated runtime
Raw response variantNoYesGenerated runtime

Module configuration ​

Configure generation through the openapi key in nuxt.config.ts.

ts
export default defineNuxtConfig({
  modules: ['nuxt-openapi-hyperfetch'],
  openapi: {
    input: './swagger.yaml',
    output: './openapi',
    baseUrl: 'https://api.example.com',
    generators: ['useFetch', 'useAsyncData'],
  },
})

Learn more about module configuration

Callbacks ​

Each generated composable supports onRequest, onSuccess, onError, and onFinish.

ts
useFetchGetPetById(
  {
    path: { petId: 123 },
  },
  {
    onRequest: ({ url, headers }) => {
      console.log('Starting request to:', url)

      return {
        headers: {
          ...headers,
          'X-Request-ID': crypto.randomUUID(),
        },
      }
    },
    onSuccess: (data) => {
      console.log('Success!', data)
    },
    onError: (error) => {
      console.error('Failed!', error)
    },
    onFinish: () => {
      console.log('Request complete')
    },
  }
)

Learn more about callbacks

Global callbacks ​

Global callbacks are provided by a Nuxt plugin that exposes getGlobalApiCallbacks on the Nuxt app.

ts
// plugins/api-callbacks.ts
export default defineNuxtPlugin(() => {
  return {
    provide: {
      getGlobalApiCallbacks: () => ({
        onRequest: ({ headers }) => {
          const token = useCookie('auth-token').value

          if (!token) {
            return
          }

          return {
            headers: {
              ...headers,
              Authorization: `Bearer ${token}`,
            },
          }
        },
        onError: (error) => {
          if (error.status === 401) {
            navigateTo('/login')
          }
        },
      }),
    },
  }
})

skipGlobalCallbacks can disable all global rules with true, or disable only named lifecycle stages with an array such as ['onError'].

Learn more about global callbacks

Global headers ​

Global headers can come from either useApiHeaders() or a Nuxt plugin that provides getApiHeaders.

ts
// composables/useApiHeaders.ts
export const useApiHeaders = () => {
  const authToken = useCookie('auth-token')

  return {
    Authorization: authToken.value ? `Bearer ${authToken.value}` : '',
    'X-Client-Version': '1.0.0',
  }
}

Global headers are merged before request-specific headers, so per-request headers still win.

Learn more about global headers

Pick fields ​

Use pick to select specific fields from the response before transform runs.

ts
const { data } = useFetchGetPetById(
  {
    path: { petId: 123 },
  },
  {
    pick: ['id', 'name', 'status'] as const,
  }
)

Dot notation is supported for nested paths.

Learn more about pick fields

Request interception ​

Return partial request modifications from onRequest to alter headers, query params, or body before the request is sent.

ts
useFetchGetPets({}, {
  onRequest: ({ headers, query, body }) => ({
    headers: {
      ...headers,
      'X-Custom-Header': 'value',
    },
    query: {
      ...query,
      locale: 'en',
    },
    body: body
      ? {
          ...body,
          clientVersion: '1.0.0',
        }
      : undefined,
  }),
})

Learn more about request interception

Authentication and error handling ​

Authentication and centralized error handling are application patterns built on top of callbacks and global headers. They are not separate generated primitives.

Typical pattern:

  • Add auth headers globally through useApiHeaders() or getGlobalApiCallbacks
  • Handle shared error cases through global onError
  • Use skipGlobalCallbacks for public or exceptional requests

Learn more about authentication

Learn more about error handling →

Feature Architecture ​

         ┌─────────────────────────────────────────────────────┐
         │                                                     │
         ▼                                                     │
  ┌────────────┐                                              │
  │ Component  │                                              │
  └──────┬─────┘                                              │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │Generated Composable  │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │  Local Callbacks     │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │  Global Callbacks    │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │Request Interception  │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │  Nuxt Composable     │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │       API            │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │     Response         │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │Data Transformation   │                                    │
  └──────┬───────────────┘                                    │
         │                                                     │
         ▼                                                     │
  ┌──────────────────────┐                                    │
  │Success/Error Callbacks│                                   │
  └──────┬───────────────┘                                    │
         │                                                     │
         └─────────────────────────────────────────────────────┘

Next Steps ​

Explore each feature in detail:

Released under the Apache-2.0 License.