Skip to content
jshacks.dev
Async

Fetch with a fallback mirror

Fetch with a fallback mirror in JavaScript: try each URL in order with a timeout and return the first good response. Node.js 24 and browsers.

1 min read
Summarize in AI

When the primary host is down or slow, try the next URL. A loop over the list with a timeout on each attempt is all it takes.

JavaScript
async function fetchFirst(urls, doFetch = fetch) {
  let lastError;
  for (const url of urls) {
    try {
      console.log('trying', url);
      const res = await doFetch(url, { signal: AbortSignal.timeout(2000) });
      if (res.ok) return res;
      lastError = new Error(`${url} answered ${res.status}`);
    } catch (err) {
      lastError = err;
    }
  }
  throw lastError;
}

const fake = async (url) =>
  url.includes('primary') ? { ok: false, status: 503 } : { ok: true, status: 200 };

const res = await fetchFirst(
  ['https://primary.example.com/data', 'https://mirror.example.com/data'],
  fake,
);
console.log(res.status);
Text
trying https://primary.example.com/data
trying https://mirror.example.com/data
200

fetch only rejects on a network failure, not on a 503, so the code checks res.ok itself. [AbortSignal.timeout](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static) makes a hanging host fail after two seconds instead of blocking the fallback. The demo passes a fake fetch so the output is the same on every run; in real use you call fetchFirst(urls).

This tries the mirrors one at a time, which is slow if the first is down. To be faster at the cost of extra traffic, race them with Promise.any.

Also inBrowser
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.