Axios: What It Is, HTTP Requests, and Basics of Working with API

Author: IT Sectr Published: 2026-03-07 Reading time: 8 min

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 — HTTP client based on Promise API for browser and Node.js with TypeScript support
  • Interceptors — allow modifying requests and responses before they are processed in code
  • Automatic transformation — the library automatically parses JSON in responses and serializes data in requests
  • Request cancellation — built-in AbortController mechanism for canceling stuck or unnecessary requests
  • File upload — upload progress support via onUploadProgress and onDownloadProgress

What is Axios?

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.

Key Characteristics of Axios

  • Promise API — all operations return a Promise, simplifying asynchronous code
  • TypeScript support — full typing for all methods and configurations
  • Interceptors — middleware for processing requests and responses
  • Transformation — automatic data transformation on input and output

Axios Architecture and How It Works

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 Request Lifecycle

  1. Configuration creation — method, URL, headers, request body
  2. Request interceptor — configuration modification, adding tokens
  3. HTTP call — execution through the browser or Node.js adapter
  4. Response interceptor — response transformation, error handling
  5. Return result — Promise resolves with data or rejects

Key Features of Axios

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.

Automatic Data Transformation

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.

CSRF Protection

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.

Timeouts and Request Cancellation

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 and Configuring Axios

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.

bash
# Install via npm
npm install axios

# Install via yarn
yarn add axios

# Install via pnpm
pnpm add axios

Creating an Instance with Configuration

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.

typescript
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

Axios Code Examples

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.

GET Request with Parameters

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.

typescript
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;
  }
}

POST Request with Body

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.

typescript
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

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.

typescript
// 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

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.

typescript
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 Fetch API

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

How is Axios different from fetch?

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.

Do I need to install Axios for TypeScript separately?

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.

How to cancel a request in Axios?

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.

Does Axios work with React Native?

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.

How to add authorization headers to all requests?

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

  • Axios is an HTTP client for JavaScript and TypeScript with Promise API and browser and Node.js support
  • Interceptors allow centrally modifying requests, handling errors, and adding authorization
  • Automatic JSON transformation simplifies working with REST API without manual serialization
  • Request cancellation via AbortController prevents memory leaks in mobile and web applications
  • Instance configuration allows setting base parameters for all API requests
  • TypeScript support is built into the package — no additional types required
  • Axios remains the de facto standard for HTTP clients in the JavaScript ecosystem

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.

Discuss the project

Read also