Skip to main content

Overview

The FetchHooks interface provides lifecycle hooks that allow you to intercept and handle different stages of the fetch request process.

Type Signature

Hooks

onRequest

FetchHook<FetchContext<T, R>> | FetchHook<FetchContext<T, R>>[]
Called before the request is sent. Use this to modify request options, add headers, or log requests.
Context Parameters:
FetchRequest
The request URL or Request object
ResolvedFetchOptions<R>
Resolved request options that will be used for the fetch
FetchResponse<T> | undefined
Undefined at this stage
Error | undefined
Undefined at this stage
Example:

onRequestError

FetchHook<FetchContext<T, R> & { error: Error }> | FetchHook<FetchContext<T, R> & { error: Error }>[]
Called when the request fails to execute (network error, timeout, etc.). Does not include HTTP error responses (4xx, 5xx) - use onResponseError for those.
Context Parameters:
FetchRequest
The request URL or Request object
ResolvedFetchOptions<R>
Request options used for the fetch
Error
required
The error that occurred during the request
FetchResponse<T> | undefined
Undefined for network errors
Example:

onResponse

FetchHook<FetchContext<T, R> & { response: FetchResponse<T> }> | FetchHook<FetchContext<T, R> & { response: FetchResponse<T> }>[]
Called after a successful response is received (any status code). Use this to log responses, modify response data, or handle specific status codes.
Context Parameters:
FetchRequest
The request URL or Request object
ResolvedFetchOptions<R>
Request options used for the fetch
FetchResponse<T>
required
The fetch response object with parsed data in _data property. See FetchResponse.
Error | undefined
Undefined for successful responses
Example:

onResponseError

FetchHook<FetchContext<T, R> & { response: FetchResponse<T> }> | FetchHook<FetchContext<T, R> & { response: FetchResponse<T> }>[]
Called when the response has an HTTP error status (4xx or 5xx). Use this to handle specific error cases before the error is thrown.
Context Parameters:
FetchRequest
The request URL or Request object
ResolvedFetchOptions<R>
Request options used for the fetch
FetchResponse<T>
required
The fetch response object with error status. See FetchResponse.
Error | undefined
May contain the error that will be thrown
Example:

Multiple Hooks

You can provide multiple hooks as an array. They will be called in order:

Async Hooks

Hooks can be asynchronous:

Global Hooks

Set hooks globally when creating a fetch instance:

Type Parameters

any
default:"any"
The expected type of the response data
ResponseType
default:"ResponseType"
The response type. See ResponseType.