Complete Axios Guide | HTTP Client, Interceptor, Error Handling & Practical Usage

Complete Axios Guide | HTTP Client, Interceptor, Error Handling & Practical Usage

Key Takeaways

Complete guide to implementing efficient HTTP communication with Axios. Covers Instance, Interceptor, error handling, Timeout, and Retry with practical examples.

Real-World Experience: Sharing experience of transitioning from fetch API to Axios, which simplified error handling and greatly improved code reusability.

Introduction: “fetch API is Inconvenient”

Real-World Problem Scenarios

Scenario 1: Complex Error Handling
fetch requires manual handling. Axios handles it automatically.

Scenario 2: Need Interceptor
fetch doesn’t support it. Axios provides powerful Interceptor.

Scenario 3: Need Request Cancellation
fetch is complex. Axios is simple.


1. What is Axios?

Core Features

Axios is a Promise-based HTTP client.

Key Advantages:

  • Simple API: Intuitive syntax
  • Interceptor: Intercept requests/responses
  • Auto Transform: Automatic JSON handling
  • Error Handling: Unified error handling
  • Browser/Node.js: Supports both

2. Installation and Basic Usage

Installation

npm install axios

GET Request

Here’s an implementation example using TypeScript. Import necessary modules, perform tasks efficiently with async processing. Please review the code to understand the role of each part.

import axios from 'axios';

const response = await axios.get('https://api.example.com/users');
console.log(response.data);

// With parameters
const response = await axios.get('https://api.example.com/users', {
  params: {
    page: 1,
    limit: 10,
  },
});

POST Request

Here’s an implementation example using TypeScript. Perform tasks efficiently with async processing. Try running the code directly to see how it works.

const response = await axios.post('https://api.example.com/users', {
  email: '[email protected]',
  name: 'John',
});

console.log(response.data);

3. Instance

Here’s an implementation example using TypeScript. Import necessary modules, perform tasks efficiently with async processing. Please review the code to understand the role of each part.

// lib/api.ts
import axios from 'axios';

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

// Usage
const response = await api.get('/users');
const user = await api.post('/users', { name: 'John' });

4. Interceptor

Request Interceptor

Here’s a detailed implementation using TypeScript. Perform tasks efficiently with async processing, ensure stability with error handling, handle branching with conditionals. Please review the code to understand the role of each part.

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    console.log('Request:', config.method, config.url);

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

Response Interceptor

Here’s a detailed implementation using TypeScript. Perform tasks efficiently with async processing, ensure stability with error handling, handle branching with conditionals. Please review the code to understand the role of each part.

api.interceptors.response.use(
  (response) => {
    console.log('Response:', response.status);
    return response;
  },
  async (error) => {
    if (error.response?.status === 401) {
      // Refresh token
      const newToken = await refreshToken();
      localStorage.setItem('token', newToken);

      // Retry
      error.config.headers.Authorization = `Bearer ${newToken}`;
      return api.request(error.config);
    }

    return Promise.reject(error);
  }
);

5. Error Handling

Here’s a detailed implementation using TypeScript. Perform tasks efficiently with async processing, ensure stability with error handling, handle branching with conditionals. Please review the code to understand the role of each part.

try {
  const response = await api.get('/users');
  console.log(response.data);
} catch (error) {
  if (axios.isAxiosError(error)) {
    if (error.response) {
      console.error('Response error:', error.response.status);
      console.error('Data:', error.response.data);
    } else if (error.request) {
      console.error('No response received');
    } else {
      console.error('Request setup error:', error.message);
    }
  }
}

6. Cancellation

AbortController

Here’s an implementation example using TypeScript. Perform tasks efficiently with async processing. Try running the code directly to see how it works.

const controller = new AbortController();

const response = await api.get('/users', {
  signal: controller.signal,
});

// Cancel
controller.abort();

CancelToken (Legacy)

Here’s an implementation example using TypeScript. Try running the code directly to see how it works.

const source = axios.CancelToken.source();

api.get('/users', {
  cancelToken: source.token,
});

// Cancel
source.cancel('Request cancelled');

7. Parallel Requests

Here’s an implementation example using TypeScript. Perform tasks efficiently with async processing. Try running the code directly to see how it works.

const [users, posts, comments] = await Promise.all([
  api.get('/users'),
  api.get('/posts'),
  api.get('/comments'),
]);

console.log(users.data, posts.data, comments.data);

8. Real-World Example

API Client

Here’s a detailed implementation using TypeScript. Import necessary modules, perform tasks efficiently with async processing, ensure stability with error handling, handle branching with conditionals. Please review the code to understand the role of each part.

// lib/apiClient.ts
import axios from 'axios';

const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL,
  timeout: 10000,
});

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export const userApi = {
  getAll: () => api.get('/users'),
  getOne: (id: string) => api.get(`/users/${id}`),
  create: (data: any) => api.post('/users', data),
  update: (id: string, data: any) => api.patch(`/users/${id}`, data),
  delete: (id: string) => api.delete(`/users/${id}`),
};

Summary and Checklist

Key Summary

  • Axios: HTTP client
  • Instance: Reusable configuration
  • Interceptor: Intercept requests/responses
  • Error Handling: Unified handling
  • Cancellation: AbortController
  • Parallel Requests: Promise.all

Implementation Checklist

  • Install Axios
  • Create Instance
  • Implement Interceptor
  • Implement error handling
  • Add cancellation feature
  • Write API client
  • Test

  • Complete TanStack Query Guide
  • Complete tRPC Guide
  • Fetch API Guide

Keywords Covered

Axios, HTTP, API, JavaScript, TypeScript, Frontend, Backend

Frequently Asked Questions (FAQ)

Q. How does it compare to fetch API?

A. Axios provides more features and is more convenient to use. fetch is standard and lightweight.

Q. Can it be used in both browser and Node.js?

A. Yes, it supports both.

Q. Does it support TypeScript?

A. Yes, type definitions are included.

Q. Is it safe to use in production?

A. Yes, it’s being used stably in countless projects.

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3