In This Article

Back to blog

Mastering Axios Retry Plugin: Handling Failed Requests with Examples

Tutorials

Vilius Dumcius

Last updated - ‐ 5 min read

Key Takeaways

  • Axios Retry adds automatic retry logic to failed HTTP requests, making apps more reliable during network hiccups or server issues.

  • You can fully customize when and how Axios retries: setting retry counts, using exponential backoff, or targeting specific status codes and request types.

  • It’s especially helpful in web scraping, where high request volume increases the chance of errors.

Axios Retry is a plugin that intercepts failed HTTP requests and retries them based on your configuration. It’s commonly used in web development and automation scenarios where failed HTTP requests are frequent.

Many apps that rely on external servers use retries to handle network errors. Without retries, some features might fail when a request breaks.

Axios Retry works seamlessly with async and promise-based Axios requests, allowing easy integration into modern JavaScript workflows.

What Are the Main Features of Axios?

Axios doesn’t include built-in retry logic for failed requests. When a request fails, Axios simply rejects the promise and throws an error.

You can use JavaScript’s built-in try…catch to handle Axios errors, but you’d need to code the retry logic yourself manually. The Axios Retry library automates the retry process, saving you from writing custom retry logic manually.

One of the main selling points for Axios Retry is the number of configuration options for retrying requests. You can set up automatic retries based on HTTP error codes, the number of retries, a backoff delay, and customize the logic in many other ways.

In web scraping, for example, the bot has to send requests to thousands, if not hundreds of thousands of URLs per day. Network error issues will be frequent, whether it’s due to the client or the server.

Using Axios with the Axios Retry plugin can make web scraping more efficient. Network errors that meet the retry conditions will be retried automatically, reducing failed requests while the scraper continues processing other URLs.

Setup

First, make sure you have Node.js installed on your device. If you don’t, you can use the official instructions to download and install it.

If you already have NVM installed, you can just install the latest Node.js version:

nvm install 22.20

Create a new project folder, initialize it with npm init, and create an index.js file. If you prefer the terminal:

mkdir axios_retry
cd axios_retry
npm init
touch index\.js

After that, install Axios and the Axios-Retry plugin with the following terminal command. Axios will be used for making web requests, while Axios-Retry will be used to help you with automatic retries on network failure:

npm i axios axios-retry --save

Here’s an example package.json file:

{
  "name": "axios-retry-requests",
  "version": "1.0.0",
  "description": "Use axios retry requests to make your app more resilient to network errors",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^1.12.2",
    "axios-retry": "^4.5.0"
  }
}

Ready to get started?
Register now

Basic Retry Example

We can then set up a basic retry system:

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


axiosRetry(axios, {
  retries: 3,
  retryCondition: axiosRetry.isRetryableError, 
});

axios.get('https://quotes.toscrape.com')
  .then(response => console.log(response.data))
  .catch(error => console.error('Failed after retries:', error));

Copy-paste the code and run node index.js in your (IDE) terminal.

The axiosRetry function attaches retry configurations to an existing Axios instance using key-value pairs.

The retries property sets the number of retry attempts, and retryCondition determines when to retry based on network errors.

If a network error occurs, Axios will retry the request up to three times before failing. The axios.get method sends a GET request, logging the response if successful or an error message if all retries fail. Request Aborted errors, caused by user cancellations, are intentionally excluded from retries.

Axios Requests Retry With Backoff

We can also include an exponential backoff strategy. Exponential backoff continually increases the delay before sending the next retry. These strategies are helpful if a server is temporarily overloaded:

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

// Configure axios-retry with exponential backoff
axiosRetry(axios, {
  retries: 3,
  retryDelay: axiosRetry.exponentialDelay,
  retryCondition: axiosRetry.isRetryableError,
});

axios.get('https://quotes.toscrape.com')
  .then(response => console.log(response.data))
  .catch(error => console.error('Failed after retries with exponential backoff:', error));

We only adjusted our axiosRetry object to include a new property retryDelay. We’re using the default Axios requests retry backoff delay, which is 2^n * 100 ms, where n is the number of retries initiated.

If you need a custom backoff strategy, the value axiosRetry.exponentialDelay can be modified to refer to a custom function:

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

// Custom exponential backoff function
function customExponentialBackoff(retryNumber) {
  // Start with 200ms delay, double each retry
  return 100 * Math.pow(2, retryNumber);
}

// Configure axios-retry
axiosRetry(axios, {
  retries: 3,
  retryDelay: customExponentialBackoff, // Use custom backoff function
  retryCondition: axiosRetry.isRetryableError,
});

// Make a GET request
axios.get('https://quotes.toscrape.com')
  .then(response => console.log(response.data))
  .catch(error => console.error('Failed after retries with custom exponential backoff:', error));

Customizing Retry Conditions

Axios Retry also provides numerous ways to modify the retry conditions. We can modify the logic to only retry on specific error codes:

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

// Custom retry condition
axiosRetry(axios, {
  retries: 4,
  retryCondition: (error) => {
    return error.response ? error.response.status === 503 : false;
  },
});

axios.get('https://quotes.toscrape.com')
  .then(response => console.log(response.data))
  .catch(error => console.error('Failed after retries on 503:', error));

In the above example, we check if the status code of an error is equal to 503 (Temporarily Unavailable). If it is, we will continue retrying.

We can also modify the logic to only retry on specific HTTP methods:

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

// Configure axios-retry to apply only to POST requests
axiosRetry(axios, {
  retries: 3,
  shouldRetry: (config) => {
    return config.method === 'post';
  }
});

axios.post('https://quotes.toscrape.com', { data: 'example' })
  .then(response => console.log('Data submitted:', response.data))
  .catch(error => console.error('Failed after retries for POST:', error));

Conclusion

Axios Retry is an excellent plugin if you need a simple and intuitive way to retry failed requests automatically. It’s well-supported by the community, with plenty of examples and discussions available online.

Create Account
Share on
Article by IPRoyal
Meet our writers
Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

Related articles