Cancellation with AbortController
Cancelling work in Node with AbortSignal, including timeouts, combining signals, and passing a signal to fetch, fs, timers, streams and your own code.
Cancellation with AbortController
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An `AbortController` has a `signal` you pass to work and an `abort()` method you call to cancel it. Anything that accepts the signal stops when it aborts.
- In Node, `{ signal }` is accepted by `fetch`, `fs/promises` reads and writes, `timers/promises`, `stream.pipeline`, `events.once`, `child_process`, and `EventTarget` listeners.
- `AbortSignal.timeout(ms)` makes a signal that aborts itself with a `TimeoutError`. `AbortSignal.any([a, b])` aborts when the first one does.
- An aborted promise rejects with an error. The signal's `reason` is a `DOMException` named `AbortError` by default, or whatever value you passed to `abort(reason)`.
- Cancellation is cooperative: aborting a signal does nothing unless the code receiving it checks `signal.aborted` or listens for `abort`.
The problem: work you cannot stop
A user navigates away. A client disconnects. A request outlives its 5 second budget. In each case the result is no longer wanted, yet the database query, upstream HTTP call, or file read carries on and consumes resources. Promises cannot be cancelled by themselves, so Node and the web needed a standard way to say “stop” that works across APIs.
The API
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', () => console.log('aborted:', signal.reason.name));
controller.abort(); // reason is a DOMException named AbortError
console.log(signal.aborted); // true
You hand the signal to the work and keep the controller to cancel it, a split that stops the worker from cancelling itself or others. abort(reason) accepts any value as the reason.
What accepts a signal in Node
Most promise-returning core APIs take { signal }, and they reject when it aborts:
import { setTimeout as sleep } from 'node:timers/promises';
import { readFile } from 'node:fs/promises';
const ac = new AbortController();
const p = sleep(1000, null, { signal: ac.signal }).catch((e) => console.log(e.name, e.code));
ac.abort();
await p; // AbortError ABORT_ERR
await readFile('d.txt', { signal: AbortSignal.abort() }).catch((e) => console.log(e.code)); // ABORT_ERR
The same option works for fetch, stream.pipeline(..., { signal }) (it destroys every stage), events.once, child_process.spawn, and addEventListener('x', fn, { signal }), which removes the listener on abort. I ran the sleep, readFile, fetch and pipeline cases on Node 26 and each rejected with AbortError or TimeoutError as above.
Timeouts and combining signals
Two helpers cover most real situations:
// 3 s budget, no controller needed
const res = await fetch(url, { signal: AbortSignal.timeout(3000) });
// on timeout: TimeoutError "The operation was aborted due to timeout"
// stop on user cancel OR timeout, whichever first
const user = new AbortController();
const signal = AbortSignal.any([user.signal, AbortSignal.timeout(2000)]);
setTimeout(() => user.abort(new Error('user cancelled')), 30);
await fetch(url, { signal }); // rejects with Error: user cancelled
When abort(reason) is given a value, fetch rejects with exactly that reason, so err.message was user cancelled in my run. AbortSignal.timeout timers do not keep the process alive on their own.
In a server, link the request lifetime to a signal:
const server = createServer(async (req, res) => {
const controller = new AbortController();
res.on('close', () => controller.abort());
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
const rows = await queryDatabase(signal); // your function, forwards the signal
});
Making your own code cancellable
Nothing is stopped for you. Your function must accept the signal and either forward it to calls that take one, or check it:
async function processAll(items, { signal } = {}) {
for (const item of items) {
signal?.throwIfAborted(); // throws signal.reason
await handle(item, { signal });
}
}
Checking only at the top of an iteration means one handle finishes before the abort is noticed. For long single steps, pass the signal down. Remember cleanup too: remove listeners and close handles in a finally, because an abort is just another way for the function to exit.
What the video covers
Web Dev Simplified’s February 2025 video goes past the usual “cancel a fetch” case. Its description says AbortController does far more than cancel fetch requests, and links an article by Artem Zakharchenko and a video by Theo as references. I could not read a transcript, so I can’t list which extra uses it demonstrates. Its examples are browser-flavoured, so the Node-specific list of APIs that take a signal, AbortSignal.any for request lifetimes, and the cooperative-cancellation rule above come from this page.
Where this fits
Signals are how error-first callbacks and promises get a stop button. They show up again in fetch and undici for timeouts, in pipeline for stopping stream chains, and in child processes. The browser use of the same API is covered in the frontend lessons.
Check yourself
How do you give a `fetch` call a 3 second timeout in current Node?
Pass `signal: AbortSignal.timeout(3000)` in the options. If the request takes longer, the promise rejects with a `TimeoutError` whose message says the operation was aborted due to timeout. No `setTimeout` or controller is needed.
A request handler should stop if the client disconnects or if 5 seconds pass. How do you combine the two?
Create a controller aborted from `res.on('close')`, then pass `AbortSignal.any([controller.signal, AbortSignal.timeout(5000)])` to the work. The combined signal aborts on whichever happens first, and its `reason` is that first cause.
What is the difference between `AbortError` and `TimeoutError`?
`AbortSignal.timeout()` aborts with a `TimeoutError`, while a plain `controller.abort()` aborts with an `AbortError` unless you pass your own reason. Checking `err.name` lets you retry timeouts but treat deliberate cancels as normal.
You wrote an async function that loops over many items. Aborting its signal does nothing. Why?
Cancellation is cooperative. The function receives the signal but never looks at it. Call `signal.throwIfAborted()` at checkpoints, such as the top of each iteration, or forward the signal to the inner calls that support it.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.