Retry Fetch With Exponential Backoff

A resilient fetch wrapper that retries failed requests with exponential backoff and a jittered cap for unreliable networks.

JavascriptData Fetching

Code

export async function fetchWithRetry(url, options = {}, policy = {}) {
  const maxRetries = policy.maxRetries ?? 3;
  const baseDelayMs = policy.baseDelayMs ?? 100;
  const maxDelayMs = policy.maxDelayMs ?? 5000;
  let lastError;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const res = await fetch(url, options);
      if (res.status >= 500) throw new Error("server error " + res.status);
      return res;
    } catch (err) {
      lastError = err;
      if (attempt === maxRetries) break;
      const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
      await new Promise((r) => setTimeout(r, backoff));
    }
  }
  throw lastError;
}