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:
- Relative Paths: If the
urlprovided to a request method is a relative path (e.g.,usersor/users), Axios combines it withbaseURL. - Slash Normalization: Axios handles overlapping or
missing slashes automatically.
- If
baseURLends with a slash (https://api.example.com/v1/) and the requested path starts with a slash (/users), Axios removes the duplicate slash, resulting inhttps://api.example.com/v1/users. - If neither contains a separating slash
(
https://api.example.com/v1andusers), Axios inserts a slash between them.
- If
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:
- Node.js: The resolved full URL is passed directly
to the native
httporhttpsmodules. If nobaseURLis set and a relative URL is used, Node.js throws an error because it lacks an implicit origin. - Browser: If
baseURLis not set and a relative URL is passed, the browser resolves the request against the current document's origin (window.location.origin).