Available Hooks
There are four lifecycle hooks available:onRequest- Called before the request is sentonRequestError- Called when the request fails (network error, invalid URL, etc.)onResponse- Called after a successful response is receivedonResponseError- Called when the response status is 4xx or 5xx
Hook Signatures
All hooks receive aFetchContext object with the following properties:
onRequest
Called before the request is sent. Use this to modify headers, add authentication, log requests, etc.(context: FetchContext) => void | Promise<void>
Hook called before the request is sent. Can be a single function or an array of functions.
Adding Authentication
Logging Requests
Modifying Request Body
Multiple Request Hooks
onRequestError
Called when the request fails before receiving a response (network errors, invalid URLs, etc.).(context: FetchContext & { error: Error }) => void | Promise<void>
Hook called when the request fails. The context includes an
error property with the error details.onResponse
Called after a successful response is received (status < 400). Use this to transform responses, cache data, or log responses.(context: FetchContext & { response: FetchResponse }) => void | Promise<void>
Hook called after receiving a successful response. The context includes a
response property with the Response object.Logging Responses
Caching Responses
Transforming Response Data
Performance Monitoring
onResponseError
Called when the response status is 4xx or 5xx. Use this to handle errors globally, refresh tokens, or log errors.(context: FetchContext & { response: FetchResponse }) => void | Promise<void>
Hook called when the response status indicates an error (400-599). The context includes a
response property with the Response object.Global Error Handling
Token Refresh on 401
Error Logging
Hook Execution Order
Hooks are executed in this order:onRequesthooks (if request is valid)- Fetch request is made
onRequestError(if request fails) → throws erroronResponse(if status < 400)onResponseError(if status >= 400) → throws error