JavaScript

Fetch with Retry

by @admin
12h ago
Apr 28, 2026
Public
Wraps the native fetch API with automatic retry logic using exponential backoff. Retries on network errors or non-OK HTTP responses up to a configurable number of attempts. Exponential backoff with optional jitter prevents thundering herd problems when many clients retry simultaneously.
JavaScript
async function fetchRetry(url, options = {}, retries = 3, backoff = 300) {
  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetch(url, options);
      if (res.ok) return res;
      if (res.status < 500) throw new Error(`HTTP ${res.status}`); // don't retry 4xx
    } catch (err) {
      if (i === retries - 1) throw err;
    }
    await new Promise((r) => setTimeout(r, backoff * 2 ** i));
  }
}

// Usage
const res  = await fetchRetry('/api/data', {}, 3, 500);
const data = await res.json();
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.