Interceptors

Intercept and modify requests before they are sent and responses before they are returned to your calling code.


Request Interceptors

Request interceptors execute in registration order before the request hits the network pipeline. Both synchronous and asynchronous interceptors are supported:

interceptors.ts
typescript
import { createClient } from 'react-native-fetch-client';

const api = createClient({ baseURL: 'https://api.example.com' });

// Add request interceptor
const reqInterceptorId = api.interceptors.request.use(
  async (config) => {
    // Dynamically inject or transform headers
    const currentLocale = await getDeviceLocale();
    config.headers = {
      ...config.headers,
      'X-Device-Locale': currentLocale,
    };
    return config;
  },
  (error) => {
    // Handle configuration errors
    return Promise.reject(error);
  }
);

// Remove the interceptor when no longer needed:
api.interceptors.request.eject(reqInterceptorId);

Response Interceptors

Response interceptors receive the decoded HttpResponse object. The rejection handler receives any caught FetchNativeError:

typescript
// Add response interceptor
const resInterceptorId = api.interceptors.response.use(
  (response) => {
    console.log(`[${response.config.method}] ${response.config.url} took ${response.durationMs}ms`);
    return response;
  },
  async (error) => {
    // Intercept errors (e.g. logging to Sentry or custom telemetry)
    if (error.status === 403) {
      showPermissionDeniedBanner();
    }
    return Promise.reject(error);
  }
);
Axios Compatibility
The api.interceptors.request.use() and .eject() API mirrors Axios exactly, making migration simple.