← Back to Node.js, page 3

nodejs-0052 · Medium mid

How do AbortController and AbortSignal work in Node.js, and how do you use them for timeouts and cancellation?

An AbortController owns a signal. Calling controller.abort() marks the signal as aborted and fires an abort event. APIs that accept a signal (fetch, timers/promises, fs, events, streams, child_process) stop and reject with an AbortError. AbortSignal.timeout(ms) gives a signal that aborts by itself, and AbortSignal.any combines signals.

Full answer

Promises cannot be cancelled by themselves. AbortController is the standard way to say "stop this work".

Parts:

  • controller = new AbortController() and controller.signal.
  • controller.abort(reason) sets signal.aborted to true, sets signal.reason (an AbortError by default), and fires the 'abort' event once.
  • AbortSignal.timeout(ms) returns a signal that aborts after ms with a TimeoutError. The timer does not keep the process alive.
  • AbortSignal.any([a, b]) aborts when any of the signals aborts, which is good for "user cancelled or 5 seconds passed".
  • signal.throwIfAborted() throws the reason when called after an abort.

Where Node accepts a signal: fetch, fs.promises.readFile and writeFile, timers/promises, events.once and events.on, stream.pipeline, child_process.spawn, http.request, readline and worker setup. The call stops its work and rejects with an error whose name is AbortError (or TimeoutError for timeouts).

Supporting a signal in your own function: check signal.aborted before starting, listen with signal.addEventListener('abort', handler, { once: true }), stop the real work in the handler, and remove the listener when finished.

Typical uses: request timeouts, cancelling work when a client disconnects, stopping background loops during shutdown, and cleaning up in tests.

An aborted signal stays aborted. Create a new controller for each operation.

javascript
const http = require('node:http');
const { setTimeout: sleep } = require('node:timers/promises');

// Your own function that supports cancellation.
async function slowJob(ms, { signal } = {}) {
  signal?.throwIfAborted();
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve('job finished'); }, ms);
    const onAbort = () => { clearTimeout(timer); reject(signal.reason); };
    signal?.addEventListener('abort', onAbort, { once: true });
  });
}

async function main() {
  // A server that answers after 200 ms.
  const server = http.createServer((req, res) => setTimeout(() => res.end('late answer'), 200));
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const url = 'http://127.0.0.1:' + server.address().port;

  // 1. fetch with a timeout signal
  await fetch(url, { signal: AbortSignal.timeout(50) }).catch((err) => console.log('fetch timeout ->', err.name));

  // 2. manual abort with a custom reason
  const controller = new AbortController();
  setTimeout(() => controller.abort(new Error('user pressed cancel')), 20);
  await fetch(url, { signal: controller.signal }).catch((err) => console.log('manual abort ->', err.name + ':', err.message));

  // 3. timers/promises accept a signal too
  const c2 = new AbortController();
  const waiting = sleep(1000, 'never used', { signal: c2.signal });
  c2.abort();
  await waiting.catch((err) => console.log('sleep aborted ->', err.name));

  // 4. our own function, plus AbortSignal.any
  const user = new AbortController();
  const combined = AbortSignal.any([user.signal, AbortSignal.timeout(30)]);
  await slowJob(500, { signal: combined }).catch((err) => console.log('slowJob stopped by ->', err.name));
  console.log('slowJob without a signal:', await slowJob(5));
  console.log('user signal aborted:', user.signal.aborted, '| combined aborted:', combined.aborted);

  server.close();
}

main();

The combined signal aborts through the timeout, so the user signal itself stays unaborted. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): fetch timeout -> TimeoutError manual abort -> Error: user pressed cancel sleep aborted -> AbortError slowJob stopped by -> TimeoutError slowJob without a signal: job finished user signal aborted: false | combined aborted: true

Key points

  • abort() fires the abort event once and sets signal.reason.
  • AbortSignal.timeout and AbortSignal.any cover timeouts and combined cancellation.
  • Aborted calls reject with AbortError or TimeoutError.
  • Custom functions should accept a signal and clean up listeners.

Common mistakes

  • Reusing an aborted controller for a second request.
  • Forgetting to remove abort listeners, which leaks memory in long-lived signals.
  • Aborting but not stopping the real work behind the promise.
  • Treating AbortError and TimeoutError as the same thing in error handling.

Follow-ups

  • How do you cancel a stream pipeline?
  • How does a server learn that the client closed the connection?
  • What is the difference between signal.reason and the error you catch?

Tips

  • Say that promises cannot be cancelled, so the signal is a cooperative request.
  • Use AbortSignal.timeout for any outgoing HTTP call.
  • Mention cleanup of listeners to show care.