Stop Repeating Your Auth Logic: Centralizing API Workflows with Axios Interceptors
Stop manually adding auth tokens to every API call. Learn how to use Axios Interceptors to centralize authentication and error handling in your JavaScript applications.
16 Jan 2026, 18:44 UTC

The Boilerplate Burden
Most modern applications rely on a handful of API endpoints that all require the same set of headers—usually an Authorization token. Without a centralized strategy, developers often find themselves wrapping every single API call in a helper function or manually injecting tokens into every request configuration. This leads to fragile code: if the token key changes from Bearer to Token, you have to update every call site in the application.
The solution is the Axios Interceptor. Interceptors act as a middleware layer for your HTTP requests and responses, allowing you to define global logic that executes automatically before a request leaves the client or after a response arrives from the server.
Request Interceptors: Automating the Handshake
A request interceptor allows you to modify the configuration object before the request is dispatched. This is the ideal place to handle authentication. Instead of passing a token into every axios.get() or axios.post() call, the interceptor pulls the latest token from storage (like localStorage or a state manager) and attaches it to the headers.
Because interceptors support asynchronous operations, you can even perform checks—such as verifying if a token is expired—before allowing the request to proceed.
Response Interceptors: Unified Error Handling
Handling errors at the individual call site is tedious. If your server returns a 401 Unauthorized, you likely want the same behavior regardless of which page the user is on: clear the local session and redirect to the login screen.
Response interceptors allow you to catch these specific HTTP status codes in one place. You can resolve the response if it's successful or intercept the error object to trigger a global notification or a redirect, keeping your component-level try/catch blocks focused on business logic rather than infrastructure failures.
Worked Example: The Auth-Ready Instance
To avoid polluting the global Axios configuration, it is best practice to create a dedicated instance. This ensures that interceptors only apply to your specific API and not to third-party requests (like a call to a public weather API).
import axios from 'axios';
// 1. Create a dedicated instance
const apiClient = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
});
// 2. Request Interceptor: Inject JWT
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// 3. Response Interceptor: Handle 401s
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
console.error('Session expired. Redirecting to login...');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default apiClient;
Implementation Details
- Execution Context: Run this code in a separate
api.jsorhttp-client.tsfile. - Permissions: Ensure the environment has access to
localStorageor your chosen token store. - Expected Result: Every request made via
apiClientwill now automatically include the Authorization header, and any 401 response will trigger a redirect. - Risk: Forgetting to return
configin the request interceptor orPromise.reject(error)in the response interceptor will cause the request chain to hang indefinitely.
Trade-offs and Limitations
While powerful, interceptors introduce a layer of "magic" that can make debugging difficult. If a request is failing, the issue might not be in the API call itself, but in a hidden interceptor modifying the headers or swallowing the error.
Furthermore, interceptors are bound to the instance. If your application needs to communicate with three different APIs—each with different authentication schemes—you must maintain three separate Axios instances. Attempting to use a single global instance with conditional logic inside the interceptor often leads to complex, unmaintainable if/else blocks.
Verifying the Setup
To verify your interceptors are working without relying on a live backend, you can use a tool like Beeceptor or Postman Mock Servers. Set the mock server to return a 401 status and verify that your application triggers the redirect logic. Alternatively, log the config object inside the request interceptor to ensure the headers are being applied as expected before the request is sent.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.