Skip to content
On this page

Hooks

Hooks are async interceptors to hook into lifecycle events of the HTTP Request and Response. Hooks can be configured both for Services and their Requests. Service hooks run before their corresponding Request hook rather than overwritting them. This allows adding additional functionality at the Request level, while retaining base functionality common to all Requests in the Service.

Hooks overview

Hooks are optional and can be declared by using export default {} to export object containing any of the following methods:

ts
export default {
  onRequest: async ({ request, options }) => {},
  onRequestError: async ({ request, options, error }) => {},
  onResponse: async ({ request, options, response }) => {},
  onResponseError: async ({ request, options, response }) => {},
}

Hook Types

There are four types of hooks:

  • onRequest: runs before the fetch request is dispatched. Allows modifying request and options
  • onRequestError: runs if the fetch request fails. Allows modifying request, options and error
  • onResponse: runs after the fetch response returns (after response.body is parsed and set to response._data). Allows modifying request, options and response
  • onResponseError: runs if the fetch response fails (when response.ok is not true). Allows modifying request, options and response

Examples

ts
export default {
  onRequest: async ({ request, options }) => {
    // modify request url:
    request = request.replace('/v1', '/v2')
    // add request headers (e.g. authorization):
    options.headers.Authorization = `Bearer ${getToken()}`
    // modify request method:
    options.method = 'POST'
  },
  onRequestError: async ({ request, options, error }) => {
    // handle errors:
    console.error(error)
  },
  onResponse: async ({ request, options, response }) => {
    // transform response data ('_data' contains parsed response body):
    response._data = response._data.filter(item => item.completed)
  },
  onResponseError: async ({ request, options, response }) => {
    // handle errors:
    console.error(error)
  },
}
Hooks has loaded