@wuyuchentr/fetch-retry-polyfill
v1.0.0
Published
Auto-retry wrapper for fetch with exponential backoff and custom retry conditions. < 1 KB, zero deps.
Maintainers
Readme
@wuyuchentr/fetch-retry-polyfill
Auto-retry wrapper for fetch with exponential backoff and custom retry conditions. < 1 KB, zero dependencies.
Install
npm install @wuyuchentr/fetch-retry-polyfillUsage
const { fetchRetry } = require('@wuyuchentr/fetch-retry-polyfill');
// Basic — retry up to 3 times on network errors / 5xx
const res = await fetchRetry('https://api.example.com/data');
// Custom retries and delay
const res = await fetchRetry('https://api.example.com/data', {
retries: 5,
retryDelay: 500,
});Retry on specific status codes
const res = await fetchRetry('https://api.example.com/data', {
retries: 3,
retryOn: [429, 502, 503, 504],
});Custom retry condition
const res = await fetchRetry('https://api.example.com/data', {
retries: 3,
retryOn: (attempt, error, response) => {
if (error) return true; // network error → retry
if (response && response.status === 429) return true; // rate limit → retry
if (attempt < 2 && response && response.status >= 500) return true; // 5xx, retry twice
return false;
},
});API
fetchRetry(url, options?)
Same signature as native fetch(url, init), with extra options:
| Option | Default | Description |
|--------|---------|-------------|
| retries | 3 | Max retry attempts |
| retryDelay | 1000 | Base delay in ms (exponential: delay × 2^attempt) |
| retryOn | — | Array of status codes, or (attempt, error, response) => boolean |
Default retry condition:
- Network errors: always retry
- HTTP 5xx: retry
- HTTP 4xx: no retry
All other init options (method, headers, body, etc.) are passed through to fetch.
