How to Update Axios Base URL Dynamically

Updating the base URL of an existing Axios instance dynamically is essential when handling environment switches, multi-tenant architectures, or dynamic server selection at runtime. This guide covers the standard methods to modify the baseURL property of an existing Axios instance without needing to recreate the client from scratch.

Method 1: Modifying instance.defaults.baseURL directly

The simplest and most common way to change the base URL for all subsequent requests is by mutating the defaults object on the existing Axios instance.

import axios from 'axios';

// 1. Create your initial Axios instance
const apiClient = axios.create({
  baseURL: 'https://api.v1.example.com',
  timeout: 5000,
});

// 2. Update the base URL dynamically
function updateBaseUrl(newUrl) {
  apiClient.defaults.baseURL = newUrl;
}

// Example usage:
updateBaseUrl('https://api.v2.example.com');

// Subsequent requests now use the updated base URL
apiClient.get('/users'); // Requests: https://api.v2.example.com/users

Method 2: Using Request Interceptors

If the base URL needs to change dynamically per request based on application state (such as an active user, token, or dynamic region), use a request interceptor to assign the baseURL dynamically before the request is dispatched.

import axios from 'axios';

const apiClient = axios.create();

// Dynamic state holder
let currentTenant = 'tenant-a';

// Add a request interceptor to evaluate baseURL on every request
apiClient.interceptors.request.use((config) => {
  config.baseURL = `https://${currentTenant}.example.com/api`;
  return config;
}, (error) => {
  return Promise.reject(error);
});

// Changing the variable dynamically routes future requests
currentTenant = 'tenant-b';
apiClient.get('/data'); // Requests: https://tenant-b.example.com/api/data

Summary of Best Practices