Axios is an open-source HTTP client for JavaScript and TypeScript, working both in the browser and in the Node.js environment. The library provides a convenient Promise-based interface for sending HTTP requests with support for interceptors, automatic JSON serialization, and request cancellation. According to the official repository on GitHub, the project has over 100,000 stars. Axios is one of the most popular libraries for working with REST API in the JavaScript ecosystem.
Key Takeaways
Axios is a JavaScript library for making HTTP requests from the browser and Node.js environment. It is built on top of XMLHttpRequest in the browser and the http module in Node.js, providing a unified API for both platforms.
The main advantage of Axios over native fetch is automatic JSON handling, interceptor support, and more convenient error handling. Unlike fetch, Axios does not require two .then calls to get the JSON response body and automatically throws exceptions on HTTP errors (4xx, 5xx).
The library supports all major HTTP methods: GET, POST, PUT, DELETE, PATCH, and HEAD. It can be used both in simple projects and in large enterprise applications with hundreds of thousands of requests daily.
Axios architecture is based on the concept of adapters. The library abstracts the transport layer: it uses XMLHttpRequest in the browser and the http or https module in Node.js. This provides a single interface regardless of the runtime environment.
Each request goes through a chain of interceptors that can modify the request configuration or response. After the interceptors, the request is passed to the adapter, which performs the actual HTTP call. The response then passes through response interceptors before reaching the application code.
Axios includes many built-in features that make it a convenient choice for working with HTTP in mobile and web applications. Let’s explore the key ones.
When sending a request, Axios automatically transforms a JavaScript object into a JSON string using JSON.stringify. When receiving a response, the library parses JSON back into an object. This saves the developer from manual serialization and deserialization of data.
In the browser environment, Axios automatically adds XSRF-TOKEN headers from cookies, protecting the application from cross-site request forgery. To do this, simply configure the server to send the token in a cookie named XSRF-TOKEN.
The library supports setting a timeout via the timeout parameter and request cancellation via AbortController. This is especially important in mobile applications with unstable connections, where stuck requests consume battery and data.
Installing Axios is done through any package manager. The library is available in the npm registry and can be used both in Node.js and browser projects. For TypeScript, types are included in the main package — no additional dependencies are required.
After installation, you can create an instance with a basic configuration: base URL, default timeout, common headers. This allows you to avoid repeating the same parameters in every request and centrally manage HTTP client settings.
# Install via npm
npm install axios
# Install via yarn
yarn add axios
# Install via pnpm
pnpm add axios
It is recommended to create a separate Axios instance for each API service. This allows you to set a base URL, standard headers, and timeout that will apply to all requests of this instance without repeating them in each call.
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
Request examples demonstrate the main usage patterns of Axios. All examples use async/await syntax, which makes asynchronous code more readable compared to .then() chains.
To retrieve data from the server, the axios.get method is used. Query parameters are passed via the params object, which is automatically transformed into a query string. The response contains data in the data field, status in status, and headers in headers.
interface User {
id: number;
name: string;
email: string;
}
async function getUsers() {
try {
const response = await api.get<User[]>('/users', {
params: { page: 1, limit: 10 }
});
return response.data;
} catch (error) {
console.error('Error loading users', error);
throw error;
}
}
To send data to the server, axios.post is used. The second argument is an object with data, which Axios automatically serializes to JSON. The Content-Type is set to application/json by default.
interface CreateUserDto {
name: string;
email: string;
role: string;
}
async function createUser(data: CreateUserDto) {
const response = await api.post<User>('/users', data);
return response.data;
}
Interceptors are middleware functions that execute for each request or response. They allow adding authorization tokens, logging requests, and handling errors centrally. A request interceptor adds an Authorization header with a token retrieved from storage.
// Request interceptor — adds authorization token
api.interceptors.request.use(
(config) => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor — handles 401 errors
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
redirectToLogin();
}
return Promise.reject(error);
}
);
Error handling in Axios is built on the exception mechanism. Unlike fetch, Axios automatically catches HTTP errors (4xx, 5xx) and passes them to the catch block. The error object contains information about the server response, request, and execution context.
It is important to distinguish three types of errors: server response error (response), request error (request), and configuration error (config). The first occurs when an HTTP call is successfully executed but returns an error code, the second occurs when there is no response from the server, and the third occurs when the request configuration is invalid.
import axios, { AxiosError } from 'axios';
async function safeRequest() {
try {
return await api.get('/data');
} catch (error) {
if (error instanceof AxiosError) {
if (error.response) {
console.warn('Response error', error.response.status);
} else if (error.request) {
console.warn('No response from server');
} else {
console.warn('Configuration error');
}
}
}
}
| HTTP Method | Axios Method | Description |
|---|---|---|
| GET | axios.get(url, config) | Retrieve data |
| POST | axios.post(url, data, config) | Create resource |
| PUT | axios.put(url, data, config) | Update resource |
| DELETE | axios.delete(url, config) | Delete resource |
| PATCH | axios.patch(url, data, config) | Partial update |
Comparing Axios with the native Fetch API helps determine when each technology is appropriate. Fetch is a built-in browser API that requires no installation. Axios is a third-party library with additional features. For simple requests, fetch is sufficient; for complex applications with interceptors and centralized error handling, Axios is more convenient.
Fetch does not treat HTTP errors (4xx, 5xx) as exceptions — you need to check response.ok. Fetch requires two .then() calls to get JSON: response.json() then returns a Promise with data. Axios does this automatically. Fetch does not support file upload progress without additional polyfills. Axios has built-in onUploadProgress and onDownloadProgress.
In Node.js, Fetch has been available since version 18 as an experimental feature, while Axios has been stable since Node.js 10. For projects supporting older Node.js versions, the choice is clearly in favor of Axios. For modern browser projects without complex request handling, fetch may be sufficient.
Frequently Asked Questions
Axios automatically parses JSON, throws exceptions on HTTP errors, and supports interceptors. Fetch requires two .then calls for JSON and does not treat 4xx/5xx as errors. Axios is also easier to configure through a settings object.
No, TypeScript types are included in the main axios package. No additional dependencies like @types/axios are required — just import axios from the package with the same name.
Use AbortController: create an AbortController instance and pass its signal to the request configuration. When controller.abort() is called, the request will be canceled and the Promise will be rejected with an appropriate error message.
Yes, Axios is fully compatible with React Native. The library uses the built-in XMLHttpRequest, which is available in the React Native environment. All features, including interceptors and request cancellation, work without additional configuration.
Use a request interceptor to centrally add the Authorization header. This eliminates the need to specify the token in each request individually and allows for uniform token expiration handling.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also