How to Set Default Headers in Axios
Axios provides several built-in mechanisms to define and manage default HTTP headers across your application. This guide covers the three primary ways to set default headers in Axios: using global configuration defaults, creating custom Axios instances, and leveraging request interceptors for dynamic headers.
1. Global Default Headers
Axios allows you to define global default headers directly on the
main axios object. Once set, these headers apply to every
HTTP request made through the standard Axios module across your entire
application.
You can set headers for all request types using
headers.common, or target specific HTTP methods like
headers.post or headers.get:
import axios from 'axios';
// Applied to all HTTP methods (GET, POST, PUT, DELETE, etc.)
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
axios.defaults.headers.common['Accept'] = 'application/json';
// Applied only to POST requests
axios.defaults.headers.post['Content-Type'] = 'application/json';2. Custom Axios Instances
When your application communicates with multiple APIs or requires
different configurations for separate modules, creating custom instances
using axios.create() is the recommended approach. Each
instance maintains its own isolated default headers.
import axios from 'axios';
// Create an instance with predefined default headers
const apiClient = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
'X-Custom-Header': 'CustomValue'
}
});
// You can also update defaults on the instance dynamically
apiClient.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// Requests made with this instance will include the defined headers
apiClient.get('/users');3. Dynamic Headers via Request Interceptors
If your headers depend on runtime state—such as an authentication token retrieved from storage or refreshed before each call—built-in request interceptors provide the most flexible mechanism. Interceptors allow you to inspect, modify, or append headers right before a request is sent.
import axios from 'axios';
const client = axios.create({
baseURL: 'https://api.example.com'
});
client.interceptors.request.use((config) => {
const token = localStorage.getItem('authToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, (error) => {
return Promise.reject(error);
});Header Precedence and Merging
Axios merges headers in a specific hierarchy:
- Global defaults
(
axios.defaults.headers) have the lowest precedence. - Instance defaults
(
instance.defaults.headers) override global defaults. - Per-request configurations
(
axios.get(url, { headers: { ... } })) have the highest precedence and will override any conflicting defaults set globally or at the instance level.