Skip to main content

How to Set a Base URL in Axios in JavaScript

When making API requests with Axios, you often find yourself repeatedly typing the same base URL (e.g., https://api.example.com/). This is not only tedious but also makes your code harder to maintain if the API domain ever changes.

This guide will teach you the modern and standard methods for setting a base URL in Axios. You will learn the recommended best practice using axios.create(), as well as other methods for global defaults and per-request overrides.

For most applications, the best practice is to create a dedicated Axios "instance" for your API. This approach is clean, modular, and prevents you from modifying the global Axios object, which can be important in larger applications or when using third-party libraries.

The logic: the axios.create() method creates a new instance of Axios with a custom configuration. Any requests made with this instance will automatically use the configured baseURL.

For example, we want to avoid typing https://api.example.com for every request.

The solution:

  1. Create and export an instance in a dedicated file (e.g., api.js).
    src/api.js
    // In a file like `src/api.js`
    import axios from 'axios';

    const api = axios.create({
    baseURL: 'https://api.example.com',
    });

    export default api;
  2. Import and use this instance in your components or other files.
    src/components/MyComponent.js
    // In another file, e.g., `src/components/MyComponent.js`
    import api from '../api'; // Import your custom instance

    async function fetchPosts() {
    // The request will automatically go to 'https://api.example.com/posts'
    const response = await api.get('/posts');
    console.log(response.data);
    }

    fetchPosts();
note

This is the most scalable and maintainable approach, especially if your application needs to connect to multiple different APIs (you can create multiple instances).

Method 2: Setting a Global Default

For very simple projects with a single API, you can set a global default on the Axios object itself.

warning

Warning: This modifies the global Axios instance that is imported everywhere in your app, which can be considered a side effect.

The solution is to set the axios.defaults.baseURL property at the entry point of your application (e.g., index.js).

import axios from 'axios';

// Set the base URL for all future Axios requests
axios.defaults.baseURL = 'https://api.example.com';

// Now, in any other file, you can do this:
async function fetchTodos() {
const response = await axios.get('/todos/1');
console.log(response.data);
}

Method 3: Overriding the Base URL for a Specific Request

Sometimes, you have a base URL configured but need to make a single request to a completely different domain. You can override the baseURL for any individual request by providing it in the request config object.

Solution:

// Assume axios.defaults.baseURL or an instance is already set to another URL

axios({
method: 'get',
url: '/posts/1',
// This baseURL will be used for this request only
baseURL: 'https://api.example.com/',
}).then(response => {
console.log(response.data);
});

An Advanced Use Case: Setting the Base URL Dynamically

In some cases, the base URL might need to be determined dynamically (e.g., based on the environment or an async configuration). For this, interceptors are the perfect tool.

An interceptor is a function that Axios calls for every request. You can use a request interceptor to modify the request config before it is sent.

import axios from 'axios';

const api = axios.create(); // Create an instance without a base URL initially

async function getBaseUrl() {
// Imagine this is an async function that fetches config
return 'https://api.example.com';
}

// Add a request interceptor
api.interceptors.request.use(async (config) => {
config.baseURL = await getBaseUrl();
return config;
});

// Now, any request made with this instance will first resolve the base URL
api.get('/posts/1').then(response => {
console.log(response.data);
});

Conclusion: Which Method Should You Use?

Choosing the right method depends on the complexity of your application.

  • axios.create() (Method 1): This is the recommended best practice for most applications. It is modular, scalable for multiple APIs, and avoids global side effects.
  • axios.defaults.baseURL (Method 2): This is a quick and simple solution for small, single-API projects.
  • Per-Request baseURL (Method 3): Use this for one-off exceptions to your main API endpoint.
  • Interceptors (Method 4): Use this for advanced, dynamic configuration where the base URL is not known at startup.