Axios
Promise-based HTTP client with interceptors and automatic JSON handling.
What it is
Axios is a promise-based HTTP client for JavaScript that works in both the browser and Node.js. It simplifies making HTTP requests, handling responses, and managing errors.
Axios allows you to perform HTTP requests using methods such as GET, POST, PUT, DELETE, and more. It returns promises that resolve with response objects containing data, status, headers, and config. Axios also supports request cancellation, interceptors, and timeout configuration.
- Licence
- MIT
- Watch for
- Axios throws on non-2xx responses; fetch does not — a common migration bug
When to use it
The question documentation cannot answer for you — because it cannot recommend something else.
Reach for it when
- You want request and response interceptors — attaching auth tokens, handling 401s centrally
- You need upload progress or request cancellation with a consistent API across browser and Node
Look elsewhere when
- `fetch` is built in and enough — for simple calls it adds a dependency for little gain
- Bundle size is tight
Installation
npm install axiosGetting started
The smallest useful thing you can do with it, and what each part means.
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => console.log(response.data))
.catch(error => console.error(error));import axios from 'axios';
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));Advanced usage
Where the library earns its place over a simpler alternative.
axios.get('https://jsonplaceholder.typicode.com/posts', {
headers: { 'Authorization': 'Bearer my-token' }
})
.then(response => console.log(response.data));axios.interceptors.request.use(config => {
console.log('Request made with config:', config);
return config;
});
axios.interceptors.response.use(response => {
console.log('Response received:', response);
return response;
});const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token });
source.cancel('Request canceled by user.');axios.all([
axios.get('/users'),
axios.get('/posts')
]).then(axios.spread((usersRes, postsRes) => {
console.log(usersRes.data, postsRes.data);
}));Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Network Error
- Check your internet connection or the API endpoint availability.
- Timeout Error
- Set a reasonable timeout using `axios({ timeout: 5000 })` and handle cases where the request takes too long.
- HTTP error (4xx, 5xx)
- Use `error.response` to inspect status codes and messages, and handle specific status codes appropriately.
Best practices
- Use interceptors for handling authentication, logging, or error processing.
- Always catch errors and handle them gracefully.
- Use environment variables for base URLs and API tokens.
- Leverage request cancellation to avoid race conditions or unnecessary network calls.
- Use async/await syntax for cleaner asynchronous code.
Alternatives
Comparable options, and the reason you would pick one over the other.
fetch
Built into every browser and Node 18+; no dependency, slightly more boilerplate
React Query
Solves the caching layer above whichever client you use
Background
Why it exists, and what it was reacting to.
Axios was created to provide a simpler and more consistent API for making HTTP requests in JavaScript compared to the built-in `fetch` API. It supports request and response interception, automatic JSON transformation, and is widely adopted in both front-end and back-end JavaScript projects.
