Skip to main content
ofetch provides powerful lifecycle hooks (interceptors) that allow you to intercept and modify requests and responses at different stages.

Available Hooks

There are four lifecycle hooks available:
  • onRequest - Called before the request is sent
  • onRequestError - Called when the request fails (network error, invalid URL, etc.)
  • onResponse - Called after a successful response is received
  • onResponseError - Called when the response status is 4xx or 5xx

Hook Signatures

All hooks receive a FetchContext 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:
  1. onRequest hooks (if request is valid)
  2. Fetch request is made
  3. onRequestError (if request fails) → throws error
  4. onResponse (if status < 400)
  5. onResponseError (if status >= 400) → throws error

Hook Error Handling

If a hook throws an error, the request is aborted and the error is thrown:
If you throw an error in a hook, the request will be aborted and the error will be propagated to the caller.

Complete Example: API Client with Interceptors