Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

We could pass in the value into the constructor, and pass it to the initInstance method, then return the URL contingent on the value of isAdmin.

class AxiosService {
    // ...

  constructor(isAdmin = false) {
    this.initInstance(isAdmin);
  }

  initInstance(isAdmin) {
    this.axiosInstance = axios.create({
      baseURL: isAdmin ? '/api/admin/v1' : '/api/v1',
      timeout: 5000
    });
        
        // ...
  }
    
    // ...
}

To use these, we'd now go...

const axiosService = new AxiosService(true); // admin url will be used
about 4 years ago · Juan Pablo Isaza Report

0

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;

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!