npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

fetch-with-retry3

v1.1.0

Published

fetch-with-retry3 is a utility function built on top of the Axios library, designed to make HTTP(S) requests with automatic retry logic. When a request fails due to issues like network errors, timeouts, or specific status codes, it retries the operation a

Readme

fetch-with-retry3

npm version TypeScript License: MIT

A robust, TypeScript-first HTTP client built on top of Axios with automatic retry logic and proxy support. Designed to handle unreliable network conditions with configurable retry strategies, timeouts, and comprehensive error handling.

✨ Features

  • 🔄 Automatic Retry Logic: Configurable retry attempts with exponential backoff
  • 🌐 Proxy Support: HTTP(S) and SOCKS4/5 proxy support with authentication
  • Modern AbortController: Uses AbortController instead of deprecated CancelToken
  • 🛡️ 100% TypeScript: Full type safety with comprehensive type definitions
  • 🎯 Zero Configuration: Works out of the box with sensible defaults
  • 📊 Request/Response Logging: Built-in error logging for debugging
  • 🧪 Thoroughly Tested: Comprehensive test suite with 95%+ coverage

📦 Installation

npm install fetch-with-retry3
# or
yarn add fetch-with-retry3
# or
pnpm add fetch-with-retry3

🚀 Quick Start

Basic Usage

import { fetchWithRetry } from 'fetch-with-retry3';

// Simple GET request
const response = await fetchWithRetry('https://api.example.com/users');

if (response.ok) {
  console.log('Success:', response.data);
} else {
  console.error('Error:', response.error);
}

With Custom Configuration

import { fetchWithRetry } from 'fetch-with-retry3';

const response = await fetchWithRetry(
  'https://api.example.com/data',
  {
    method: 'POST',
    data: { name: 'John Doe', email: '[email protected]' },
    headers: { 'Content-Type': 'application/json' }
  },
  5,      // 5 retry attempts
  2000,   // 2 second delay between retries
  30000   // 30 second timeout
);

📖 API Reference

fetchWithRetry

function fetchWithRetry<T = any, D = any>(
  url: string,
  options?: AxiosRequestConfig<D>,
  attempts?: number,
  delay?: number,
  timeout?: number
): Promise<AxiosResponse<T> & { ok: boolean; error?: Error }>

Parameters

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | url | string | - | The request URL | | options | AxiosRequestConfig<D> | {} | Axios request configuration | | attempts | number | 3 | Number of retry attempts | | delay | number | 1500 | Delay between retries (ms) | | timeout | number | 30000 | Request timeout (ms) |

Returns

Returns a Promise that resolves to an enhanced AxiosResponse with:

  • ok: Boolean indicating if the request was successful (2xx status)
  • error: Error object if the request failed after all retries

fetchWithProxy

function fetchWithProxy<T = any, D = any>(
  url: string,
  options?: AxiosRequestConfig<D>,
  proxies?: Proxy[],
  attempts?: number,
  delay?: number,
  timeout?: number
): Promise<AxiosResponse<T> & { ok: boolean; error?: Error }>

Proxy Configuration

type Proxy = {
  host: string;
  port: number;
  protocol: PROXY_PROTOCOL;
  username?: string;
  password?: string;
};

enum PROXY_PROTOCOL {
  http = "http",
  https = "https",
  socks4 = "socks4",
  socks5 = "socks5"
}

📝 Examples

GET Request

import { fetchWithRetry } from 'fetch-with-retry3';

const getUserData = async (userId: string) => {
  const response = await fetchWithRetry(`https://api.example.com/users/${userId}`, {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer your-token-here'
    }
  });

  if (response.ok) {
    return response.data;
  } else {
    throw new Error(`Failed to fetch user: ${response.error?.message}`);
  }
};

POST Request with Retry

import { fetchWithRetry } from 'fetch-with-retry3';

const createUser = async (userData: any) => {
  const response = await fetchWithRetry(
    'https://api.example.com/users',
    {
      method: 'POST',
      data: userData,
      headers: { 'Content-Type': 'application/json' }
    },
    3,    // Retry up to 3 times
    1000  // Wait 1 second between retries
  );

  return response;
};

Using Proxies

import { fetchWithProxy, PROXY_PROTOCOL } from 'fetch-with-retry3';

const proxies = [
  {
    host: 'proxy1.example.com',
    port: 8080,
    protocol: PROXY_PROTOCOL.http,
    username: 'user1',
    password: 'pass1'
  },
  {
    host: 'proxy2.example.com',
    port: 1080,
    protocol: PROXY_PROTOCOL.socks5,
    username: 'user2',
    password: 'pass2'
  }
];

const response = await fetchWithProxy(
  'https://api.example.com/data',
  { method: 'GET' },
  proxies,
  3,    // attempts
  1500, // delay
  30000 // timeout
);

With AbortController

import { fetchWithRetry } from 'fetch-with-retry3';

const controller = new AbortController();

// Cancel request after 5 seconds
setTimeout(() => controller.abort(), 5000);

const response = await fetchWithRetry(
  'https://api.example.com/slow-endpoint',
  {
    method: 'GET',
    signal: controller.signal
  }
);

🔧 Error Handling

The library automatically handles various error scenarios:

  • Network errors: Automatic retry with configurable delay
  • Timeout errors: Uses AbortController for clean cancellation
  • HTTP errors: 4xx and 5xx status codes (404s return ok: false)
  • Proxy failures: Tries next proxy in the list
const response = await fetchWithRetry('https://api.example.com/data');

if (!response.ok) {
  if (response.status === 404) {
    console.log('Resource not found');
  } else if (response.error) {
    console.error('Request failed:', response.error.message);
  }
}

🧪 Testing

Run the test suite:

npm test

Run tests with coverage:

npm run test:coverage

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📊 Package Information

🔗 Related

Built with: