How to Update Headers in an Existing Axios Instance
Updating headers on an existing Axios instance is a common task in modern web applications, particularly when handling authentication tokens, dynamic content types, or custom API keys. This guide covers the standard procedures for updating headers on an existing Axios client instance, including mutating instance defaults, dynamically updating headers with interceptors, and overriding headers on individual requests.
1. Mutating Instance Defaults Directly
The most straightforward way to update headers on an already
instantiated Axios client is by directly modifying the
defaults.headers object. This approach is ideal for global
values like authentication tokens set immediately after a user logs
in.
Updating Common Headers
To update a header applied to all HTTP methods (GET, POST, PUT, DELETE, etc.):
import axios from 'axios';
// Existing Axios instance
const apiClient = axios.create({
baseURL: 'https://api.example.com',
});
// Update the Authorization header
apiClient.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
// Add a custom header
apiClient.defaults.headers.common['X-Custom-Header'] = 'CustomValue';Updating Method-Specific Headers
To update headers exclusively for a specific HTTP method (e.g.,
POST or PUT):
// Update Content-Type specifically for POST requests
apiClient.defaults.headers.post['Content-Type'] = 'application/json';Removing a Header
To remove a header completely from the instance:
delete apiClient.defaults.headers.common['Authorization'];2. Using Request Interceptors (Recommended for Dynamic Headers)
Direct mutation can lead to race conditions or stale headers if your values change dynamically (such as refreshing expired JWTs). Using an Axios request interceptor ensures that the latest header values are evaluated right before every request is dispatched.
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
});
// Attach a request interceptor
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('authToken');
if (token) {
// For Axios v1.x and newer, use config.headers.set or direct assignment
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);Note: In Axios v1.x and later,
config.headers is an instance of AxiosHeaders.
You can also use the .set() method:
config.headers.set('Authorization', Bearer
${token});.
3. Overriding Headers on a Per-Request Basis
If you need to change or add a header for a single API call without altering the shared instance defaults, pass a configuration object directly into the request method.
// Overrides only for this specific GET request
apiClient.get('/user/profile', {
headers: {
'Cache-Control': 'no-cache',
'Authorization': 'Bearer temporary_override_token',
},
});Summary of Best Practices
- Use
apiClient.defaults.headers.commonwhen setting static, application-wide headers upon initialization or login/logout state changes. - Use Request Interceptors when header values are dynamic, asynchronous, or dependent on a central state store.
- Use Per-Request Configuration when modifying
headers for one-off operations, such as file uploads requiring
multipart/form-data.