Skip to content

Using Interceptors in `fetch‐like‐axios`

Alp edited this page Sep 25, 2024 · 4 revisions

Using Interceptors in fetch-like-axios

One of the powerful features of fetch-like-axios is its support for request and response interceptors. Interceptors allow you to modify or handle requests before they are sent, or responses before they are processed.

This functionality is useful for:

  • Automatically attaching authentication tokens.
  • Logging or modifying request/response data.
  • Centralized error handling.
  • Modifying response structures before passing them to your application.

Setting Up Request and Response Interceptors

In fetch-like-axios, you can easily add interceptors to handle or modify your requests and responses. Here’s how:

Request Interceptors

A request interceptor can be used to modify the request configuration before it's sent. For example, adding a custom authorization header to every request:

// Set a request interceptor
apiClient.setRequestInterceptor((config) => {
config.headers['Authorization'] = 'Bearer your-token-here';
console.log('Request Interceptor: Adding Authorization Header');
return config; // Don't forget to return the modified config!
});

Response Interceptors

A response interceptor allows you to handle or modify the response before it reaches your application. For instance, you can standardize error handling or modify the response structure:

// Set a response interceptor
apiClient.setResponseInterceptor((response) => {
  console.log('Response Interceptor: Handling response data');
  
  // Modify or log the response data
  if (response.error) {
    console.error('Error in response:', response.error);
  }
  
  return response; // Return the modified response
});

Combining Request and Response Interceptors

You can combine both request and response interceptors to create a powerful pipeline for handling all your HTTP requests.

// Example: Using both interceptors
apiClient.setRequestInterceptor((config) => {
  config.headers['Custom-Header'] = 'CustomValue';
  return config;
});

apiClient.setResponseInterceptor((response) => {
  if (response.status === 401) {
    // Handle unauthorized access (e.g., redirect to login)
    window.location = '/login';
  }
  return response;
});

Use Cases for Interceptors

  • Authentication: Automatically attach JWT tokens to all requests.
  • Logging: Log every outgoing request or incoming response for debugging.
  • Error Handling: Standardize error handling by intercepting responses and checking for errors.

Example: Implementing Global Authentication

Here’s a real-world scenario where interceptors can simplify authentication across all API calls. By using a request interceptor, you can attach your token to every outgoing request:

// Adding a token to every request
apiClient.setRequestInterceptor((config) => {
  const token = localStorage.getItem('authToken');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

And in the response interceptor, you can handle expired tokens or redirect users if needed:

// Handling expired tokens or unauthorized access
apiClient.setResponseInterceptor((response) => {
  if (response.status === 401) {
    console.log('Unauthorized! Redirecting to login...');
    window.location = '/login';
  }
  return response;
});