Tillitsdone
down Scroll to discover

Using Axios Interceptors in Node.js Apps

Learn how to leverage Axios interceptors in Node.js for seamless request and response manipulation.

Discover practical examples of authentication, error handling, and data transformation.
thumbnail

A modern sleek tech-inspired geometric pattern with interlocking hexagons and flowing lines rendered in bright lime green and white colors against a dark background. Shot from top-down perspective ultra-realistic cinematic 8K UHD high resolution sharp and detailed

Using Axios Interceptors for Request and Response Manipulation in Node.js

Ever wondered how to globally handle API requests and responses in your Node.js application? Let me introduce you to one of the most powerful features of Axios - Interceptors. They’re like magical gatekeepers that can inspect, modify, or even reject requests and responses before they reach their destination.

What Are Axios Interceptors?

Think of interceptors as middleware for your HTTP requests. They sit between your application and the server, allowing you to perform actions before a request is sent or after a response is received. It’s like having a security checkpoint that can check, stamp, or modify your “HTTP passport” before letting it through.

Elegant architectural maze structure with interconnected pathways featuring bright blue glass and white concrete elements. Captured from a diagonal aerial view sunlight creating dynamic shadows high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Setting Up Request Interceptors

Let’s dive into how we can set up request interceptors. Here’s a practical example:

// Create an Axios instance
const axios = require('axios');
const api = axios.create({
baseURL: 'https://api.example.com'
});
// Add a request interceptor
api.interceptors.request.use(
(config) => {
// Add authentication header
config.headers.Authorization = `Bearer ${getToken()}`;
// Add timestamp to requests
config.headers['Request-Time'] = new Date().toISOString();
return config;
},
(error) => {
return Promise.reject(error);
}
);

This interceptor automatically adds an authentication token and timestamp to every request. Pretty neat, right?

Response Interceptors in Action

Response interceptors are equally powerful. They can transform data, handle errors globally, or even retry failed requests:

api.interceptors.response.use(
(response) => {
// Transform response data
if (response.data.items) {
response.data.items = response.data.items.map(item => ({
...item,
processed: true
}));
}
return response;
},
async (error) => {
if (error.response.status === 401) {
// Refresh token and retry request
await refreshToken();
return api(error.config);
}
return Promise.reject(error);
}
);

Abstract flowing network of interconnected nodes and paths rendered in bright emerald green and orange colors against white background. Photographed from a low angle perspective highlighting depth and dimension high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Real-World Use Cases

Interceptors shine in many scenarios:

  • Automatically handling authentication
  • Logging requests and responses
  • Adding correlation IDs for request tracking
  • Transforming request/response data formats
  • Implementing retry mechanisms
  • Showing/hiding global loading indicators

Best Practices

Remember these golden rules when working with interceptors:

  1. Keep them focused and lightweight
  2. Handle errors properly
  3. Maintain clear separation of concerns
  4. Document any transformations
  5. Be mindful of the order of multiple interceptors

Error Handling Tips

Always implement proper error handling in your interceptors. Here’s a robust approach:

api.interceptors.response.use(
response => response,
error => {
if (!error.response) {
// Network or connection error
console.error('Network Error:', error.message);
return Promise.reject(new Error('Network error occurred'));
}
switch (error.response.status) {
case 401:
// Handle unauthorized
return handleUnauthorized(error);
case 404:
// Handle not found
return Promise.reject(new Error('Resource not found'));
default:
// Handle other errors
return Promise.reject(error);
}
}
);

Serene Japanese zen garden with geometric patterns in white sand featuring clean lines and minimalist design elements in bright gem blue stones. Captured from a 45-degree elevated angle morning light casting subtle shadows high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.