Axios: use same interceptor with multiple axios instances

Viewed 2215

In my code base there are various Axios instances created using

axios.create()

because there are multiple base URLs used in my app. So per baseURL we have created a corresponding Axios instance.

Now in App.js file, I have included 2 interceptors

  1. request interceptor
  2. response interceptor
axios.interceptors.response.use(
        config => {
          return config;
        },
        error => {          
          if (error && error.response.status === 401) {
              signOut();
          }
          return Promise.reject(error);
        }
      );

But all the API calls are by-passing the above-mentioned 2 interceptors.

Problem:

I want to use the above-mentioned interceptors as the Global interceptors for all the Axios instances in my project.

1 Answers

First Option - "Easier"

Just create your own "axios generator" function.

const createAxios = (baseURL) => {
   const newInstance = axios.create({ baseURL });

   newInstance.interceptors.response.use(
      (config) => config,
      (error) => {
        if (error && error.response.status === 401) {
          signOut();
        }
        return Promise.reject(error);
      }
    );

    return newInstance;
}

Second Option - More Complicated Personally I prefer this option, as I find it more tidy, and logically separated and divided (each "entity" stands by itself).

What i would probably do is create a BasicService Class which would look something like this:

import axios from 'axios';

class BasicService {
  constructor(url) {
    const options = {
      baseURL: url,
      // any options that you would want for all axios requests,
      // like (proxy, etc...)
    };
    
    this.fetcher = axios.create(options);

    // Your default config
    this.fetcher.interceptors.response.use(
      (config) => {
        return config;
      },
      (error) => {
        if (error && error.response.status === 401) {
          signOut();
        }
        return Promise.reject(error);
      }
    );
  }
}

then for each axios instance i would like to create, i would also create a class with all fetches. like:

const baseURL= '/users';

class UserService extends Service {
  // GET Requests
  async GetAll() {
    return (await this.fetcher.get('/all')).data;
  }

  // POST Requests
  async insertUser(userToInsert) {
    return await this.fetcher.post(...)
  }
}

const userService = new UserService(baseURL);

export default userService;

then in any file i would just import my wanted service and fetch it

import UserService from "/services/UserService";
UserService.getAll().then(...);

This helps you keep the same config for all axios instances while keeping your code as generic and clean as possible

Related