Skip to content

useFetchClient Composable ​

File Information ​

  • Path: app/composables/api/useFetchClient.ts
  • Purpose: Fetch client implementation (Axios-like API using Fetch API)
  • Category: Utility API Composable

Overview ​

The useFetchClient composable provides a Fetch-based HTTP client with Axios-like API, including interceptors, cancellation, and request/response handling. This is a lower-level utility used by the API client plugin.

Class: FetchClient ​

Constructor ​

typescript
constructor(context: NuxtContext)

Creates a new FetchClient instance with the provided Nuxt context.

Properties ​

  • context: NuxtContext - Nuxt context
  • config: NuxtContext['$config'] - Runtime config
  • defaults: { headers: Record<string, string> } - Default headers
  • requestInterceptors: RequestInterceptor[] - Request interceptors
  • responseInterceptors: ResponseInterceptor[] - Response interceptors

Methods ​

addRequestInterceptor ​

Adds a request interceptor.

typescript
addRequestInterceptor(
  onFulfilled?: (config: FetchConfig) => Promise<FetchConfig>,
  onRejected?: (error: any) => any
): void

addResponseInterceptor ​

Adds a response interceptor.

typescript
addResponseInterceptor(
  onFulfilled?: (response: FetchResponse) => Promise<FetchResponse>,
  onRejected?: (error: any) => any
): void

request ​

Main request method (similar to Axios).

typescript
request<T = any>(config: FetchConfig): Promise<FetchResponse<T>>

get, post, put, patch, delete ​

HTTP method helpers.

typescript
get<T = any>(url: string, config?: FetchConfig): Promise<FetchResponse<T>>
post<T = any>(url: string, data?: any, config?: FetchConfig): Promise<FetchResponse<T>>
put<T = any>(url: string, data?: any, config?: FetchConfig): Promise<FetchResponse<T>>
patch<T = any>(url: string, data?: any, config?: FetchConfig): Promise<FetchResponse<T>>
delete<T = any>(url: string, config?: FetchConfig): Promise<FetchResponse<T>>

isCancel ​

Checks if error is a cancellation error.

typescript
isCancel(error: any): boolean

CancelToken ​

CancelToken equivalent for compatibility.

typescript
CancelToken = {
  source: () => {
    token: AbortSignal | null
    cancel: (message?: string) => void
    controller: AbortController | null
  }
}

Features ​

Request Interceptors ​

Default request interceptor setup:

  1. Rate Limiting: Enqueues requests (placeholder)
  2. AbortController: Creates abort controller for cancellation
  3. Throttling: Adds throttle controller for specific endpoints
  4. Workspace ID: Automatically adds workspace_id from route params
  5. Authentication: Adds Authorization header from auth token

Response Interceptors ​

Default response interceptor setup:

  1. Cleanup: Removes cancel/throttle controllers
  2. Error Handling: Handles AbortError (cancellation)
  3. 401 Handling: Auto-logout on 401 errors
  4. Error Transformation: Transforms errors to standard format

URL Building ​

  • Handles base URL logic
  • Supports both internal (useApiBase: false) and external routes
  • Automatically adds query parameters
  • Normalizes multiple slashes

Request Options ​

  • Supports FormData (removes Content-Type header)
  • Supports JSON (stringifies object body)
  • Supports custom headers
  • Supports AbortController signal

Response Handling ​

  • Parses JSON responses
  • Parses text responses
  • Creates Axios-like response object
  • Handles non-2xx responses as errors

Usage ​

Direct Usage ​

typescript
import useFetchClient from '~/composables/api/useFetchClient'

const fetchClient = useFetchClient(context)

// Make request
const response = await fetchClient.get('/api/endpoint')
const data = response.data

Via API Client Plugin ​

The API client plugin uses this composable internally:

typescript
// In app/plugins/api-client.ts
const fetchClient = useFetchClient(nuxtApp)
nuxtApp.$api = fetchClient.request.bind(fetchClient)

With Cancellation ​

typescript
const { CancelToken } = useFetchClient(context)

const source = CancelToken.source()

fetchClient.get('/api/endpoint', {
  signal: source.token
})

// Cancel request
source.cancel('Request cancelled')

Type Definitions ​

typescript
import type {
  FetchConfig,
  FetchResponse,
  FetchRequestInterceptor,
  FetchResponseInterceptor,
  FetchNuxtContext,
} from '~/types'

Integration ​

The composable integrates with:

  • Cancel Token Manager: For request cancellation
  • Auth Module: For token injection
  • Runtime Config: For base URLs and configuration