How to Use Axios Interceptors in Node.js: Complete Implementation Guide
Axios interceptors are functions that execute before a request is sent or immediately after a response is received, enabling you to centralize cross-cutting concerns such as authentication, logging, and error handling in Node.js HTTP clients.
Axios interceptors provide a powerful mechanism for modifying HTTP requests and responses globally within your application. When running on the Node.js runtime—as provided by the nodejs/node repository—these interceptors work seamlessly with the platform's underlying http and https modules to process outgoing and incoming traffic. Understanding how to use axios interceptors effectively allows you to maintain clean separation between your networking logic and business concerns.
Understanding Axios Interceptor Types
Axios provides two distinct interceptor chains that operate at different stages of the HTTP lifecycle. Both interceptor types integrate naturally with JavaScript's promise-based async patterns and function identically whether your code executes in a browser or a Node.js environment.
Request Interceptors
Request interceptors run in the order they were registered immediately before Axios dispatches the HTTP call. Each interceptor receives the request config object, which contains the URL, headers, method, and other request parameters.
You can modify this configuration object—for example, by injecting authentication headers or generating trace IDs—but you must return the modified config object (or a promise that resolves to it) for the request to proceed. If a request interceptor throws an error or returns a rejected promise, Axios aborts the request and passes control to the error handling chain.
Response Interceptors
Response interceptors execute after the server responds but before the data reaches your application code. Unlike request interceptors, response interceptors run in the reverse order of their registration.
These interceptors receive the full response object, allowing you to transform payloads, unwrap data envelopes, or trigger side-effects such as caching. Like their request counterparts, response interceptors must return the response object or a promise, and they can reject to trigger error handling.
How to Configure Axios Interceptors in Node.js
To implement interceptors in a Node.js application, you first create a dedicated Axios instance using axios.create(). This approach allows you to share interceptor logic across multiple API calls while maintaining isolation from other HTTP clients in your codebase.
const axios = require('axios');
// Create a reusable Axios instance
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
});
// ----- Request interceptor -----
apiClient.interceptors.request.use(
(config) => {
// Attach a bearer token stored in an environment variable
const token = process.env.API_TOKEN;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// Add a custom header for distributed tracing
config.headers['X-Request-ID'] = generateUuid();
return config;
},
(error) => {
// Log request errors before transmission
console.error('Request interceptor error:', error);
return Promise.reject(error);
}
);
// ----- Response interceptor -----
apiClient.interceptors.response.use(
(response) => {
// Transform the payload by unwrapping data envelopes
if (response.data && response.data.payload) {
response.data = response.data.payload;
}
return response;
},
(error) => {
// Centralized error handling logic
if (error.response) {
console.warn('API error:', error.response.status, error.response.data);
} else if (error.request) {
console.error('No response received:', error.message);
} else {
console.error('Axios error:', error.message);
}
return Promise.reject(error);
}
);
module.exports = apiClient;
Practical Use Cases for Axios Interceptors
Once configured, the Axios instance handles cross-cutting concerns automatically, keeping your business logic focused on application-specific tasks rather than infrastructure details.
Authentication and Request Enhancement
Request interceptors excel at attaching credentials to outgoing calls. By accessing process.env variables within a Node.js environment, you can inject bearer tokens or API keys without cluttering every function that makes an HTTP call.
Response Transformation and Error Boundaries
Response interceptors allow you to normalize server responses before they reach your application code. You can flatten nested JSON structures, convert date strings to Date objects, or implement automatic retries for failed requests based on status codes.
Using the Configured Client
The following example demonstrates how to consume the pre-configured client that uses axios interceptors for automatic error logging and data transformation:
const apiClient = require('./apiClient');
async function fetchUser(userId) {
try {
const response = await apiClient.get(`/users/${userId}`);
// Response data is already unwrapped by the interceptor
return response.data;
} catch (err) {
// Errors are already logged; add business-specific handling here
throw err;
}
}
// Example invocation
fetchUser('12345')
.then((user) => console.log('User data:', user))
.catch((err) => console.error('Failed to fetch user:', err));
Managing Interceptor Lifecycle
Axios assigns unique IDs to interceptors when you register them, enabling dynamic removal when temporary modifications are needed. This functionality proves useful for scenarios requiring one-time headers or feature flags.
// Register a temporary header for a specific request flow
const requestInterceptorId = apiClient.interceptors.request.use((config) => {
config.headers['X-Temporary'] = 'temp-value';
return config;
});
// Execute the request and clean up afterward
apiClient.get('/temp-endpoint').finally(() => {
// Remove the interceptor to prevent affecting subsequent calls
apiClient.interceptors.request.eject(requestInterceptorId);
});
Node.js HTTP Implementation Details
While Axios itself is an external dependency not housed in the nodejs/node repository, it relies on Node.js's core networking modules to execute HTTP requests. The underlying transport behavior is documented in doc/api/http.md, and the platform's networking test coverage resides in test/parallel/test-http.js.
When you use axios interceptors, they operate as a middleware layer above Node.js's native http and https modules. The interceptor receives the configuration object before Node.js opens a socket connection, and processes the response after Node.js completes parsing the incoming HTTP stream but before Axios resolves the promise to your application code.
Summary
- Axios interceptors function as request and response middleware that centralize HTTP concerns in Node.js applications.
- Request interceptors execute in registration order and must return the modified
configobject for the request to proceed. - Response interceptors run in reverse registration order and receive the full response object for transformation.
- The Node.js
http/httpsmodules provide the underlying transport layer, as documented indoc/api/http.mdand tested intest/parallel/test-http.js. - Interceptors return numeric IDs that enable dynamic removal using
interceptors.request.eject()orinterceptors.response.eject().
Frequently Asked Questions
What happens if an Axios interceptor throws an error?
If a request interceptor throws an error or returns a rejected promise, Axios aborts the request immediately and triggers the error interceptors. For response interceptors, throwing or rejecting prevents the response from reaching your application code and instead routes to the error handling chain. This behavior allows you to implement centralized error logging and recovery logic.
In what order do multiple Axios interceptors execute?
Request interceptors execute in the order they were added to the instance, creating a processing pipeline from first to last. Response interceptors execute in the reverse order of registration, meaning the last registered response interceptor processes the server response first. This reverse ordering ensures that transformations applied closest to the network layer are unwound logically as the data travels back to your application.
How do you remove an Axios interceptor after adding it?
The .use() method returns a unique numeric ID immediately upon registration. Store this ID and pass it to apiClient.interceptors.request.eject(id) or apiClient.interceptors.response.eject(id) to remove the interceptor from the chain. This technique is essential for temporary modifications, such as adding one-time headers or toggling debug logging for specific request batches.
Do Axios interceptors work differently in Node.js compared to the browser?
No, the interceptor API remains identical between Node.js and browser environments because Axios abstracts the underlying HTTP implementation. However, in Node.js, Axios utilizes the http and https modules from the Node.js core library (documented in doc/api/http.md), whereas browsers use the XMLHttpRequest API. The interceptor logic—request modification, response transformation, and error handling—functions identically across both platforms.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s https://instagit.com/install.md