Skip to content

How to update this axios service for being able conditionally decide which API URL to use?

I have the following axis service:

   const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

I need conditionally pass isAdmin from outside for being able to switch the API URL here. How can be it achieved.

Answer

You can use multiple instances for each baseURL and call the instance by isAdmin condition. However, you can config the defaults that will be applied to every request.

import axios from "axios";
    
/* default config for each request */
axios.defaults.headers['Authorization'] = 'Bearer ' + token;
axios.defaults.timeout = 1000;

const adminAxios = axios.create({
    baseURL: 'https://some-domain.com/api/'
});
    
const nonAdminAxios = axios.create({
    baseURL: 'https://other-some-domain.com/api/'
});
    
    
const getInstance = (isAdmin) => isAdmin ? adminAxios : nonAdminAxios;