JAVASCRIPT

Centralized API Request Handling with Axios Interceptors

Efficiently manage API requests in JavaScript by using Axios interceptors to add common headers, handle errors, and refresh tokens globally.

import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://api.example.com/v1',
  timeout: 10000, // Request timeout in milliseconds
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request Interceptor: Add authorization token
apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('authToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Response Interceptor: Handle global errors, token refresh
apiClient.interceptors.response.use(
  response => response,
  async error => {
    const originalRequest = error.config;

    // Example: Handle 401 Unauthorized errors for token refresh
    if (error.response && error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        // Assume a refresh token endpoint exists
        const refreshToken = localStorage.getItem('refreshToken');
        const { data } = await axios.post('/auth/refresh-token', { refreshToken });

        localStorage.setItem('authToken', data.newToken);
        // Retry the original request with the new token
        originalRequest.headers.Authorization = `Bearer ${data.newToken}`;
        return apiClient(originalRequest); // Use the custom instance
      } catch (refreshError) {
        console.error('Failed to refresh token:', refreshError);
        // Redirect to login or clear auth data
        localStorage.removeItem('authToken');
        localStorage.removeItem('refreshToken');
        window.location.href = '/login';
        return Promise.reject(refreshError);
      }
    }

    // Example: Global error logging
    console.error('API Error:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

export default apiClient;

// How to use:
// import apiClient from './apiClient';
// apiClient.get('/users').then(response => console.log(response.data));
// apiClient.post('/products', { name: 'New Product' }).then(response => console.log(response.data));
How it works: This snippet demonstrates how to set up a centralized Axios instance with request and response interceptors. The request interceptor automatically adds an authorization token to outgoing requests if available. The response interceptor handles global error logging and includes an example of automatically refreshing an expired access token using a refresh token, then retrying the original failed request. This pattern ensures consistent handling of authentication and errors across all API calls.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs