idimetrix / fetch-with-retry

fetch-with-retry is an Axios-based utility that adds automatic retry logic to HTTP(S) requests. It retries failed requests due to network issues, timeouts, or specific status codes. Customizable with options for retry count, delay, backoff strategies, and error handling to improve reliability in unstable networks.

Repository from Github https://github.comidimetrix/fetch-with-retryRepository from Github https://github.comidimetrix/fetch-with-retry

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: 'john@example.com' },
    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:

About

fetch-with-retry is an Axios-based utility that adds automatic retry logic to HTTP(S) requests. It retries failed requests due to network issues, timeouts, or specific status codes. Customizable with options for retry count, delay, backoff strategies, and error handling to improve reliability in unstable networks.

License:Other


Languages

Language:TypeScript 100.0%