Creating an instance in Axios
An Axios instance keeps a baseline config, such as a base URL, a timeout and headers, so you do not repeat them on every call.
How it works
- Create the instance.
axios.create()takes a config object. Here it setsbaseURL,timeout, a custom header, and an offlineadapterthat reports what each request would send. [1] - Override a default for one request. The
/reportscall passes{ timeout: 30000 }. The echoed config shows 30000 for that call and 5000 for the others. [1] - Change defaults later. After the first calls the example writes an
Authorizationheader intoapi.defaults.headers.common. The next request carries it, while the globalaxiosobject keeps nobaseURL. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import axios from 'axios';
// Offline adapter: reports what the request would have sent
const echo = async (config) => ({
data: {
url: config.baseURL + config.url,
timeout: config.timeout,
custom: config.headers.get('X-Custom-Header'),
auth: config.headers.get('Authorization') || '(none)',
},
status: 200,
statusText: 'OK',
headers: {},
config,
});
const api = axios.create({
baseURL: '/api/v1',
timeout: 5000,
headers: { 'X-Custom-Header': 'foobar' },
adapter: echo,
});
const show = (label, { data }) =>
console.log(label.padEnd(10), data.url, '| timeout', data.timeout, '| custom', data.custom, '| auth', data.auth);
show('users', await api.get('/users/1'));
show('reports', await api.get('/reports', { timeout: 30000 }));
// Change instance defaults after creation
api.defaults.headers.common['Authorization'] = 'Bearer demo-token';
show('me', await api.get('/me'));
console.log('instance baseURL:', api.defaults.baseURL);
console.log('global axios baseURL:', axios.defaults.baseURL);
Each line shows the URL, timeout and headers the instance would use; try adding another default header. Code written by AgentGid [1].
Each line shows the URL, timeout and headers the instance would use; try adding another default header. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with axios 1.20.0. Needs WebGL.
More Axios examples
Custom adapters in Axios Interceptors in Axios Error handling in Axios transformResponse in Axios
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.