Promise based HTTP client for the browser and node.js
Axios is a promise-based HTTP client that works in both Node.js and browser environments, providing a unified interface for making HTTP requests. With over 82 million weekly downloads, it has become the de facto standard for JavaScript developers who need a robust, feature-rich alternative to native HTTP APIs. The library wraps Node.js's native http module on the server and XMLHttpRequest in browsers, offering a consistent API across environments.
The package was created to address the verbosity and complexity of native HTTP request mechanisms. While the Fetch API has become standard in modern browsers, Axios still offers significant advantages: automatic JSON transformation, request/response interceptors, built-in timeout and cancellation support, and better error handling out of the box. These features eliminate common boilerplate code and reduce the risk of subtle bugs in HTTP communication.
Axios is widely used in production applications ranging from small startups to enterprise systems. Its adoption is particularly strong in React, Vue, and Node.js ecosystems where developers need reliable API communication. The library's stability, comprehensive documentation, and active maintenance make it a safe choice for projects of any scale. Its interceptor system enables sophisticated patterns like automatic token refresh, request queuing, and centralized error handling that would require significant custom code with native alternatives.
import axios from 'axios';
// Create a configured instance for your API
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: { 'X-Custom-Header': 'value' }
});
// Add request interceptor for authentication
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// Add response interceptor for error handling
api.interceptors.response.use(
response => response.data,
error => {
if (error.response?.status === 401) {
window.location.href = '/login';
}
return Promise.reject(error);
}
);
// Usage with async/await
async function fetchUserData(userId) {
try {
const user = await api.get(`/users/${userId}`);
console.log('User:', user);
return user;
} catch (error) {
if (error.code === 'ECONNABORTED') {
console.error('Request timeout');
} else if (error.response) {
console.error('Server error:', error.response.status);
} else if (error.request) {
console.error('Network error');
}
throw error;
}
}
// POST request with cancellation
const controller = new AbortController();
api.post('/users', {
name: 'John Doe',
email: 'john@example.com'
}, {
signal: controller.signal
}).then(response => {
console.log('Created:', response);
}).catch(error => {
if (axios.isCancel(error)) {
console.log('Request cancelled');
}
});
// Cancel the request
setTimeout(() => controller.abort(), 1000);REST API Integration: Making GET, POST, PUT, DELETE requests to RESTful backends with automatic JSON serialization/deserialization, eliminating manual JSON.stringify() and response.json() calls.
Authentication Flow Management: Using request interceptors to automatically attach JWT tokens to outgoing requests and response interceptors to handle token refresh logic when receiving 401 errors, centralizing auth logic in one place.
File Upload with Progress Tracking: Uploading files using multipart/form-data with built-in progress event handlers to display upload progress bars, which requires less setup than with Fetch API.
Request Cancellation: Implementing search-as-you-type functionality where previous requests need to be cancelled when new input arrives, preventing race conditions using AbortController integration or Axios's CancelToken.
Microservices Communication: Creating multiple Axios instances with different base URLs, timeout configurations, and headers for communicating with various microservices in a Node.js backend, keeping service-specific configurations isolated and reusable.
npm install axiospnpm add axiosbun add axios