Sequence NODE_239
Medium

Wrap Fetch with Retry Logic in Node

Node.js
Technical Specification

Implement a fetchWithRetry(url, options, maxRetries) helper that retries on network errors or 5xx responses.

Input/Output Samples
Input:fetchWithRetry('https://api', {}, 3)
Output:Attempts up to 3 times
Optimal Logic Path
async function sleep(ms) {
  return new Promise((res) => setTimeout(res, ms));
}

async function fetchWithRetry(url, options = {}, maxRetries = 3) {
  let attempt = 0;
  while (true) {
    try {
      const res = await fetch(url, options);
      if (!res.ok && res.status >= 500 && attempt < maxRetries) {
        attempt++;
        await sleep(500);
        continue;
      }
      return res;
    } catch (err) {
      if (attempt >= maxRetries) throw err;
      attempt++;
      await sleep(500);
    }
  }
}

module.exports = { fetchWithRetry };
Architectural Deep-Dive
We wrap fetch in a retry loop with delays, reattempting on 5xx errors or thrown network errors.