axios-retry

repository·master·Indexed 24 days ago

https://github.com/softonic/axios-retry

An Axios plugin that intercepts failed requests and automatically retries them based on configurable conditions and delay strategies. It supports built-in delay strategies like exponential and linear back-off, respects the HTTP Retry-After header, and provides utility functions to determine if errors are retryable based on network status or request idempotency.

Tokens
1.5K
Snippets
2
Records
9
Agent score
34%

What's inside axios-retry

  1. How the Retry-After header is handled

    master
    The plugin respects the HTTP Retry-After response header. If a response includes this header, axios-retry will wait for the duration specified by the header, or the duration configured in retryDelay, whichever is larger.
  2. Use axios-retry with Axios

    master

    To enable retries, import axiosRetry and call it passing your axios instance and a configuration object. You can apply it to the global axios object or to specific custom instances created via axios.create().

    By default, it retries 3 times. You can also override retry settings for a specific request by passing an 'axios-retry' key in the request configuration.

  3. Configure axios-retry options

    master

    When calling axiosRetry(axios, options), you can provide the following configuration keys:

    NameTypeDefaultDescription
    retriesNumber3The number of times to retry before failing. 1 = One retry after first failure
    retryConditionFunctionisNetworkOrIdempotentRequestErrorA callback to control if a request should be retried. Default retries on network errors or 5xx errors on idempotent requests (GET, HEAD, OPTIONS, PUT, or DELETE).
    shouldResetTimeoutBooleanfalseIf true, the timeout is reset between retries. If false (default), the timeout applies to the entire request lifecycle.
    retryDelayFunctionfunction noDelay() { return 0; }Callback to control delay in ms. Receives retryCount and error.
    onRetryFunctionfunction onRetry(retryCount, error, requestConfig) { return; }Callback triggered before a retry occurs. Useful for tracing or refreshing tokens (e.g., on 401).
    onMaxRetryTimesExceededFunctionfunction onMaxRetryTimesExceeded(error, retryCount) { return; }Callback called after all retries fail, receiving the last error and the retry count.
    validateResponseFunction | nullnullCallback to define if a response should be resolved or rejected. If null, falls back to Axios default (2xx resolved).
  4. Install and use axios-retry

    master

    To enable automatic retries in your Axios requests, import the axiosRetry function and pass your Axios instance (or the global axios object) to it. You can optionally provide a configuration object to customize retry behavior.

    import axios from 'axios';
    import axiosRetry from 'axios-retry';
    
    const client = axios.create();
    
    axiosRetry(client, {
      retries: 3,
      retryDelay: (retryCount) => {
        return retryCount * 1000;
      },
      retryCondition: (error) => {
        return error.response?.status === 503;
      }
    });
    
    // Now this request will automatically retry up to 3 times on 503 errors
    await client.get('https://api.example.com/data');
  5. Configure retry delay strategies

    master

    The retryDelay option controls the wait time between retries. You can use built-in strategies or provide a custom function.

    Available built-in strategies:

    • axiosRetry.noDelay: No delay between retries.
    • axiosRetry.exponentialDelay: Exponential back-off.
    • axiosRetry.linearDelay(): Linear delay (note the function call syntax).

    Custom functions receive retryCount and error as arguments.

    // No retry delay
    axiosRetry(axios, { retryDelay: axiosRetry.noDelay });
    
    // Exponential back-off
    axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay });
    
    // Linear retry delay
    axiosRetry(axios, { retryDelay: axiosRetry.linearDelay() });
    
    // Custom retry delay
    axiosRetry(axios, { retryDelay: (retryCount) => {
      return retryCount * 1000;
    }});
    
    // Exponential back-off with custom initial delay
    axiosRetry(axios, { retryDelay: (retryCount, error) => {
      return axiosRetry.exponentialDelay(retryCount, error, 1000);
    }});
  6. Use linearDelay for retries

    master

    linearDelay provides a simple delay strategy where the wait time increases linearly based on the number of retries. It also respects the Retry-After header.

    import axiosRetry from 'axios-retry';
    
    // Retries with 500ms, 1000ms, 1500ms, etc.
    axiosRetry(axiosInstance, {
      retryDelay: axiosRetry.linearDelay(500)
    });
  7. Use exponentialDelay for retries

    master

    exponentialDelay is a pre-defined strategy that increases the wait time between retries exponentially, helping to avoid overwhelming a struggling server. It also respects the Retry-After header if present in the response and adds a small amount of jitter (0-20% of the delay) to prevent thundering herd problems.

    import axiosRetry from 'axios-retry';
    
    axiosRetry(axiosInstance, {
      retryDelay: (retryCount, error) => 
        axiosRetry.exponentialDelay(retryCount, error, 100)
    });
  8. Determine if an error is retryable

    master

    The axiosRetry object exports several utility functions to help you implement custom retryCondition logic based on the type of error encountered:

    • isNetworkError(error): Returns true if the error is a network error (no response received) and is not a cancellation or timeout error.
    • isRetryableError(error): Returns true if the error is not a timeout (ECONNABORTED) and the status code is either 429 (Too Many Requests) or in the 5xx range.
    • isSafeRequestError(error): Returns true if the error is retryable AND the HTTP method is get, head, or options.
    • isIdempotentRequestError(error): Returns true if the error is retryable AND the HTTP method is get, head, options, put, or delete.
    • isNetworkOrIdempotentRequestError(error): Returns true if the error is either a network error or an idempotent request error. This is the default condition used by the library.