A fetch timeout is not built into the Fetch API: there is no timeout option, and a request to a server that accepts the connection but never answers can hang far longer than any user will wait. The modern fix is a single line, AbortSignal.timeout(), and it works the same in current browsers and in Node.js. This guide shows how to set a deadline for the whole request including the body, cancel requests from the UI with AbortController, combine both with AbortSignal.any(), tell a timeout apart from a cancel, and handle streams that stall halfway. The Node.js test scripts below were run on Node.js 26 against a local test server that delays headers or body on purpose.

fetch timeout flow in JavaScript: AbortSignal.timeout and a user AbortController combined with AbortSignal.any, passed to fetch, rejecting with TimeoutError or AbortError
A fetch timeout built from signals: a deadline and a manual cancel combined and passed to fetch, with separate handling for TimeoutError and AbortError.

From my own work: In client integrations I review, a missing fetch timeout is one of the usual reasons a worker or serverless function stays busy until the platform kills it. A payment or shipping API slows down, every call waits, and the queue backs up. A deadline on each request turns that into a fast, visible error the retry logic can handle.

Why fetch has no timeout by default

The fetch() options object has method, headers, body and signal, but no timeout. Cancellation was designed as a separate, general mechanism: an AbortSignal that any API can watch (MDN: fetch()). Browsers do eventually give up on dead connections, and Node.js has transport-level limits, but those are measured in minutes, not the few seconds an API call should take.

In Node.js, the built-in fetch is implemented by undici. Its client options default to 300,000 ms for headersTimeout and bodyTimeout and 10,000 ms for connectTimeout, according to the undici Client documentation. So a server that accepts the TCP connection and then stalls can keep a Node.js request waiting for five minutes before undici gives up. Set your own deadline.

Add a fetch timeout with AbortSignal.timeout()

AbortSignal.timeout(ms) returns a signal that aborts itself after the given time, with a TimeoutError as the reason (MDN: AbortSignal.timeout()). Pass it as the signal option:

try {
  const res = await fetch("https://api.example.com/orders", {
    signal: AbortSignal.timeout(5000),   // 5 second deadline
  });
  const data = await res.json();
} catch (err) {
  if (err.name === "TimeoutError") {
    console.error("The API did not answer within 5 seconds");
  } else {
    throw err;
  }
}

To test this honestly, you need a server that is slow on purpose. This one delays headers on one route and trickles the body on another:

// slow-server.mjs - a test server with slow headers and a slow body
import http from "node:http";
import { setTimeout as sleep } from "node:timers/promises";

http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (url.pathname === "/slow-headers") {
    await sleep(Number(url.searchParams.get("ms") ?? 3000));
    return res.end("finallyn");
  }
  if (url.pathname === "/slow-body") {
    res.writeHead(200, { "content-type": "text/plain" });
    for (let i = 0; i < 5; i++) { res.write(`chunk ${i}n`); await sleep(1000); }
    return res.end();
  }
  res.end("fastn");
}).listen(8099, () => console.log("test server on :8099"));

Start it with node slow-server.mjs, then run the experiments below in a second terminal as node test.mjs.

The timeout also covers the response body

A common misunderstanding is that the signal only matters until headers arrive. In fact the same signal keeps watching while you read the body with res.json(), res.text() or a stream reader. A server that sends headers immediately and then dribbles data still hits the deadline:

const base = "http://localhost:8099";

// 1. AbortSignal.timeout while waiting for headers
try {
  await fetch(`${base}/slow-headers?ms=3000`, { signal: AbortSignal.timeout(1000) });
} catch (err) {
  console.log("1:", err.name, "|", err.message);
}

// 3. Timeout during body: headers arrive at once, body takes 5 s
const t = performance.now();
try {
  const res = await fetch(`${base}/slow-body`, { signal: AbortSignal.timeout(2500) });
  console.log("3: status", res.status, "after", Math.round(performance.now() - t), "ms");
  await res.text();
} catch (err) {
  console.log("3:", err.name, "after", Math.round(performance.now() - t), "ms");
}
1: TimeoutError | The operation was aborted due to timeout
3: status 200 after 14 ms
3: TimeoutError after 2504 ms

The status line arrived after 14 ms, yet the request still failed at 2.5 seconds while the body was being read. That is usually what you want: a deadline for the complete operation. If you need a different rule for long downloads, see the idle timeout section below.

Cancel requests manually with AbortController

An AbortController gives you a signal plus an abort() method you call yourself, for example when the user clicks Cancel, types a new search term or leaves the page (MDN: AbortController):

// 2. Manual AbortController
const ac = new AbortController();
setTimeout(() => ac.abort(), 500);
try {
  await fetch(`${base}/slow-headers?ms=3000`, { signal: ac.signal });
} catch (err) {
  console.log("2:", err.name, "|", err.message);
}

