How to Cancel Axios Requests Using AbortController

This article explains how to cancel ongoing HTTP requests in Axios using the native AbortController web API. Starting from Axios version 0.22.0, AbortController replaces the deprecated CancelToken API as the recommended method for aborting requests. You will learn how to attach an abort signal to a request, trigger the cancellation, and handle the resulting error cleanly in your code.

The Basic Implementation

To cancel a request, create an instance of AbortController, pass its signal property to the Axios request configuration object, and call the controller's .abort() method whenever you need to terminate the request.

import axios from 'axios';

// 1. Create a new AbortController instance
const controller = new AbortController();

// 2. Pass the signal to the Axios config
axios.get('https://api.example.com/data', {
  signal: controller.signal
})
.then(response => {
  console.log('Data received:', response.data);
})
.catch(error => {
  // 4. Handle the cancellation
  if (axios.isCancel(error)) {
    console.log('Request was canceled:', error.message);
  } else {
    console.error('An error occurred:', error);
  }
});

// 3. Cancel the request
controller.abort();

Handling Cancellation Errors

When a request is aborted, Axios throws an error. You can identify whether the failure was caused by an intentional cancellation using the axios.isCancel() helper or by inspecting the error name:

try {
  const response = await axios.get('/endpoint', { signal: controller.signal });
  return response.data;
} catch (error) {
  if (axios.isCancel(error)) {
    // Expected behavior: Request was deliberately aborted
    console.log('Operation aborted by the user.');
  } else {
    // Network errors, 4xx/5xx responses, etc.
    console.error('Network or server error:', error);
  }
}

Automatic Request Timeouts with AbortSignal

Modern JavaScript environments allow you to set an automatic timeout using AbortSignal.timeout(), which automatically triggers cancellation after a specified number of milliseconds:

axios.get('https://api.example.com/data', {
  signal: AbortSignal.timeout(5000) // Automatically aborts after 5 seconds
})
.then(response => console.log(response.data))
.catch(error => {
  if (axios.isCancel(error)) {
    console.log('Request timed out and was aborted.');
  }
});

Canceling Requests in React useEffect

A common use case is canceling ongoing requests when a component unmounts to prevent memory leaks and state updates on unmounted components:

import { useEffect, useState } from 'react';
import axios from 'axios';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    axios.get(`/api/users/${userId}`, { signal: controller.signal })
      .then(res => setUser(res.data))
      .catch(err => {
        if (!axios.isCancel(err)) {
          console.error(err);
        }
      });

    // Cleanup: Abort request on unmount or userId change
    return () => {
      controller.abort();
    };
  }, [userId]);

  return <div>{user ? user.name : 'Loading...'}</div>;
}