Set Bearer Token for All Axios Requests
Setting up a Bearer token across all requests in Axios ensures that
your application automatically sends the necessary
Authorization header with every outgoing HTTP call. This
article explains how to configure global authorization headers in Axios
using default headers, custom instances, and dynamic request
interceptors.
Method 1: Setting Global Defaults
The fastest way to attach a Bearer token to all Axios calls is by
modifying the global defaults object. Once set, every
subsequent request made with the standard axios object will
include the specified header.
import axios from 'axios';
const token = 'YOUR_BEARER_TOKEN';
// Set the default Authorization header for all requests
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;To remove the token (for example, when a user logs out):
delete axios.defaults.headers.common['Authorization'];Method 2: Creating a Custom Axios Instance
Creating a dedicated Axios instance is recommended over mutating the global Axios object, especially when interacting with multiple APIs with different base URLs or authentication methods.
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_BEARER_TOKEN',
},
});
// Use the instance for your requests
apiClient.get('/user/profile');Method 3: Using Request Interceptors (Recommended for Dynamic Tokens)
If your token is updated frequently (such as after refreshing tokens)
or stored in browser storage (localStorage or
sessionStorage), using a request interceptor is the most
robust solution. An interceptor executes before every request, allowing
you to dynamically retrieve the latest token.
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
});
// Add a request interceptor
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('access_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
export default apiClient;Summary
- Use
axios.defaults.headers.commonfor simple setups with static tokens. - Use
axios.create()to isolate headers and configurations per API client. - Use Request Interceptors when tokens need to be retrieved dynamically before each request.