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.
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.
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);trying https://primary.example.com/data
trying https://mirror.example.com/data
200fetch 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.