node-fetch-retry
node-fetch-retry is a lightweight wrapper library designed to enhance `node-fetch` with automatic retry capabilities. It enables developers to specify a fixed number of retry attempts for network requests, introduce a pause duration between retries, and execute a custom callback function before each attempt. The current stable version is 2.0.1. Its release cadence appears to be infrequent, with the last notable activity several years ago, suggesting it is in maintenance mode or effectively abandoned. This library differentiates itself by offering a straightforward, integrated retry mechanism directly within the `fetch` options, making it a simple choice for adding basic request resilience without complex configurations often found in more feature-rich alternatives. It's best suited for Node.js environments requiring basic retry logic for transient network failures.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require('node-fetch-retry')` in an ECMAScript Module (ESM) file (e.g., a file with `"type": "module"` in `package.json` or a `.mjs` extension).fixEither convert your project or the specific file to CommonJS (`.js` extension without `"type": "module"`) or use dynamic `import()` if `node-fetch-retry` supports it, or use an alternative library designed for ESM. -
TypeError: fetch is not a function
cause The `node-fetch-retry` package or its underlying `node-fetch` dependency was not correctly installed, resolved, or imported, leading to the `fetch` symbol being undefined.fixEnsure `node-fetch-retry` is correctly installed (`npm install node-fetch-retry`) and that the `require` statement is at the top level of your CommonJS module. Verify `node-fetch` is a compatible version with `node-fetch-retry` (likely `node-fetch@2`). -
ERR_REQUIRE_ESM
cause This error occurs when a CommonJS `require()` call attempts to load an ESM-only module. If `node-fetch-retry` has an internal dependency on `node-fetch` v3+, and your project uses `require`, this conflict can arise.fixDowngrade your direct or indirect `node-fetch` dependency to version 2 (e.g., `npm install node-fetch@2`) if `node-fetch-retry` doesn't explicitly state ESM compatibility. Alternatively, migrate your project to ESM if feasible, or use `import('node-fetch').then(...)` for dynamic loading if supported.
Warnings
- gotcha This library explicitly uses `require` in its examples and is likely a CommonJS module. If `node-fetch-retry` internally depends on `node-fetch` version 3 or higher, it might lead to `ERR_REQUIRE_ESM` errors when imported via `require` in a CommonJS context, as `node-fetch` v3+ is ESM-only. Users should ensure compatibility with `node-fetch` v2 if sticking to CommonJS.
- gotcha The library's GitHub repository shows the last commit was several years ago. This indicates that the project is not actively maintained, which could mean no new features, bug fixes, or security patches. Users should consider this for long-term project stability and security.
- gotcha Retrying non-idempotent HTTP methods (e.g., POST, PATCH) can lead to unintended side effects, such as duplicate resource creation or multiple charges, if the original request succeeded but the response was not received.
- gotcha This library provides basic retry capabilities (fixed retries, fixed pause). It lacks more advanced features like exponential backoff, configurable retry conditions based on HTTP status codes, or custom error handling for different failure types, which are common in more robust retry solutions.
Install
-
npm install node-fetch-retry -
yarn add node-fetch-retry -
pnpm add node-fetch-retry
Imports
- fetch
import fetch from 'node-fetch-retry';
const fetch = require('node-fetch-retry'); - fetch (async import)
import { fetch } from 'node-fetch-retry';const fetch = (...args) => import('node-fetch-retry').then(({ default: fetch }) => fetch(...args));
Quickstart
import * as process from 'process';
const fetch = require('node-fetch-retry');
async function fetchDataWithRetry() {
const targetUrl = 'https://httpstat.us/503?sleep=1000'; // Example URL that returns 503 after a delay
const retries = 3;
const pauseMs = 1000; // 1 second pause
console.log(`Attempting to fetch from ${targetUrl} with ${retries} retries...`);
try {
let opts = {
method: 'GET',
retry: retries,
pause: pauseMs,
callback: (retryAttempt) => {
console.log(`Retry attempt: ${retryAttempt}. Waiting ${pauseMs}ms before next attempt.`);
},
silent: false // Set to true to suppress pause messages
};
// Make the fetch request with retry options
const res = await fetch(targetUrl, opts);
if (res.ok) {
const text = await res.text();
console.log('Fetch successful after retries!');
console.log('Response:', text.substring(0, 100) + '...');
} else {
console.error(`Fetch failed after all retries with status: ${res.status}`);
}
} catch (error) {
console.error('An unhandled error occurred during fetch operation:', error.message);
}
}
fetchDataWithRetry();