Convert Figma logo to code with AI

softonic logoaxios-retry

Axios plugin that intercepts failed requests and retries them whenever possible

2,014
175
2,014
58

Top Related Projects

109,037

Promise based HTTP client for the browser and node.js

Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.

14,921

🌐 Human-friendly and powerful HTTP request library for Node.js

25,538

🏊🏾 Simplified HTTP request client.

A light-weight module that brings the Fetch API to Node.js

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.

Quick Overview

Axios-retry is an Axios plugin that intercepts failed requests and retries them whenever possible. It provides automatic request retrying functionality for Axios, a popular HTTP client for JavaScript. This library is particularly useful for handling network issues or temporary server errors.

Pros

  • Easy integration with existing Axios setups
  • Configurable retry behavior (e.g., number of retries, delay between retries)
  • Supports both CommonJS and ES6 module systems
  • Lightweight and has minimal dependencies

Cons

  • Limited to Axios library, not usable with other HTTP clients
  • May increase overall request time due to retries
  • Potential for unintended consequences if not configured properly (e.g., excessive retries)

Code Examples

  1. Basic usage:
import axios from 'axios';
import axiosRetry from 'axios-retry';

const client = axios.create();
axiosRetry(client, { retries: 3 });

client.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
  1. Custom retry condition:
import axios from 'axios';
import axiosRetry from 'axios-retry';

const client = axios.create();
axiosRetry(client, {
  retries: 3,
  retryCondition: (error) => {
    return error.response.status === 503;
  }
});

client.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
  1. Exponential backoff:
import axios from 'axios';
import axiosRetry from 'axios-retry';

const client = axios.create();
axiosRetry(client, {
  retries: 3,
  retryDelay: axiosRetry.exponentialDelay
});

client.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Getting Started

To use axios-retry in your project:

  1. Install the package:

    npm install axios-retry
    
  2. Import and use in your code:

    import axios from 'axios';
    import axiosRetry from 'axios-retry';
    
    const client = axios.create();
    axiosRetry(client, { retries: 3 });
    
    // Use the client for making requests
    client.get('https://api.example.com/data')
      .then(response => console.log(response.data))
      .catch(error => console.error(error));
    

This setup will automatically retry failed requests up to 3 times. You can customize the retry behavior by modifying the options passed to axiosRetry.

Competitor Comparisons

109,037

Promise based HTTP client for the browser and node.js

Pros of axios

  • More comprehensive HTTP client with broader feature set
  • Larger community and ecosystem, leading to better support and more resources
  • Built-in request and response interceptors for global modifications

Cons of axios

  • Larger package size, which may impact bundle size in client-side applications
  • No built-in retry functionality, requiring additional configuration or plugins

Code Comparison

axios:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

axios-retry:

import axios from 'axios';
import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Key Differences

  • axios-retry is a plugin for axios, focusing specifically on request retry functionality
  • axios-retry provides automatic request retrying with configurable options, while axios requires manual implementation or additional plugins for retry logic
  • axios-retry is lightweight and focused, making it ideal for projects that only need retry functionality
  • axios offers a more complete HTTP client solution with additional features beyond retrying requests

Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.

Pros of superagent

  • More comprehensive HTTP client with a wider range of features
  • Supports both Node.js and browser environments
  • Chainable API for more readable and expressive code

Cons of superagent

  • Larger package size due to more features
  • Steeper learning curve for developers familiar with simpler libraries
  • May be overkill for projects that only need basic HTTP functionality

Code Comparison

superagent:

superagent
  .post('/api/pet')
  .send({ name: 'Manny', species: 'cat' })
  .set('X-API-Key', 'foobar')
  .set('Accept', 'application/json')
  .end((err, res) => {
    // Callback
  });

axios-retry:

axiosRetry(axios, { retries: 3 });

axios.get('http://example.com/api')
  .then(response => {
    // Handle response
  })
  .catch(error => {
    // Handle error
  });

Key Differences

  • superagent is a full-featured HTTP client, while axios-retry is a plugin for axios focused on retry functionality
  • superagent offers a more expressive API with method chaining, whereas axios-retry enhances axios with automatic retries
  • axios-retry is specifically designed for handling network failures and retries, while superagent provides a broader set of features for HTTP requests

Both libraries have their strengths, and the choice between them depends on the specific needs of your project. superagent is better suited for complex HTTP interactions, while axios-retry is ideal for projects that require robust retry mechanisms with axios.

14,921

🌐 Human-friendly and powerful HTTP request library for Node.js

Pros of got

  • More comprehensive HTTP client with built-in features like pagination, rate limiting, and caching
  • Supports both Promise and stream interfaces for flexible usage
  • Actively maintained with frequent updates and improvements

Cons of got

  • Larger package size and potentially higher learning curve due to more features
  • May be overkill for simple use cases where only retry functionality is needed
  • Not a drop-in replacement for axios, requiring code changes when migrating

Code comparison

axios-retry:

import axios from 'axios';
import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });
axios.get('https://example.com');

got:

import got from 'got';

const response = await got('https://example.com', {
  retry: { limit: 3 }
});

Key differences

  • axios-retry is a plugin for axios, while got is a standalone HTTP client
  • got offers more built-in features beyond retrying, such as automatic retrying on certain HTTP codes
  • axios-retry allows for more granular control over retry behavior, while got provides a simpler API for basic retry functionality

Use cases

  • axios-retry: Best for projects already using axios or requiring specific retry configurations
  • got: Ideal for new projects or those needing a full-featured HTTP client with built-in retry capabilities

Both libraries are well-maintained and popular choices for handling HTTP requests with retry functionality in Node.js applications.

25,538

🏊🏾 Simplified HTTP request client.

Pros of request

  • Mature and widely adopted library with extensive documentation
  • Supports both promises and callbacks for flexibility
  • Offers a simpler API for basic HTTP requests

Cons of request

  • No longer actively maintained (deprecated)
  • Lacks built-in retry functionality
  • Larger bundle size compared to axios-retry

Code Comparison

request:

const request = require('request');

request('https://api.example.com', (error, response, body) => {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
});

axios-retry:

const axios = require('axios');
const axiosRetry = require('axios-retry');

axiosRetry(axios, { retries: 3 });

axios.get('https://api.example.com')
  .then(response => console.log(response.data));

Key Differences

  • axios-retry is specifically designed for retrying failed requests, while request requires additional logic for retries
  • request offers more low-level control over HTTP requests, while axios-retry focuses on enhancing axios with retry capabilities
  • axios-retry integrates seamlessly with axios, providing a more modern and promise-based approach to HTTP requests

Use Cases

  • Choose request for legacy projects or when extensive customization is needed
  • Opt for axios-retry when working with axios and requiring automatic retry functionality for failed requests

A light-weight module that brings the Fetch API to Node.js

Pros of node-fetch

  • Lightweight and simple API, closely mimicking the browser's Fetch API
  • Built-in support for streaming responses
  • Native Promise-based interface

Cons of node-fetch

  • Lacks built-in retry functionality
  • No automatic request transformation or response handling

Code Comparison

node-fetch:

import fetch from 'node-fetch';

const response = await fetch('https://api.example.com/data');
const data = await response.json();

axios-retry:

import axios from 'axios';
import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });
const response = await axios.get('https://api.example.com/data');

Key Differences

  1. Retry Mechanism: axios-retry provides built-in retry functionality, while node-fetch requires manual implementation.

  2. API Style: node-fetch closely resembles the browser's Fetch API, whereas axios-retry extends Axios with additional features.

  3. Ecosystem: node-fetch is more focused on providing a Fetch-like API for Node.js, while axios-retry is part of the broader Axios ecosystem with additional plugins and extensions.

  4. Configurability: axios-retry offers more options for configuring retry behavior out of the box, such as retry count, delay, and error handling.

  5. Learning Curve: node-fetch may be easier to adopt for developers familiar with the Fetch API, while axios-retry requires understanding of both Axios and its retry mechanism.

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.

Pros of Octokit.js

  • Comprehensive GitHub API client with built-in authentication and pagination support
  • Provides TypeScript typings for improved developer experience
  • Offers plugins for extended functionality and customization

Cons of Octokit.js

  • Larger package size due to its comprehensive feature set
  • Steeper learning curve for developers unfamiliar with GitHub's API structure
  • Limited to GitHub-specific operations, not a general-purpose HTTP client

Code Comparison

Octokit.js:

