Axios Request Retries

4.0.3 · active · verified Tue Apr 21

retry-axios is a library designed to automatically retry failed HTTP requests made using the Axios client library. It operates as an Axios interceptor, providing built-in exponential backoff and extensive configuration options for retry logic, including HTTP methods, status codes, retry delays, and jitter strategies. The current stable version is 4.0.3, released in April 2026. The package demonstrates a consistent release cadence, with major versions aligning with significant Node.js LTS updates. Key differentiators include its deep integration with Axios interceptors, allowing for global or instance-specific retry policies, and its flexible backoff algorithms (exponential, static, linear) to prevent thundering herd problems, making it suitable for robust client-side network operations in both Node.js and browser environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a custom Axios instance, configure `retry-axios` for it with specific retry policies (count, delay, status codes, backoff, jitter), and attach the retry interceptor. It includes an `onError` callback for logging and illustrates fetching data from an endpoint that might return a retryable status code, showcasing the retry mechanism in action.

import * as rax from 'retry-axios';
import axios, { AxiosInstance } from 'axios';

interface MyRaxConfig extends rax.RaxConfig {
  // Optionally extend raxConfig if needed
}

const myAxiosInstance: AxiosInstance = axios.create();

// Configure retry-axios for this specific instance
myAxiosInstance.defaults.raxConfig = {
  retry: 5, // Retry 5 times
  retryDelay: 500, // 500ms delay between retries
  statusCodesToRetry: [[429, 429], [500, 599]], // Only retry for Too Many Requests and 5xx errors
  backoffType: 'exponential', // Use exponential backoff
  jitter: 'full', // Add full jitter
  onError: (err) => {
    const cfg = rax.getConfig(err);
    if (cfg) {
      console.log(`Retry attempt #${cfg.currentRetryAttempt + 1} for URL: ${err.config?.url}`);
    }
  }
} as MyRaxConfig;

// Attach the retry interceptor to the custom instance
rax.attach(myAxiosInstance);

async function fetchData() {
  try {
    // Simulate an API call that might fail and need retries
    // Using httpbin.org for demonstration purposes.
    // In a real scenario, this might be a flaky backend endpoint.
    const response = await myAxiosInstance.get('https://httpbin.org/status/503');
    console.log('Successfully fetched data:', response.data);
  } catch (error: any) {
    if (error.response) {
      console.error(`Failed to fetch data after retries. Status: ${error.response.status}`);
    } else if (error.request) {
      console.error('Failed to fetch data after retries. No response received.');
    } else {
      console.error('Error during request setup:', error.message);
    }
  }
}

fetchData();

view raw JSON →