How to Use Axios Interceptors in SPAs

How to Use Axios Interceptors in SPAs

When building Single Page Applications (SPAs), managing API calls and handling responses effectively is crucial for a smooth user experience. One powerful tool for this purpose is Axios, a promise-based HTTP client that offers a feature called interceptors. In this article, we’ll explore how to use Axios interceptors to streamline your API interactions in SPAs.

What Are Axios Interceptors?

Axios interceptors allow you to intercept requests or responses before they are handled by `.then()` or `.catch()`. This provides an opportunity to perform operations on either the request or response, such as modifying headers, handling errors, or logging requests.

Setting Up Axios Interceptors

First, make sure you have Axios installed in your project. You can do this using npm:

npm install axios

Next, you can create an Axios instance and apply interceptors to that instance. Here is a typical setup:

import axios from 'axios';
const axiosInstance = axios.create({
  baseURL: 'https://api.example.com', // Your API base URL
  timeout: 1000,                      // Timeout for requests
});
// Add a request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before the request is sent
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    return config;
  },
  function (error) {
    // Handle request error
    return Promise.reject(error);
  }
);
// Add a response interceptor
axiosInstance.interceptors.response.use(
  function (response) {
    // Any status code that lies within the range of 2xx causes this function to trigger
    // Do something with response data
    return response.data;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx causes this function to trigger
    console.error('API Error:', error.message);
    return Promise.reject(error);
  }
);

Using Axios Interceptors to Handle Authentication

One common use case for interceptors is handling authentication tokens. By adding an "Authorization" header to every outgoing request, you can ensure that your API calls are authenticated:

axiosInstance.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

Error Handling with Axios Interceptors

Handling errors globally can improve user experience. Instead of duplicating error handling code in every API call, you can manage it centrally with interceptors:

axiosInstance.interceptors.response.use(
  response => response,
  error => {
    // Global error handling
    if (error.response) {
      // Server-side errors
      if (error.response.status === 401) {
        console.error('Unauthorized access - Redirecting to Login');
        // Redirect to login page
      } else {
        const message = error.response.data.message || 'An error occurred';
        alert(message);
      }
    } else {
      // Network or other errors
      alert('Network error occurred. Please try again later.');
    }
    return Promise.reject(error);
  }
);

Using Axios Interceptors for Request Logging

Another beneficial use case is logging each request. You can log the request method, URL, and data for debugging purposes:

axiosInstance.interceptors.request.use(config => {
  console.log(`Making request to ${config.url} with method ${config.method}`);
  return config;
});

Conclusion

Using Axios interceptors is a powerful way to manage API interactions in your Single Page Applications. By leveraging request and response interceptors, you can enhance authentication, streamline error handling, and log requests effectively. Implementing these practices can lead to cleaner code and a more robust application.

Start using Axios interceptors in your SPAs today to improve your API management strategy!