JAVASCRIPT
Centralized API Authentication with Axios Interceptors
Implement a centralized authentication strategy for API requests using Axios interceptors, automatically attaching tokens and handling token refreshes or logout.
import axios from 'axios';
// 1. Create an Axios instance
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000, // 10 seconds
headers: {
'Content-Type': 'application/json',
},
});
// 2. Request Interceptor: Attach authentication token
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken'); // Or from a state management solution
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 3. Response Interceptor: Handle errors, e.g., 401 Unauthorized
apiClient.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
// Example: Handle 401 Unauthorized - Token expired or invalid
if (error.response && error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true; // Mark request as retried
console.log('401 Unauthorized. Attempting to refresh token...');
try {
// Implement token refresh logic here
// const refreshToken = localStorage.getItem('refreshToken');
// const refreshResponse = await axios.post('/auth/refresh', { refreshToken });
// const newAccessToken = refreshResponse.data.accessToken;
// localStorage.setItem('accessToken', newAccessToken);
// For demonstration, let's just log and reject.
// In a real app, update originalRequest.headers.Authorization
// and then return apiClient(originalRequest)
console.warn('Token refresh not implemented in this snippet. User should re-authenticate.');
// Redirect to login or show re-authentication prompt
// window.location.href = '/login';
return Promise.reject(error); // Reject after failed refresh or if not attempting refresh
} catch (refreshError) {
console.error('Failed to refresh token:', refreshError);
// Clear tokens, redirect to login
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
// window.location.href = '/login';
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
// Export for use throughout the application
export default apiClient;
// Example Usage:
// async function getUserProfile() {
// try {
// // localStorage.setItem('accessToken', 'YOUR_VALID_TOKEN'); // Simulate a token
// const response = await apiClient.get('/users/me');
// console.log('User Profile:', response.data);
// } catch (error) {
// console.error('Failed to fetch user profile:', error.message);
// }
// }
// getUserProfile();
How it works: This snippet demonstrates how to use Axios interceptors to centralize API authentication logic. A request interceptor automatically attaches an access token (e.g., from `localStorage`) to the `Authorization` header of every outgoing request. A response interceptor is then used to catch specific error codes, such as `401 Unauthorized`. In a production application, this would trigger a token refresh mechanism, re-attempt the original request, or redirect the user to a login page, providing a robust and maintainable way to handle authentication across an entire application.