const octokit = new Octokit({ auth: 'token' });
const { data } = await octokit.rest.repos.get({
  owner: 'octokit',
  repo: 'octokit.js'
});

Axios-retry:

const axiosRetry = require('axios-retry');
const axios = axiosRetry(require('axios'));
axios.get('https://api.github.com/repos/octokit/octokit.js')
  .then(response => console.log(response.data));

Key Differences

  • Octokit.js is tailored for GitHub API interactions, while Axios-retry is a general-purpose HTTP client with retry functionality
  • Axios-retry focuses on automatic request retrying, which is not a core feature of Octokit.js
  • Octokit.js provides a more declarative API for GitHub-specific operations, whereas Axios-retry offers a lower-level approach to HTTP requests

Use Cases

  • Choose Octokit.js for projects heavily integrated with GitHub's API
  • Opt for Axios-retry when working with various APIs and requiring robust retry mechanisms

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

axios-retry

Node.js CI

Axios plugin that intercepts failed requests and retries them whenever possible.

Installation

npm install axios-retry

Usage

// CommonJS
// const axiosRetry = require('axios-retry').default;

// ES6
import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });

axios.get('http://example.com/test') // The first request fails and the second returns 'ok'
  .then(result => {
    result.data; // 'ok'
  });

// No retry delay
axiosRetry(axios, { retryDelay: axiosRetry.noDelay });

// Exponential back-off retry delay between requests
axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay });

// Linear retry delay between requests; note the different function signature
axiosRetry(axios, { retryDelay: axiosRetry.linearDelay() });

// Custom retry delay
axiosRetry(axios, { retryDelay: (retryCount) => {
  return retryCount * 1000;
}});

// Exponential back-off retry delay with a custom initial delay
axiosRetry(axios, { retryDelay: (retryCount, error) => {
  return axiosRetry.exponentialDelay(retryCount, error, 1000);
}});

// Works with custom axios instances
const client = axios.create({ baseURL: 'http://example.com' });
axiosRetry(client, { retries: 3 });

client.get('/test') // The first request fails and the second returns 'ok'
  .then(result => {
    result.data; // 'ok'
  });

// Allows request-specific configuration
client
  .get('/test', {
    'axios-retry': {
      retries: 0
    }
  })
  .catch(error => { // The first request fails
    error !== undefined
  });

Note: Unless shouldResetTimeout is set, the plugin interprets the request timeout as a global value, so it is not used for each retry but for the whole request lifecycle.

Options

NameTypeDefaultDescription
retriesNumber3The number of times to retry before failing. 1 = One retry after first failure
retryConditionFunctionisNetworkOrIdempotentRequestErrorA callback to further control if a request should be retried. By default, it retries if it is a network error or a 5xx error on an idempotent request (GET, HEAD, OPTIONS, PUT or DELETE).
shouldResetTimeoutBooleanfalseDefines if the timeout should be reset between retries
retryDelayFunctionfunction noDelay() { return 0; }A callback to further control the delay in milliseconds between retried requests. By default there is no delay between retries. Another option is exponentialDelay (Exponential Backoff) or linearDelay. The function is passed retryCount and error.
onRetryFunctionfunction onRetry(retryCount, error, requestConfig) { return; }A callback to notify when a retry is about to occur. Useful for tracing and you can any async process for example refresh a token on 401. By default nothing will occur. The function is passed retryCount, error, and requestConfig.
onMaxRetryTimesExceededFunctionfunction onMaxRetryTimesExceeded(error, retryCount) { return; }After all the retries are failed, this callback will be called with the last error before throwing the error.
validateResponseFunction | nullnullA callback to define whether a response should be resolved or rejected. If null is passed, it will fallback to the axios default (only 2xx status codes are resolved).

Retry-After Header

Note that axios-retry respects the Retry-After response header. If a response contains a Retry-After header, axios-retry will wait as long as the biggest value between the Retry-After header and the configured retryDelay option.

Testing

Clone the repository and execute:

npm test

Contribute

  1. Fork it: git clone https://github.com/softonic/axios-retry.git
  2. Create your feature branch: git checkout -b feature/my-new-feature
  3. Commit your changes: git commit -am 'Added some feature'
  4. Check the build: npm run build
  5. Push to the branch: git push origin my-new-feature
  6. Submit a pull request :D

NPM DownloadsLast 30 Days