// 4. Custom reason
const ac4 = new AbortController();
ac4.abort(new Error("user navigated away"));
try { await fetch(base, { signal: ac4.signal }); } catch (err) { console.log("4:", err.name, "|", err.message); }
2: AbortError | This operation was aborted
4: Error | user navigated away

Without an argument, abort() rejects the fetch with an AbortError. If you pass a reason, fetch rejects with that exact value, which is handy for telling different cancel causes apart. One controller can cancel many requests at once: pass the same signal to all of them.

The older pattern you will still find in many answers, setTimeout(() => controller.abort(), ms), works but has two drawbacks: you must remember clearTimeout() on success, and the error is an AbortError, so you cannot tell a timeout from a user cancel. AbortSignal.timeout() fixes both.

Combine a timeout and a cancel with AbortSignal.any()

Real code often needs both: a deadline and a way for the caller to cancel. AbortSignal.any() takes a list of signals and returns one that aborts as soon as any of them does, with that signal’s reason (MDN: AbortSignal.any()). Here is a small wrapper that uses it, checks the HTTP status and turns a timeout into a clear message:

// fetch-timeout.mjs - Node.js 20.3+ and modern browsers
export class HttpError extends Error {
  constructor(response) {
    super(`HTTP ${response.status} ${response.statusText}`);
    this.name = "HttpError";
    this.status = response.status;
    this.response = response;
  }
}

/**
 * fetch with a deadline that covers headers AND body.
 * Pass options.signal to also allow cancellation by the caller.
 */
export async function fetchJson(url, { timeout = 8000, signal, ...init } = {}) {
  const timeoutSignal = AbortSignal.timeout(timeout);
  const combined = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
  try {
    const res = await fetch(url, { ...init, signal: combined });
    if (!res.ok) throw new HttpError(res);
    return await res.json();          // body reading is covered by the same signal
  } catch (err) {
    if (err.name === "TimeoutError") {
      throw new Error(`Request to ${url} timed out after ${timeout} ms`, { cause: err });
    }
    throw err;                        // AbortError (caller cancelled), HttpError, TypeError (network)
  }
}
import { fetchJson } from "./fetch-timeout.mjs";

// 5. Wrapper: the deadline wins
try { await fetchJson(`${base}/slow-headers?ms=3000`, { timeout: 800 }); }
catch (err) { console.log("5:", err.message, "| cause:", err.cause.name); }

// 6. Wrapper: the caller's cancel wins
const ac6 = new AbortController();
setTimeout(() => ac6.abort(), 200);
try { await fetchJson(`${base}/slow-headers?ms=3000`, { timeout: 5000, signal: ac6.signal }); }
catch (err) { console.log("6:", err.name); }
5: Request to http://localhost:8099/slow-headers?ms=3000 timed out after 800 ms | cause: TimeoutError
6: AbortError

TimeoutError, AbortError and TypeError: what each means

Check err.name, never the message text, which differs between browsers and Node.js versions:

err.name Cause Typical handling
TimeoutError An AbortSignal.timeout() signal fired Retry if the request is idempotent, or show a slow-network message
AbortError controller.abort() without a reason Usually ignore: the user or your code cancelled on purpose
Your reason’s name controller.abort(reason) with a custom value Handle according to the reason you passed
TypeError Network failure: DNS, refused connection, TLS, CORS in browsers Retry with backoff; check connectivity
(no error) HTTP 4xx or 5xx: fetch resolves normally Check res.ok or res.status yourself

The last row catches many people: fetch only rejects for network-level failures and aborts. A 500 response is a successful fetch with res.ok === false, which is why the wrapper throws its own HttpError. For APIs you control, a consistent error body helps clients act on these cases; see RFC 9457 problem details for API errors.

Idle timeouts for long downloads and streams

A total deadline is wrong for a large download or a streamed response that legitimately takes a minute. What you really want to catch there is a stall: no data for N seconds. Reset a timer every time a chunk arrives:

// idle.mjs - abort only when the stream stalls, not when it is merely long
export async function fetchWithIdleTimeout(url, { idle = 2000, ...init } = {}) {
  const ac = new AbortController();
  let timer;
  const arm = () => {
    clearTimeout(timer);
    timer = setTimeout(() => ac.abort(new DOMException(`no data for ${idle} ms`, "TimeoutError")), idle);
  };
  arm();
  try {
    const res = await fetch(url, { ...init, signal: ac.signal });
    const chunks = [];
    for await (const chunk of res.body) {   // Node.js; in browsers use res.body.getReader()
      arm();                                // data arrived: reset the idle timer
      chunks.push(chunk);
    }
    return Buffer.concat(chunks).toString("utf8");
  } finally {
    clearTimeout(timer);
  }
}
import { fetchWithIdleTimeout } from "./idle.mjs";
const t = performance.now();
const text = await fetchWithIdleTimeout("http://localhost:8099/slow-body", { idle: 1500 });
console.log(text.trim().split("n").length, "chunks in", Math.round(performance.now() - t), "ms");
try { await fetchWithIdleTimeout("http://localhost:8099/slow-headers?ms=3000", { idle: 1000 }); }
catch (e) { console.log(e.name, e.message); }

