Using Abort Signals and Request Priority in Axios

Managing network efficiency requires precise control over HTTP requests. This guide explains how to implement modern request cancellation using the native AbortSignal API and how to configure request priority in Axios to optimize resource loading and prevent unnecessary network overhead.


Canceling Requests with AbortSignal

Modern versions of Axios (v0.22.0+) support the standard browser AbortController API, replacing the deprecated CancelToken.

To cancel a request, instantiate an AbortController, pass its signal property to the Axios request configuration, and call .abort() when necessary.

Basic Cancellation Example

import axios from 'axios';

const controller = new AbortController();

axios.get('https://api.example.com/data', {
  signal: controller.signal
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  if (axios.isCancel(error)) {
    console.log('Request canceled:', error.message);
  } else {
    console.error('API Error:', error);
  }
});

// Cancel the request
controller.abort();

Automatic Timeouts with AbortSignal.timeout

Modern JavaScript environments allow creating signals that abort automatically after a specified duration using AbortSignal.timeout():

axios.get('https://api.example.com/data', {
  signal: AbortSignal.timeout(5000) // Aborts automatically after 5 seconds
})
.catch(error => {
  if (error.name === 'CanceledError' || error.name === 'TimeoutError') {
    console.log('Request timed out and was aborted.');
  }
});

Configuring Request Priority

Modern browsers support request prioritization (high, low, auto) through the Fetch Priority API.

Axios can utilize the Fetch API under the hood by specifying the fetch adapter. When using this adapter, you can pass the priority option directly inside fetchOptions.

Setting Priority with the Fetch Adapter

import axios from 'axios';

// High-priority request (e.g., critical user action or above-the-fold content)
axios.get('https://api.example.com/critical-data', {
  adapter: 'fetch',
  fetchOptions: {
    priority: 'high'
  }
});

// Low-priority request (e.g., analytics, background prefetching)
axios.get('https://api.example.com/analytics', {
  adapter: 'fetch',
  fetchOptions: {
    priority: 'low'
  }
});

Combining Priority and Abort Signals

You can combine both features in a single request configuration to optimize performance and lifecycle management:

import axios from 'axios';

const controller = new AbortController();

axios.get('https://api.example.com/prefetch', {
  adapter: 'fetch',
  signal: controller.signal,
  fetchOptions: {
    priority: 'low'
  }
})
.then(response => {
  console.log('Prefetched data:', response.data);
})
.catch(error => {
  if (axios.isCancel(error)) {
    console.log('Prefetch aborted before completion.');
  }
});