Skip to content

Axios

Promise-based HTTP client with interceptors and automatic JSON handling.

Web & HTTPWebJavaScript

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 axios

Getting started

The smallest useful thing you can do with it, and what each part means.

GET request
import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
Performs a GET request to the given URL and logs the response data.
POST request with JSON payload
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));
Sends a POST request with a JSON payload and logs the returned data.

Advanced usage

Where the library earns its place over a simpler alternative.

Setting custom headers
axios.get('https://jsonplaceholder.typicode.com/posts', {
    headers: { 'Authorization': 'Bearer my-token' }
})
.then(response => console.log(response.data));
Adds custom headers to a request, useful for authentication or custom API requirements.
Using interceptors
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;
});
Intercepts requests and responses globally for logging, modifying headers, or handling errors.
Canceling requests
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', { cancelToken: source.token });
source.cancel('Request canceled by user.');
Demonstrates canceling a request using Axios CancelToken.
Concurrent requests
axios.all([
  axios.get('/users'),
  axios.get('/posts')
]).then(axios.spread((usersRes, postsRes) => {
  console.log(usersRes.data, postsRes.data);
}));
Performs multiple HTTP requests concurrently and handles the responses together.

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.

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.