Interceptors
Interceptors are the ofetch callbacks onRequest, onResponse, onRequestError and onResponseError, passed to a single call. They see that call's fetch lifecycle and nothing else, which makes them the place for per-request concerns – a retry on one endpoint, a log line for one query. Both useMyApiData and $myApi accept them.
To cover every request instead, reach for a hook.
onRequest({ request, options })
The onRequest interceptor is called before the request is sent, letting you modify the request or options. Use for authentication headers, query parameters or request logging.
const { data } = await useMyApiData('posts', {
async onRequest({ request, options }) {
// Add dynamic authentication
const token = await getAuthToken()
if (token) {
options.headers.set('Authorization', `Bearer ${token}`)
}
// Log the request
console.log(`Making request to: ${request}`)
}
})onRequestError({ request, options, error })
The onRequestError interceptor is called when the request fails before being sent (network issues, timeout, etc.). Useful for logging infrastructure problems or implementing fallback strategies.
const { data } = await useMyApiData('posts', {
async onRequestError({ request, options, error }) {
// Log network errors to monitoring service
console.error(`Failed to send request to ${request}:`, error.message)
}
})onResponse({ request, options, response })
The onResponse interceptor is called for all responses, including both successful and error responses. Use for response processing, caching, or analytics.
const { data } = await useMyApiData('posts', {
async onResponse({ request, response, options }) {
// Log response metrics
console.log(`Response from ${request}: ${response.status} (${response.statusText})`)
// Handle specific status codes
if (response.status === 429) {
console.warn('Rate limit reached, consider implementing backoff strategy')
}
}
})onResponseError({ request, options, response })
The onResponseError interceptor is called when the response indicates an error (status codes 4xx, 5xx). Use for centralized error handling, retry logic or user notifications.
const { data } = await useMyApiData('posts', {
async onResponseError({ request, response, options }) {
const errorData = await response.json().catch(() => ({}))
// Log to error monitoring service
console.error(`API Error ${response.status}:`, errorData)
}
})