Axios Request Cancellation: Migration Timing from CancelToken to AbortSignal in v0.22.0+
0 reputation · 19 Dec 2025, 09:16 UTC
0 reputation · 19 Dec 2025, 09:16 UTC
Axios v0.22.0 introduced signal as the documented cancellation mechanism while retaining the legacy CancelToken API in 1.x releases. Teams maintaining codebases with search-as-you-type or polling logic face a decision: migrate now or continue using CancelToken since both are currently supported.
The constraint is that error shapes differ: 1.x rejects with CanceledError (code: 'ERR_CANCELED') while 0.x rejects with a Cancel instance. Meanwhile axios.isCancel() works across both. Additionally, timeout and AbortSignal.timeout() provide overlapping deadline control but produce different rejection types.
35275 reputation · 19 Dec 2025, 12:48 UTC
For a codebase pinned to Axios 0.x planning an upgrade to 1.x, the migration from CancelToken to AbortSignal should be timed with the major version upgrade itself. Because CancelToken remains available (though deprecated) in 1.x, there is no immediate breaking change forcing a migration. However, migrating during the 1.x transition prevents the accumulation of technical debt and allows you to leverage native browser/Node.js AbortController features.
Prioritize the migration to AbortSignal if any of the following apply:
AbortSignal.timeout() for standardized deadline control across different request types.AbortController, removing the need for Axios-specific cancellation logic.To identify cancellations reliably across both 0.x and 1.x without checking for version-specific error codes (like ERR_CANCELED) or specific class instances (like CanceledError), use the built-in axios.isCancel() helper.
This method is designed to abstract the underlying error shape, returning true regardless of whether the request was canceled via a legacy CancelToken or a modern AbortSignal.
try {
const response = await axios.get('/api/data', { signal: controller.signal });
} catch (err) {
if (axios.isCancel(err)) {
// Handle cancellation (e.g., ignore in search-as-you-type)
console.log('Request canceled');
} else {
// Handle actual API or network errors
handleError(err);
}
}
It is critical to separate axios.isCancel() from timeout logic. While AbortSignal.timeout() triggers a cancellation, standard Axios timeout configurations produce different rejection shapes (typically ECONNABORTED). Treat isCancel() as a signal to ignore the request, while treating timeouts as a failure state that may require a retry or a user notification.
Verification Step: To confirm behavior before upgrading, run a test case that triggers a cancellation in your current 0.x environment and verify that axios.isCancel(err) returns true. Ensure your runtime supports AbortController or include a polyfill before switching to signal.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.