retry-fetch-pro
v1.0.1
Published
Zero-dependency, type-safe promise retry utility with exponential backoff, jitter, timeout, and abort signal support.
Maintainers
Readme
🔄 retry-fetch-pro
Zero-dependency, type-safe promise retry utility with exponential backoff, jitter, timeout, and abort signal support.
✨ Features
- ⚡ Zero Dependencies — Ultra-lightweight, purely native JavaScript / TypeScript.
- 📈 Exponential Backoff — Configurable base delay, multiplier, and maximum delay ceiling.
- 🎲 Full Jitter — Randomizes retry delays to prevent thundering-herd issues on downstream servers.
- ⏱️ Per-Attempt Timeout — Fails fast if any individual attempt hangs (
timeoutMs). - 🛑 AbortSignal Support — Instantly cancel in-flight or scheduled retries using
AbortController. - 🔍 Fine-Grained Filtering — Custom
shouldRetrypredicate to skip non-retryable errors (e.g. 401, 404). - 📡 Built-in
retryFetch— Drop-in wrapper around nativefetchwith automatic 5xx server error retry. - 📦 Dual ESM & CommonJS — Native compatibility with modern bundlers, Node.js, and browsers.
📥 Installation
npm install retry-fetch-proor with Yarn / pnpm:
pnpm add retry-fetch-pro
# or
yarn add retry-fetch-pro🚀 Quick Start
1. Basic Retry with Default Exponential Backoff
import { retryAsync } from 'retry-fetch-pro';
async function loadData() {
const result = await retryAsync(async (attempt) => {
console.log(`Trying attempt #${attempt}...`);
const res = await fetch('https://api.example.com/items');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
});
return result;
}2. Built-in retryFetch
Automatically retries network drops and 5xx server errors:
import { retryFetch } from 'retry-fetch-pro';
const response = await retryFetch('https://api.example.com/data', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
}, {
retries: 3,
delayMs: 1000,
});
const data = await response.json();3. Advanced Configuration
import { retryAsync, TimeoutError, AbortError } from 'retry-fetch-pro';
const controller = new AbortController();
try {
const data = await retryAsync(
async (attempt) => {
return await makePaymentApiCall();
},
{
retries: 4, // Max 4 retry attempts
delayMs: 500, // Start with 500ms delay
maxDelayMs: 10000, // Maximum delay capped at 10s
backoffFactor: 2, // 500ms -> 1000ms -> 2000ms -> 4000ms
jitter: true, // Add random jitter to avoid spike traffic
timeoutMs: 3000, // Fail single attempt if > 3s
signal: controller.signal, // Cancel anytime via controller.abort()
// Skip retry for client error 400, 401, 403, 404
shouldRetry: (error, attempt) => {
if (error instanceof Error && error.message.includes('404')) {
return false; // Do not retry
}
return true;
},
// Hook invoked before each sleep/retry
onRetry: (attempt, error, nextDelayMs) => {
console.warn(`Attempt ${attempt} failed with: ${(error as Error).message}. Retrying in ${nextDelayMs}ms...`);
},
}
);
} catch (err) {
if (err instanceof TimeoutError) {
console.error('Request timed out!');
} else if (err instanceof AbortError) {
console.warn('Request was cancelled by user');
} else {
console.error('All retries failed:', err);
}
}⚙️ Options Reference
| Option | Type | Default | Description |
|---|---|---|---|
| retries | number | 3 | Maximum number of retry attempts. |
| delayMs | number | 500 | Initial delay in milliseconds before the first retry. |
| maxDelayMs | number | 30000 | Ceiling limit for exponential backoff delay. |
| backoffFactor | number | 2 | Multiplier applied to delay after each retry. |
| jitter | boolean | true | When true, randomizes backoff to avoid synchronized retry storms. |
| timeoutMs | number | undefined | Per-attempt timeout in milliseconds. Throws TimeoutError. |
| signal | AbortSignal | undefined | Optional signal to cancel all pending retries. |
| shouldRetry | (err, attempt) => boolean \| Promise<boolean> | () => true | Predicate function to allow or block retries. |
| onRetry | (attempt, err, delay) => void | undefined | Callback invoked before each wait cycle. |
🛠 Development & Testing
# Install dependencies
npm install
# Run unit tests
npm test
# Build dual ESM/CJS bundles + .d.ts types
npm run build🚢 Publishing to NPM
- Login to your NPM account:
npm login - (Optional) If publishing under your scope, rename
"name"inpackage.jsonto@your-username/retry-fetch-pro:npm publish --access public - Or publish directly:
npm publish
💖 Support the Project
If you find this package useful, consider sponsoring its ongoing development and maintenance: 👉 Sponsor @Piratha97 on GitHub Sponsors
📄 License
MIT © 2026
