Overview
Axios is an HTTP client library designed for both browser-based JavaScript applications and Node.js environments. It provides a promise-based API for making asynchronous HTTP requests, simplifying the process of sending data to and receiving data from web servers. The library supports various request methods, including GET, POST, PUT, DELETE, and PATCH, and handles different data formats, with automatic transformation for JSON data. This feature reduces the boilerplate code often associated with parsing responses, as Axios can automatically convert JSON strings into JavaScript objects upon receipt and vice-versa for outgoing requests.
A core strength of Axios lies in its interceptor system, which allows developers to modify requests or responses before they are handled by then or catch. This functionality is useful for tasks such as adding authentication tokens to outgoing requests, logging request details, or handling global error conditions from responses. For instance, an interceptor can automatically attach an authorization header to every outgoing request, centralizing authentication logic rather than repeating it across multiple API calls. Similarly, a response interceptor can check for specific HTTP status codes, such as 401 Unauthorized, and initiate a token refresh or redirect the user to a login page.
Axios is also equipped with client-side protection against Cross-Site Request Forgery (XSRF). When making requests from a browser, it can automatically detect and include XSRF tokens in the request headers, provided the server is configured to issue such tokens, a security measure detailed in the Axios request configuration guide. This helps mitigate a common web vulnerability by ensuring that requests originate from the intended source. The library's versatility extends to handling request cancellations, allowing developers to abort pending requests, which can be crucial for optimizing performance in single-page applications where users might rapidly navigate between views or submit multiple forms.
Developers often choose Axios for its consistent API across browser and Node.js environments, which streamlines development for full-stack JavaScript projects. Its feature set, including request/response transformation, interceptors, and error handling, makes it a suitable choice for applications ranging from simple data fetching scripts to complex enterprise systems requiring robust network communication. While the browser's native Fetch API provides similar functionality, Axios adds a layer of convenience and advanced features like interceptors and XSRF protection out of the box, which often require additional manual implementation with Fetch.
Key features
- Promise-based API: Utilizes promises for asynchronous operations, facilitating cleaner and more manageable code with
async/awaitsyntax. - Automatic JSON data transformation: Automatically converts request data to JSON and response data from JSON, reducing manual parsing and stringification.
- Request/response interceptors: Allows global modification of HTTP requests before they are sent and responses before they are passed to
thenorcatchhandlers. This enables centralized logic for authentication, logging, or error handling. - Client-side XSRF protection: Provides built-in support for mitigating Cross-Site Request Forgery attacks in browser environments by automatically including XSRF tokens.
- Cancellation of requests: Offers a mechanism to cancel ongoing HTTP requests, useful for preventing unnecessary network activity and handling rapidly changing user interactions.
- Streamlined error handling: Differentiates between various types of errors, including network errors, timeout errors, and HTTP status code errors, providing structured error objects for easier debugging.
- Browser and Node.js compatibility: Works consistently across both browser environments and Node.js, allowing for code reuse and simplifying isomorphic application development.
- HTTP and HTTPS support: Capable of making requests over both HTTP and encrypted HTTPS protocols, ensuring secure communication.
Pricing
Axios is an open-source project distributed under the MIT License. It is completely free to use for any purpose, including commercial applications, and does not offer paid tiers or commercial support plans. The project is maintained by its community of contributors.
| Service | Cost | Notes |
|---|---|---|
| Axios HTTP Client Library | Free | Fully open-source, no licensing fees or usage costs. |
Pricing as of 2026-06-22. Refer to the Axios homepage for current details.
Common integrations
Axios is a fundamental library that integrates with various parts of a JavaScript application stack. Due to its core function of making HTTP requests, it typically integrates with:
- Frontend frameworks (React, Vue, Angular): Used within components and services to fetch and send data to backend APIs. Developers using frameworks like React often use Axios within React Effect Hooks for data fetching.
- Node.js backend applications: Employed in server-side scripts to interact with external APIs, microservices, or databases.
- State management libraries (Redux, Zustand, Valtio): Integrates with state management patterns to update application state based on data retrieved via HTTP requests. For example, Axios requests might trigger Redux actions to update a global store. Valtio's
useProxyhook could similarly consume data fetched by Axios. - Testing frameworks (Jest, Mocha, Jasmine): Used for mocking HTTP requests in unit and integration tests to ensure reliable testing without external network calls. Jasmine's mocking capabilities can be combined with Axios to simulate API responses for testing.
Alternatives
- Fetch API: A native browser API for making network requests, which typically requires more boilerplate for JSON handling and error checking compared to Axios.
- superagent: A lightweight, progressive HTTP request library for Node.js and browsers, known for its chainable API.
- ky: A minimalistic HTTP client based on the Fetch API, focusing on developer experience and modern JavaScript features.
Getting started
To begin using Axios, first install it in your project using npm or yarn:
npm install axios
# or
yarn add axios
Once installed, you can import Axios and use it to make HTTP requests. The following example demonstrates a simple GET request to fetch data from a public API and a POST request to send data.
import axios from 'axios';
// --- Making a GET Request ---
async function fetchPosts() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log('Fetched Post:', response.data);
// Expected output for response.data:
// { userId: 1, id: 1, title: 'sunt aut facere ...', body: 'quia et suscipit ...' }
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request canceled:', error.message);
} else {
console.error('Error fetching post:', error.message);
}
}
}
// --- Making a POST Request ---
async function createPost() {
try {
const newPost = {
title: 'foo',
body: 'bar',
userId: 1,
};
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', newPost);
console.log('Created Post:', response.data);
// Expected output for response.data (may include an 'id' assigned by the server):
// { title: 'foo', body: 'bar', userId: 1, id: 101 }
} catch (error) {
console.error('Error creating post:', error.message);
}
}
fetchPosts();
createPost();
// --- Example with Request Interceptor ---
// Add a request interceptor to add an Authorization header to all requests
axios.interceptors.request.use(
config => {
const token = 'my_auth_token_123'; // Replace with actual token retrieval logic
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
console.log('Request Interceptor - Config:', config.url, config.headers.Authorization);
return config;
},
error => {
return Promise.reject(error);
}
);
// Example with Response Interceptor
axios.interceptors.response.use(
response => {
console.log('Response Interceptor - Status:', response.status, response.config.url);
return response;
},
error => {
if (error.response && error.response.status === 401) {
console.error('Unauthorized request. Redirecting to login...');
// Example: window.location.href = '/login';
}
return Promise.reject(error);
}
);
// Make another request to see interceptors in action
async function fetchWithInterceptor() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
console.log('Fetched User with Interceptors:', response.data.name);
} catch (error) {
console.error('Error fetching user with interceptors:', error.message);
}
}
fetchWithInterceptor();
This code snippet illustrates how to perform basic GET and POST operations. It also includes examples of setting up request and response interceptors, which log relevant information and demonstrate how to handle common scenarios like adding authentication headers and responding to unauthorized access. The axios.isCancel() utility is shown for handling request cancellation, a feature that can prevent race conditions in dynamic user interfaces.