// 5 chunks in 5059 ms
// TimeoutError no data for 1000 ms

The five-second body succeeds because a chunk arrives every second, below the 1.5 second idle limit, while the silent endpoint fails after one second. Passing a DOMException named TimeoutError as the reason keeps error handling identical to AbortSignal.timeout().

Cancel fetch requests in React effects

In a React component, abort the request in the effect’s cleanup function. This prevents an old, slow response from overwriting newer state when the user changes a filter quickly, and stops work when the component unmounts:

useEffect(() => {
  const ac = new AbortController();
  const signal = AbortSignal.any([ac.signal, AbortSignal.timeout(8000)]);

  fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal })
    .then((res) => res.json())
    .then(setResults)
    .catch((err) => {
      if (err.name === "AbortError") return;           // cleanup ran: ignore
      setError(err.name === "TimeoutError" ? "Search is slow, try again" : "Search failed");
    });

  return () => ac.abort();                             // runs on query change and unmount
}, [query]);

Timeouts with retries: one deadline per attempt

When you retry, create a fresh timeout signal for each attempt. If you create a single AbortSignal.timeout() outside the loop and the first attempt times out, that signal is already aborted, so every retry fails instantly. If you also want an overall budget, combine a per-attempt signal with one outer signal:

const overall = AbortSignal.timeout(20000);           // whole operation, all attempts
for (let attempt = 1; attempt <= 3; attempt++) {
  try {
    return await fetchJson(url, { timeout: 5000, signal: overall });   // new 5 s deadline each time
  } catch (err) {
    if (overall.aborted || attempt === 3) throw err;
    await new Promise((r) => setTimeout(r, 2 ** attempt * 250));
  }
}

Only retry idempotent requests such as GET, or requests protected by an idempotency key. Backoff with jitter, Retry-After handling and which status codes to retry are covered in depth in retry with exponential backoff and jitter in JavaScript. If you are on the receiving end of webhooks, remember the sender has its own timeout too: acknowledge quickly and process later, as described in webhook signature verification.

Runtime support and choosing timeout values

AbortSignal.timeout() and AbortSignal.any() are available in current versions of Chrome, Edge, Firefox and Safari; MDN lists the exact versions in the compatibility tables on each page (MDN: compatibility). In Node.js, AbortSignal.timeout() was added in 17.3.0 and 16.14.0 and AbortSignal.any() in 20.3.0 and 18.17.0, so any supported LTS release has both. If you must support older browsers, fall back to an AbortController with setTimeout and clearTimeout.

For values, start from what the user or the caller can tolerate, not from what the API usually needs:

  • Interactive UI requests: a few seconds, with a visible retry option.
  • Server-to-server API calls: a little above the dependency’s normal p99 latency, and always below your own request timeout so you can still return a proper error.
  • Background jobs and downloads: an idle timeout plus a generous overall limit.
  • Event loop health: a timeout that fires late usually means the process is blocked; see Node.js event loop latency for how to measure that.

fetch timeout checklist

  • Every outbound fetch() has a signal; no request can wait indefinitely.
  • AbortSignal.timeout() for deadlines; AbortController for user cancels; AbortSignal.any() to combine.
  • Errors classified by err.name: TimeoutError, AbortError, TypeError.
  • res.ok checked, because HTTP errors do not reject.
  • Body reading inside the same try block, covered by the same signal.
  • Idle timeouts for long streams instead of short total deadlines.
  • A new timeout signal for every retry attempt.
  • React effects abort in cleanup and ignore AbortError.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

Does fetch have a timeout option?

No. The Fetch API has no timeout option. You add one by passing a signal, most simply signal: AbortSignal.timeout(5000), which aborts the request after five seconds and rejects the promise with a TimeoutError.

What is the difference between TimeoutError and AbortError?

TimeoutError comes from a signal created with AbortSignal.timeout() when the time runs out. AbortError comes from calling abort() on an AbortController without a reason. Checking err.name lets you show a slow-network message for the first and silently ignore the second.

Does AbortSignal.timeout stop reading the response body?

Yes. The signal stays attached to the response, so if the deadline passes while you are still reading res.json(), res.text() or a stream, reading fails with a TimeoutError. In the test above, headers arrived after 14 ms and the body read still failed at 2.5 seconds.

How do I combine a timeout with a cancel button?

Create an AbortController for the button and pass AbortSignal.any([controller.signal, AbortSignal.timeout(ms)]) to fetch. Whichever fires first aborts the request, and the error name tells you which one it was.

What is the default fetch timeout in Node.js?

Node.js fetch uses undici, whose client defaults are 300 seconds for receiving headers, 300 seconds between body chunks and 10 seconds for connecting. There is no shorter overall deadline unless you pass a signal yourself.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.