Fetch JSON With Retry and Timeout
Fetch JSON from an endpoint, applying a per-attempt timeout and retrying transient failures while treating client errors as final.
Code
export async function fetchJson(url, options = {}) {
const attempts = options.attempts ?? 3;
const timeoutMs = options.timeoutMs ?? 5000;
let lastError;
for (let attempt = 1; attempt <= attempts; attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, { signal: controller.signal });
if (response.status >= 500) throw new Error("server error " + response.status);
if (!response.ok) return { ok: false, status: response.status, data: null };
return { ok: true, status: response.status, data: await response.json() };
} catch (error) {
lastError = error;
} finally {
clearTimeout(timer);
}
}
throw lastError;
}What the code does
Fetch JSON With Retry and Timeout comes down to the function fetchJson.
Repetition is confined to for (let attempt = 1; attempt <= attempts; attempt++) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The Error throw is the give-up path: it fires only after the loop above it has gone through every attempt without the early return firing.
The result comes back as an object carrying false, status.
Points of care
fetchexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
response.status >= 500short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The primary signature is export async function fetchJson(url, options = {})
Import fetchJson from the file and call it — the rest of the code is implementation detail.
The call returns false, status — destructure what you need at the call site.
Statements that matter
return { ok: true, status: response.status, data: await response.json() };
if (response.status >= 500) throw new Error("server error " + response.status);
if (!response.ok) return { ok: false, status: response.status, data: null };
Interactive Tools for This Topic
FAQ
- Does `fetchJson` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- When does the code throw?
- On the exhaustion path: `Error` is thrown after the loop has gone through every attempt without the early return firing.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `fetchJson` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.