How Axios Base URL Resolution Works

This article provides an overview of how the Axios HTTP client automatically resolves base URLs. It covers the configuration of the baseURL property, the internal mechanism Axios uses to combine relative paths, how absolute URLs bypass the base URL, and best practices for configuring base URLs in instances.

The baseURL Configuration Property

In Axios, you can define a baseURL option globally or on a custom instance. When specified, Axios automatically prepends this URL to any relative URL passed to request methods (such as axios.get('/users')).

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

// Sends request to https://api.example.com/v1/users
api.get('/users');

How Path Combination Works

Axios handles URL resolution using an internal utility function often referred to as buildFullPath. This function determines how the baseURL and the requested url are joined together:

  1. Relative Paths: If the url provided to a request method is a relative path (e.g., users or /users), Axios combines it with baseURL.
  2. Slash Normalization: Axios handles overlapping or missing slashes automatically.
    • If baseURL ends with a slash (https://api.example.com/v1/) and the requested path starts with a slash (/users), Axios removes the duplicate slash, resulting in https://api.example.com/v1/users.
    • If neither contains a separating slash (https://api.example.com/v1 and users), Axios inserts a slash between them.

Absolute URLs Override baseURL

Axios checks whether the provided path is an absolute URL before applying the baseURL. An absolute URL is identified if it starts with a protocol scheme (like http://, https://, or // for protocol-relative URLs).

If you pass an absolute URL to an Axios instance configured with a baseURL, the baseURL is completely ignored for that specific request:

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

// The baseURL is ignored; request goes to https://other-domain.com/data
api.get('https://other-domain.com/data');

Browser vs. Node.js Environment Resolution

While Axios uses its internal path-combining logic across both Node.js and browser environments, standard environment URL parsing rules apply once the final URL is constructed: