v1.4.2

Interceptors

Interceptors are powerful middleware hooks that allow you to modify the request configuration before it is sent, or intercept the response before it reaches your application code.

They are defined when you create a client using configureBoltFetchClient.

Request Interceptor

The requestInterceptor is a function that receives the outgoing configuration object. You must return the modified configuration object.

This is the standard place to attach dynamic authentication tokens.

typescript
import { configureBoltFetchClient } from "boltfetch"; const apiClient = configureBoltFetchClient({ baseUrl: "https://api.example.com", requestInterceptor: (config) => { // Retrieve your token (e.g., from localStorage) const token = localStorage.getItem("token"); if (token) { config.headers = { ...config.headers, Authorization: `Bearer ${token}` }; } return config; } });

Response Interceptor

The responseInterceptor is a function that receives the response object. It allows you to log activities, mutate the response, or trigger global side-effects (like redirecting on a 401).

typescript
import { configureBoltFetchClient } from "boltfetch"; const apiClient = configureBoltFetchClient({ baseUrl: "https://api.example.com", responseInterceptor: (response) => { // We can log the status code and URL // 'response.config' contains the original request setup console.log(`[API ${response.config.reqType || 'REQ'}] ${response.config.url} - ${response.status}`); // You must return the response return response; } });

Global Authentication Strategy

Combining these interceptors allows you to handle both attaching tokens and reacting when those tokens expire.

typescript
const apiClient = configureBoltFetchClient({ baseUrl: "https://api.example.com", requestInterceptor: (config) => { const token = localStorage.getItem("token"); if (token) { config.headers = { ...config.headers, Authorization: `Bearer ${token}` }; } return config; }, responseInterceptor: (response) => { // If we receive a 401 Unauthorized, we know the token is invalid if (response.status === 401) { localStorage.removeItem("token"); window.location.href = "/login"; } return response; } });