javascript fetch timeout

A javascript fetch timeout is a limit on how long fetch() may wait. You set that limit with an AbortSignal. AbortSignal.timeout() builds one for you.

const response = await fetch("https://example.com/data.json", {
  signal: AbortSignal.timeout(5000),
});
const data = await response.json();

AbortSignal.timeout(5000) returns a signal that aborts after 5000 milliseconds of active time. fetch() sends the request with that signal attached. The fetch() promise resolves once the response headers arrive, or it rejects if the signal aborts first. response.json() then reads the body. If the signal aborts during that read, json() rejects too. The name on that rejection is TimeoutError. The clock started when AbortSignal.timeout() ran, so the headers and the body share one 5 second budget.

Without a signal, a server that accepts the connection and then stays quiet leaves the promise pending. The page sits on a spinner for as long as the browser is willing to hold the socket.

What happens with no timeout

The Fetch standard’s RequestInit dictionary has signal. It does not have timeout. There is no argument that means “give up after 8 seconds.”

Browsers still give up in some phases of opening a connection, on their own timers, and those timers are not the timeout you wanted. In Chromium, TransportConnectJob::ConnectionTimeout() returns 4 minutes. That limit covers the transport connect job, and the comment next to it says a single operating-system connect can itself run anywhere from 20 seconds to 190 seconds. Firefox’s network.http.connection-timeout preference defaults to 90 seconds. The preference comment says that is how long Firefox waits after the initial SYN before giving up, if the operating system has not given up first. A server that already accepted the socket and then sends nothing is past those connect limits. fetch() has no deadline of its own for that wait.

AbortSignal.timeout()

AbortSignal.timeout(milliseconds) is a static method. It returns a new AbortSignal. When the time is up, the signal aborts, and its reason is a TimeoutError DOMException. You do not create an AbortController, and you do not call clearTimeout().

try {
  const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
  const data = await response.json();
  console.log(data);
} catch (error) {
  if (error.name === "TimeoutError") {
    console.error("The request took more than 5 seconds");
  } else {
    throw error;
  }
}

fetch() and json() are both inside the try. A timeout in either step lands in the catch. error.name is "TimeoutError" when this signal fired. Any other failure is rethrown.

The method is in Firefox 100, Safari 16, and Chrome 124. Chrome 103 through 123 already had AbortSignal.timeout(), but that implementation always aborted with an AbortError, not a TimeoutError. A check for error.name === "TimeoutError" misses those Chrome versions. Node.js has had the method since 16.14.0 and 17.3.0.

MDN describes this wait as active time. It pauses while the document is in the back-forward cache, and while a worker is suspended. There is no handle that cancels this timer early. Finishing the request does not cancel it either. Once the body has been read, a later abort is harmless, because rejecting an already settled fetch() promise does nothing and a body stream that is already closed is not read again. If you still need the timer gone as soon as the read finishes, use AbortController and clearTimeout(), below.

typeof AbortSignal.timeout === "function" tells you the method exists. It does not tell you that the error name is TimeoutError, because Chrome 103 through 123 pass that test and still use AbortError.

AbortController and setTimeout

AbortController is the older tool, and it is the one that can abort early for a reason other than a clock. Chrome 66, Firefox 57, Safari 12.1, and Edge 16 can abort a fetch() with it. Safari 11.1 exposed AbortController, but aborting did not cancel fetch().

async function loadData(url) {
  const controller = new AbortController();
  const timer = setTimeout(() => {
    controller.abort(new DOMException("The operation timed out.", "TimeoutError"));
  }, 8000);

  try {
    const response = await fetch(url, { signal: controller.signal });
    const data = await response.json();
    return data;
  } finally {
    clearTimeout(timer);
  }
}

loadData creates a fresh controller. setTimeout calls abort() after 8000 milliseconds and passes a TimeoutError DOMException, so a caller that catches the rejection sees error.name === "TimeoutError". The reason argument on abort() is supported in Chrome 98, Firefox 97, and Safari 15.4. On older browsers abort() still cancels the request, and the reason is an AbortError whether or not you passed one. fetch() uses controller.signal. response.json() reads the body while that same signal is still armed, so a slow body aborts too. finally calls clearTimeout(). That runs after json() resolves or rejects, which is why the timer is still active during the body read. Clearing the timer as soon as fetch() resolves would stop the clock before the body starts, and a slow body would have no limit.

