HTTP(S) Request Retry
request-retry is a Node.js library designed to automatically re-attempt HTTP(S) requests that fail due to transient network errors or specific HTTP status codes like 5xx and 429 (Too Many Requests). It functions as a wrapper, providing a drop-in replacement API for the underlying HTTP client, but with added configurable retry logic including `maxAttempts`, `retryDelay`, and a customizable `retryStrategy`. The current stable version, 8.0.0, marks a significant shift, migrating its core dependency from the unmaintained `request` library to the more actively developed `postman-request` fork, addressing security concerns and ensuring continued functionality. This package is crucial for building robust network clients that can gracefully handle temporary service disruptions, simplifying the implementation of resilient communication patterns by abstracting away common retry mechanisms.
Common errors
-
Error: Cannot find module 'postman-request'
cause The peer dependency 'postman-request' is not installed in the project.fixRun `npm install postman-request` to install the required HTTP client. -
TypeError: request is not a function
cause Attempting to use `requestretry` with an ES module `import` statement in a CommonJS-only Node.js environment, or an incorrect import style.fixUse CommonJS `require` syntax: `const request = require('requestretry');` Ensure your project's module type is correctly configured if using ESM. -
(node:xyz) DeprecationWarning: The request package has been deprecated.
cause This warning indicates that your project (or a transitive dependency) is still using an older version of `request-retry` (pre-v8.0.0) which relies on the deprecated `request` library.fixUpgrade `request-retry` to version 8.0.0 or higher: `npm install requestretry@latest`. Also, ensure `postman-request` is installed as a peer dependency.
Warnings
- breaking Version 8.0.0 replaced the deprecated `request` library with `postman-request`. This is a breaking change in its underlying dependency, though the API surface aims to remain compatible. Users must explicitly install `postman-request` as a peer dependency.
- gotcha The original `request` library, on which older versions of `request-retry` were based, is deprecated and no longer maintained. While v8.0.0 migrates to `postman-request`, users should be aware that `postman-request` is a fork and may have subtle differences or its own future maintenance considerations.
- gotcha `request-retry` expects `postman-request` as a peer dependency. If `postman-request` is not installed, the library will fail with a module not found error, as it cannot function without its underlying HTTP client.
Install
-
npm install requestretry -
yarn add requestretry -
pnpm add requestretry
Imports
- request
import request from 'requestretry';
const request = require('requestretry'); - RetryStrategies
import { RetryStrategies } from 'requestretry';const request = require('requestretry'); const strategy = request.RetryStrategies.HTTPOrNetworkError; - request (Promise-based usage)
import requestPromise from 'requestretry/promise';
const request = require('requestretry'); request({ /* options */ }).then(/* ... */);
Quickstart
// First, ensure you have the necessary peer dependency installed:
// npm install requestretry postman-request
const request = require('requestretry');
async function makeRetriedRequest() {
console.log('Initiating retriable HTTP request...');
try {
const response = await request({
url: 'https://httpstat.us/503', // An endpoint that reliably returns a 503 (Service Unavailable)
json: true, // Parse response body as JSON
maxAttempts: 3, // Configure up to 3 attempts
retryDelay: 1000, // Wait 1 second between retries
retryStrategy: request.RetryStrategies.HTTPOrNetworkError, // Retry on 5xx status codes or network errors
fullResponse: true // Resolve the promise with the full response object, including headers and status
});
console.log(`\nRequest successfully completed after ${response.attempts} attempts.`);
console.log(`HTTP Status Code: ${response.statusCode}`);
console.log(`Response Body: ${JSON.stringify(response.body, null, 2)}`);
} catch (error) {
console.error(`\nRequest failed after all attempts. Error: ${error.message}`);
if (error.attempts) {
console.error(`Total attempts made: ${error.attempts}`);
}
}
}
makeRetriedRequest();