What is Axios?
Axios is a popular HTTP client for the browser and Node.js, written in TypeScript. It provides a convenient and modern API for making asynchronous HTTP requests. The library automatically handles JSON data, supports interceptors, CSRF protection, and request cancellation.
Why is Axios needed?
Unlike the built-in fetch, Axios offers a more intuitive syntax, automatic data transformation, and built-in error handling. It is ideal for creating REST API clients, working with authentication, and file uploads. Thanks to TypeScript support, you get strict typing for all requests and responses.
Installation
To install Axios in your project, use npm or yarn:
npm install axios# oryarn add axiosFor working with TypeScript, install the types (usually they are already included):
npm install @types/axiosMain Features
- Support for all HTTP methods: GET, POST, PUT, DELETE, PATCH, and others.
- Automatic JSON serialization: data is transformed automatically.
- Interceptors: you can handle requests and responses globally (e.g., for adding tokens).
- Request cancellation: using
CancelTokenorAbortController. - File uploads: support for upload progress via
onUploadProgress. - CSRF protection: automatic handling of cookies and headers.
- Typing: full TypeScript support with generics.
TypeScript Code Example
Basic GET request with response typing:
import axios, { AxiosResponse } from 'axios';
interface User { id: number; name: string; email: string;}
async function getUser(id: number): Promise<User> { const response: AxiosResponse<User> = await axios.get(`/api/users/${id}`); return response.data;}
// UsagegetUser(1).then(user => console.log(user.name));Example of a POST request with data sending:
import axios from 'axios';
interface CreateUserPayload { name: string; email: string;}
const newUser: CreateUserPayload = { name: 'John', email: 'john@example.com' };
axios.post('/api/users', newUser) .then(response => console.log('User created:', response.data)) .catch(error => console.error('Error:', error));Example with an interceptor for adding a token:
import axios from 'axios';
axios.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config;});When to use Axios
Axios is ideal for:
- Building client applications with React, Vue, Angular, or Svelte.
- Node.js servers where a convenient HTTP client is required.
- Projects where strict TypeScript typing is important.
- Scenarios where interceptors, request cancellation, or upload progress are needed.
If you are using fetch and want more concise code with automatic error handling — Axios will be an excellent choice.