AZ.dev

Give a fetch call a timeout

| node: 18+ browsers: all modern

Pass AbortSignal.timeout() as the request’s signal. The fetch rejects with a TimeoutError when the time is up.

const res = await fetch(url, { signal: AbortSignal.timeout(5000) });

Catch it by name if you want to tell a timeout apart from a network failure:

try {
  const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
  return await res.json();
} catch (err) {
  if (err.name === "TimeoutError") throw new Error(`${url} timed out after 5s`);
  throw err;
}

Cancel for another reason too

When the timeout has to combine with a user cancel or a shutdown signal, use AbortSignal.any():

const signal = AbortSignal.any([AbortSignal.timeout(5000), controller.signal]);

Node 20.3 and up, and current browsers.

Gotchas

fetch timeout AbortSignal AbortController http

This entry is one card on a printable cheat sheet:

Node.js Essentials Cheat Sheet

Was this helpful?

Related Entries

Reproduce Railway's npm ci locally with the exact npm versionSerialize per-user check-then-write flows with pg_advisory_xact_lock(hashtext(id))Content-hash dedup that restores a soft-deleted row must re-run quota and limit checksA storage URL builder and its static file handler must share one prefix constantFail a Node script without cutting off its output