Tillitsdone
down Scroll to discover

Best Practices for Working with Axios in Node.js

Learn essential best practices for using Axios in Node.js applications, including error handling, request cancellation, rate limiting, and testing.

Improve your HTTP client implementation today.
thumbnail

A futuristic abstract network of glowing data streams forming an interconnected web colors: bright canary yellow streams against deep black background floating in space ultra-realistic cinematic lighting 8K UHD high resolution sharp and detail camera angle: wide shot from above looking down

As a Node.js developer, making HTTP requests is a fundamental part of building modern applications. Axios has emerged as the go-to HTTP client for its elegance and powerful features. Let’s dive into the best practices that will help you write more maintainable and robust code with Axios.

Setting Up Axios Instances

Instead of using Axios directly, create reusable instances with predefined configurations. This approach keeps your code DRY and makes it easier to maintain consistent headers, base URLs, and timeouts across your application.

const axios = require('axios');
const api = axios.create({
baseURL: process.env.API_BASE_URL,
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
});

Abstract flowing light rays intersecting and weaving through space colors: bright cobalt blue streams against pure white background ethereal glow effect high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail camera angle: extreme close-up shot

Error Handling and Interceptors

One of the most crucial aspects of working with HTTP requests is proper error handling. Axios interceptors provide a clean way to handle errors globally and transform responses consistently.

api.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// Handle authentication errors
return refreshTokenAndRetry(error);
}
return Promise.reject(error);
}
);

Request Cancellation

When building responsive applications, it’s essential to handle scenarios where requests need to be cancelled. Axios provides a built-in mechanism using cancel tokens.

const CancelToken = axios.CancelToken;
const source = CancelToken.source();
api.get('/long-running-query', {
cancelToken: source.token
}).catch(error => {
if (axios.isCancel(error)) {
console.log('Request cancelled:', error.message);
}
});
// Cancel the request
source.cancel('Operation cancelled by user');

Rate Limiting and Retries

Implement rate limiting and retry mechanisms to handle API restrictions and temporary failures gracefully. You can use libraries like axios-retry or implement your own solution.

Smooth brush stroke texture forming abstract waves colors: vibrant light red strokes blending into pristine white background organic flowing patterns high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail camera angle: macro shot of texture

Request and Response Transformation

Use transforms to standardize your request data and response handling. This ensures consistent data formatting across your application.

const api = axios.create({
transformRequest: [(data) => {
// Transform request data
return JSON.stringify(data);
}],
transformResponse: [(data) => {
// Transform response data
return JSON.parse(data);
}]
});

Testing and Mocking

When writing tests, use axios-mock-adapter to simulate API responses. This allows you to test your code without making actual HTTP requests.

const MockAdapter = require('axios-mock-adapter');
const mock = new MockAdapter(api);
mock.onGet('/users').reply(200, {
users: [{ id: 1, name: 'John' }]
});

Remember to always handle promises appropriately using async/await or proper promise chains, and implement proper logging for debugging and monitoring your applications in production.

Mechanical robotic components arranged in a geometric pattern colors: metallic canary yellow parts against off-black background with subtle light glints high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail camera angle: top-down isometric view

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.