clearTimeout() also matters in Node.js. A setTimeout that is still scheduled keeps the process alive. After the read finishes you do not want that timer to fire, and you do not want the process to wait for it.

abort() with no argument sets the reason to an AbortError DOMException. Calling abort() again does not change that reason. The signal stays aborted, so a later fetch() that reuses it rejects immediately. One controller can be passed to several requests when you want one cancel to stop all of them. The next request, after an abort, needs a new controller.

A wrapper has to keep a signal the caller already passed. Replacing options.signal drops their cancel.

function fetchWithTimeout(url, options = {}, timeout = 8000) {
  const controller = new AbortController();
  const timer = setTimeout(() => {
    controller.abort(new DOMException("The operation timed out.", "TimeoutError"));
  }, timeout);

  if (options.signal) {
    if (options.signal.aborted) {
      controller.abort(options.signal.reason);
    } else {
      options.signal.addEventListener(
        "abort",
        () => controller.abort(options.signal.reason),
        { once: true }
      );
    }
  }

  return fetch(url, { ...options, signal: controller.signal }).finally(() => {
    clearTimeout(timer);
  });
}

The timer calls controller.abort() with a TimeoutError. If options.signal is already aborted, the controller aborts with that signal’s reason before fetch() runs, and fetch() rejects immediately with the same reason. Otherwise a listener aborts the controller when the caller’s signal aborts, and the listener runs once. fetch() receives controller.signal, not options.signal. The function returns the promise from finally, so a rejection still reaches the caller, and clearTimeout() runs when that fetch() promise settles. Settlement here is the header wait. The returned response can still be reading its body after the timer is gone. To put the body on the same clock, read it before clearing, as in the try / finally above, or use AbortSignal.timeout(), which stays armed until it fires.

In TypeScript the extra timeout number is not a field of RequestInit, so the options type is an intersection.

type FetchTimeoutOptions = RequestInit & { timeout?: number };

function fetchWithTimeout(
  url: string,
  options: FetchTimeoutOptions = {}
): Promise<Response> {
  const { timeout = 8000, signal, ...rest } = options;
  const deadline = AbortSignal.timeout(timeout);
  return fetch(url, {
    ...rest,
    signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
  });
}

timeout is pulled out of options so it is not passed through to fetch(). AbortSignal.timeout(timeout) is the deadline. When the caller also passed signal, AbortSignal.any() aborts on the first of the two. The return type is Promise<Response>, the same promise fetch() returns.

Promise.race leaves the request running

Promise.race() settles with whichever promise settles first. That is not the same as aborting the request.

const response = await Promise.race([
  fetch(url),
  new Promise((_, reject) => {
    setTimeout(() => reject(new Error("timeout")), 5000);
  }),
]);

Promise.race watches two promises. If the timer rejects first, this await throws Error: timeout, and the fetch() promise is still pending. The browser or Node.js keeps the socket open, and the response can still arrive later. If fetch() wins the race, the timer is still scheduled. You also have no TimeoutError. Use a signal when the request itself has to stop.

Telling a timeout from other failures

fetch() rejects for a network failure. It does not reject for an HTTP error status. A 404 still resolves, and response.ok is false.

const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
if (!response.ok) {
  throw new Error("HTTP " + response.status);
}
const data = await response.json();

The await fetch() line rejects with a TimeoutError if the signal aborts before the headers, and with a TypeError if the failure is a network error. The Fetch standard says a network error rejects the fetch() promise with a TypeError. That covers a refused connection, a DNS failure, and a CORS failure. An HTTP 404 does not take either path. response.ok is checked next, and only then does json() read the body, where a late timeout can still throw TimeoutError.

AbortController.abort() with no reason also rejects with an AbortError. That is the same name you get if the person hits the browser stop button. TimeoutError means this signal was created by AbortSignal.timeout(), or you passed a DOMException with that name into abort() yourself. AbortError means something aborted the request without that timeout reason. Those two names are why a timeout message and a cancel message can be different strings.

