JAVASCRIPT
Attaching JWT to API Requests Using Axios Interceptors
Implement an Axios interceptor to automatically add a JSON Web Token (JWT) from local storage to the Authorization header of every outgoing API request, simplifying authentication.
import axios from 'axios';
// Assume you have a function to retrieve the JWT from storage (e.g., localStorage)
const getAuthToken = () => {
return localStorage.getItem('jwt_token');
};
// Create an Axios instance (optional, but good practice for specific configurations)
const api = axios.create({
baseURL: 'https://api.example.com', // Your API base URL
headers: {
'Content-Type': 'application/json',
},
});
// Add a request interceptor
api.interceptors.request.use(
(config) => {
const token = getAuthToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// Do something with request error
return Promise.reject(error);
}
);
// Example usage:
async function fetchDataWithAuth() {
try {
const response = await api.get('/protected-resource');
console.log('Protected data:', response.data);
} catch (error) {
console.error('Error fetching protected data:', error.response ? error.response.data : error.message);
}
}
// To demonstrate: store a dummy token (in a real app, this would come from a login response)
localStorage.setItem('jwt_token', 'your_dummy_jwt_token_here');
fetchDataWithAuth();
How it works: This snippet shows how to use Axios interceptors to automatically include a JWT in the `Authorization` header of every API request. The `api.interceptors.request.use` method allows you to modify request configurations before they are sent. Here, it retrieves a JWT from `localStorage` and append it as a Bearer token. This centralizes authentication logic, preventing repetitive token attachment in individual API calls.