DEV Community

Cover image for Effective Request Cancellation with Axios in JavaScript
PEAKIQ
PEAKIQ

Posted on • Originally published at peakiq.in

Effective Request Cancellation with Axios in JavaScript

Originally published on PEAKIQ

Source: https://www.peakiq.in/blog/effective-request-cancellation-with-axios-in-javascript


How CancelTokens Work

A CancelToken is a token you attach to an Axios request. When you want to cancel that request, you call the cancel() function on the token source. Axios intercepts the cancellation, aborts the request, and throws a specific cancellation error that you can catch and handle separately from other errors.

The four things to understand:

  • Creating a tokenaxios.CancelToken.source() returns a { token, cancel } pair. Pass token to the request and call cancel() when you want to abort.
  • Canceling a request — Calling cancel(message) immediately interrupts any in-flight request using that token.
  • Handling cancellation errors — Axios throws a CanceledError on cancellation. Use axios.isCancel(error) to distinguish it from real network or server errors.
  • Resetting the token — After canceling, create a new CancelToken.source() before making the next request. A canceled token cannot be reused.

Implementation

Cancel token module

Create a shared module that holds the current token source and exposes a reset function. This lets any part of your application cancel the active request and prepare a fresh token in one call.

// cancel.js

/* eslint-disable import/no-mutable-exports */
import axios from 'axios';

export let axiosCancelSource = axios.CancelToken.source();

export const resetCancelSource = (cancelMessage = 'Request is Cancelled') => {
  axiosCancelSource.cancel(cancelMessage);
  axiosCancelSource = axios.CancelToken.source();
};
Enter fullscreen mode Exit fullscreen mode

axiosCancelSource is exported as a mutable let so the reference can be updated when resetCancelSource creates a new source. The eslint-disable comment suppresses the mutable export warning — this pattern is intentional here.

Using the token in a request

Import the shared token and attach it to your Axios config. In the finally block, reset the source so the next call gets a clean token.

// DownloadClass.js

import axios from 'axios';
import { axiosCancelSource, resetCancelSource } from '../components/shared/cancelToken';

export class DownloadAssessment {
  static async downloadFromServer(paramData) {
    const { axiosReqPayload } = paramData;

    try {
      const response = await axios({
        ...axiosReqPayload,
        cancelToken: axiosCancelSource.token,
      });
      return response.data;
    } catch (error) {
      if (axios.isCancel(error)) {
        console.log('Request canceled:', error.message);
        // Handle cancellation — update UI state, log, or silently ignore
      } else {
        throw error; // Re-throw real errors so callers can handle them
      }
    } finally {
      // Reset after every request — success, error, or cancellation
      resetCancelSource();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The finally block ensures resetCancelSource runs regardless of outcome. Without this, a failed or canceled request would leave the token in a canceled state, causing all subsequent requests to fail immediately.


Triggering Cancellation

Call resetCancelSource() from anywhere in your application when you need to abort the current request:

import { resetCancelSource } from '../components/shared/cancelToken';

// On component unmount, route change, or user action
resetCancelSource('User navigated away');
Enter fullscreen mode Exit fullscreen mode

This cancels the active request and immediately prepares a fresh token for the next one.


Best Practices

  • Call resetCancelSource in component cleanup functions (useEffect return, componentWillUnmount) to prevent state updates on unmounted components.
  • Always use axios.isCancel(error) before deciding how to handle a caught error — swallowing a real network error as if it were a cancellation is a common bug.
  • Never reuse a canceled token. Always call axios.CancelToken.source() to create a new one before the next request.
  • If you are using Axios 0.22+, consider migrating to the AbortController API, which is the web standard equivalent and is now supported natively by Axios.

Summary

Concept How it works
Create token axios.CancelToken.source() returns { token, cancel }
Attach to request Pass token as cancelToken in the Axios config
Cancel Call cancel(message) on the source
Detect cancellation axios.isCancel(error) returns true for canceled requests
Reset Call axios.CancelToken.source() again before the next request

Request cancellation is a small addition to your Axios setup that pays dividends in application reliability — fewer race conditions, cleaner unmount behavior, and a better experience when users change their mind mid-request.

Top comments (0)