← Back to Snippets
JavaScriptJun 2026

Fetch with retry on failure

Retries a failed fetch request up to N times with exponential backoff between attempts.

snippet
async function fetchWithRetry(url, options = {}, retries = 3) {
  for (let attempt = 0; attempt < retries; attempt++) {
    try {
      const res = await fetch(url, options)
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return await res.json()
    } catch (err) {
      if (attempt === retries - 1) throw err
      await new Promise(r => setTimeout(r, 2 ** attempt * 500))
    }
  }
}

// Usage
const data = await fetchWithRetry('https://api.example.com/users')
FetchRetryError Handling