Cancel, or time out, whichever comes first

AbortSignal.any() takes signals and returns one that aborts when the first of them aborts. The reason on the combined signal is the reason from the signal that fired.

const cancel = new AbortController();
cancelButton.addEventListener("click", () => {
  cancel.abort();
});

try {
  const response = await fetch(url, {
    signal: AbortSignal.any([cancel.signal, AbortSignal.timeout(5000)]),
  });
  const data = await response.json();
  console.log(data);
} catch (error) {
  if (error.name === "TimeoutError") {
    console.error("Timed out");
  } else if (error.name === "AbortError") {
    console.error("Cancelled");
  } else {
    throw error;
  }
}

The click listener calls cancel.abort() with no argument, so that signal’s reason is an AbortError. AbortSignal.timeout(5000) aborts with a TimeoutError. AbortSignal.any() is the signal fetch() sees. A click before 5 seconds rejects with AbortError. The timer winning rejects with TimeoutError. any() does not stop the timeout timer if the click happens first. The timeout can still fire later. That later abort does not change the combined signal, which has already aborted.

AbortSignal.any() is in Chrome 116, Firefox 124, and Safari 17.4. In Node.js it is in 18.17.0 and, after the 19.x releases, in 20.3.0.

Retrying a timed-out request

A timeout or a 500 can be a short outage. Retry a request that is safe to send twice, such as a GET. A POST that charges a card is not that kind of request. Each attempt needs a new AbortSignal.timeout(), because an aborted signal stays aborted.

async function fetchWithRetry(url, options = {}, timeout = 8000) {
  let wait = 200;
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const response = await fetch(url, {
        ...options,
        signal: AbortSignal.timeout(timeout),
      });
      if (response.status < 500 || attempt === 3) return response;
      await response.body?.cancel();
    } catch (error) {
      if (error.name !== "TimeoutError" || attempt === 3) throw error;
    }
    await new Promise((resolve) => setTimeout(resolve, wait));
    wait *= 2;
  }
}

The loop runs at most three times. Each pass creates a new timeout signal and calls fetch(). A status under 500 returns that response, including a 404. You still have to check response.ok after this function returns. A status of 500 or more, before the last attempt, cancels the unread body and falls through to the wait. A TimeoutError also falls through, unless this was the last attempt. Any other rejection, including an AbortError or a TypeError, is thrown on the spot. After a failure that will be retried, the function waits 200 milliseconds, then 400. Chrome 103 through 123 report a timeout from AbortSignal.timeout() as AbortError, so this function does not retry that case. It throws it.

How long to wait

The limit has to be longer than the server takes on a slow but successful call. A health check can use 2 to 5 seconds. A normal JSON request can use 8 to 15 seconds. An upload or a large export can use 30 seconds or more. Those are choices you pass in. They are not a default of fetch().

Pass the number into the helper instead of hiding a different literal in each call site. A limit of a few seconds on a download that you know takes a minute will fail the requests that were going to succeed.

Node.js

Node’s global fetch() follows the same signal rules. It has been available without the --experimental-fetch flag since Node.js 18.0.0, and it has not been experimental since 21.0.0. AbortSignal.timeout() is older than that global. It is in Node.js 16.14.0 and 17.3.0, so code on those versions can pass the signal to a library that accepts one, but fetch itself is not a global yet.

When the signal comes from AbortSignal.timeout(), Node’s fetch() rejects with a TimeoutError DOMException, including when the abort happens during the body read. The try / finally pattern above is the same. clearTimeout() is what lets a short script exit, because a pending setTimeout holds the process open.

node-fetch is a separate package. Version 2 has a timeout option, a number of milliseconds. 0 means no timeout, and that timer resets on redirect. Since version 2.3.0 it also accepts signal. Version 3 removed the timeout option. You pass signal there, the same way you do with global fetch().

Axios is also a different client. Its request config has timeout, in milliseconds, and Axios aborts the request when that time passes. That field is not part of fetch().

If this article was helpful, tweet it!