An axios Interceptor for the JWT
An axios Interceptor for the JWT
~13 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
Chapter 76 stores the token, but does NOT yet SEND it along – a request interceptor AUTOMATICALLY adds the Authorization header to EVERY outgoing request, EXACTLY as done by hand in chapter 50 with curl -H.
Registering the interceptor
import axios from 'axios';
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL,
headers: {
'Content-Type': 'application/ld+json',
},
});
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});EVERY call via apiClient (including the useProjects hook ALREADY written in chapter 75, WITHOUT having to touch it) NOW AUTOMATICALLY gets the header, IF a token exists.
Achtung: Direct localStorage access INSIDE the interceptor (instead of via useAuth()) is a DELIBERATE exception: interceptors run OUTSIDE the React component tree and can NOT use hooks – localStorage remains the PRAGMATIC, working solution here.
Catching 401 responses globally
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
}
return Promise.reject(error);
},
);A response interceptor catches 401 (chapter 50: missing/expired token) GLOBALLY – EVERY component AUTOMATICALLY benefits from a redirect to the login page, WITHOUT EVERY individual useQuery instance having to handle that ITSELF.
Testing the complete behavior
AFTER logging in (chapter 76), ProjectListPage (chapter 75) NOW ACTUALLY shows data – the TOKEN gets sent AUTOMATICALLY, EXACTLY as in the curl example from chapter 50, but WITHOUT this component itself having to know ANYTHING about authentication.
Tipp: THIS separation (components only know the API endpoints, the interceptor takes care OF authentication) is a COMMON pattern – if the auth strategy CHANGES LATER (e.g. switching to HTTP-only cookies), ONLY the interceptor needs adjusting, NO individual component.