Skip to footer content
NODE HELP

Axios Retry NPM (How It Works For Developers)

Web applications frequently rely on several external services, APIs, and resources to provide users with dynamic information and functionality in today's fast-paced digital environment. However, occasionally, these dependencies can cause problems such as timeouts, network error outages, and temporary faults, which can halt important processes like PDF creation. To assure the reliability of their applications and handle such situations gracefully, developers have responded by implementing robust retry mechanisms.

Axios Retry is a robust npm library that simplifies building custom retry logic for failed HTTP requests. Built on top of Axios, a popular HTTP client for Node.js, developers can design robust and fault-tolerant PDF generation workflows by combining Axios Retry, an Axios plugin with IronPDF—a feature-rich library for creating PDF documents in Node.js applications.

This post will discuss the benefits of combining Axios Retry with IronPDF and show how these two tools work together to enhance Node.js applications' PDF generation capabilities. By integrating Axios Retry's resilient retry mechanisms with IronPDF's sophisticated PDF creation functionalities, developers can ensure dependable execution of PDF generation tasks, even amidst temporary network disruptions, idempotent request failures, or external service outages.

Retry Logic

For Axios requests, Axios-retry streamlines the implementation of retry logic. Based on programmable parameters, such as HTTP status codes or specific error types, it automatically retries unsuccessful requests.

Custom Retry Policies

To regulate the frequency and method of retrying requests, developers can create custom retry policies. This involves defining the maximum number of retries, the intervals between retries, and circumstances that warrant retries.

Exponential Backoff

Axios-retry facilitates the popular retry strategy known as exponential backoff, which increases the interval between retries incrementally. This helps improve the odds of success for failed requests and avoids overwhelming the server with repetitive queries.

Retryable Errors

Developers can specify which error types or HTTP status codes should trigger a retry. This allows precise control over which errors are treated as permanent failures versus those that should be retried.

Retry Interceptors

Axios-retry provides interceptors that allow developers to modify retry behavior on a per-request basis. This includes handling retryable errors, tracking retry attempts, and adjusting retry delays.

Global Configuration

With axios-retry, developers can set up retry policies globally for all Axios requests, ensuring consistent retry behavior throughout the application's request lifecycle.

Create and Configure Axios Retry

The following sample code demonstrates how to utilize Axios Retry in a Node.js application, with each step explained briefly:

Import Dependencies

To add retry capabilities to Axios, we first import the axios-retry library along with the axios library for making HTTP requests.

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

Create Axios Instance

We use axios.create() to create an Axios instance, allowing us to customize Axios's behavior for specific use cases.
To configure Axios Retry, we call axiosRetry() and pass in the Axios instance along with an options object. Parameters in the options object include the retry count (retries), the retry delay (retryDelay), and the retry condition (retryCondition).

// Create an Axios instance
const axiosInstance = axios.create();
// Create an Axios instance
const axiosInstance = axios.create();
JAVASCRIPT

Configuring Retries

Specifies the number of retry attempts. retryDelay uses an exponential backoff strategy, which increases delay exponentially with each attempt. In this example, we set it to 3 retries.

axiosRetry(axiosInstance, {
    retries: 3, // Number of retry attempts
    retryDelay: axiosRetry.exponentialDelay, // Exponential delay function
    retryCondition: (error) => {
        // Retry on network errors or status code 429 (rate limit)
        return axiosRetry.isNetworkOrIdempotentRequestError(error) || error.response.status === 429;
    }
});
axiosRetry(axiosInstance, {
    retries: 3, // Number of retry attempts
    retryDelay: axiosRetry.exponentialDelay, // Exponential delay function
    retryCondition: (error) => {
        // Retry on network errors or status code 429 (rate limit)
        return axiosRetry.isNetworkOrIdempotentRequestError(error) || error.response.status === 429;
    }
});
JAVASCRIPT

Getting Started with IronPDF

What is IronPDF?

IronPDF Node.js Toolkit is a widely used library for creating, editing, and rendering PDF documents within applications. It offers multiple ways to work with PDFs, including inserting text, images, and shapes into documents, extracting content from existing PDFs, and converting HTML to PDFs.

Key benefits of IronPDF include its ease of use, efficiency, and high speed—allowing developers to produce high-quality PDFs rapidly.

Some advantages of IronPDF:

  • Converting HTML, images, and raw data into PDFs.
  • Text and image extraction from PDFs.
  • Adding headers, footers, and watermarks to PDFs.
  • Encrypting and password-protecting PDFs.
  • Filling out and electronically signing documents.

Install Libraries

Install the required libraries and configure Axios for retry capabilities as the first step in integrating Axios Retry with IronPDF for PDF generation in a Node.js application. Here's a step-by-step guide:

npm install axios 
npm install axios-retry 
npm install ironpdf
npm install axios 
npm install axios-retry 
npm install ironpdf
SHELL

Using Axios Retry with IronPDF for URL-to-PDF Conversion

Consider the scenario where dynamic HTML content from an external API IronPDF URL to PDF Example is used by a Node.js app to generate PDF reports. The app should gracefully handle potential network errors or rate limiting to ensure tasks involving PDF creation are completed successfully.

Set up an Axios instance with Axios Retry configurations:

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

// Create Axios instance
const axiosInstance = axios.create();

// Configure Axios Retry
axiosRetry(axiosInstance, {
    retries: 3,
    retryDelay: axiosRetry.exponentialDelay,
    retryCondition: (error) => {
        // Retry on network errors or status code 429 (rate limit)
        return axiosRetry.isNetworkOrIdempotentRequestError(error) || error.response.status === 429;
    }
});
const axios = require('axios');
const axiosRetry = require('axios-retry');

// Create Axios instance
const axiosInstance = axios.create();

// Configure Axios Retry
axiosRetry(axiosInstance, {
    retries: 3,
    retryDelay: axiosRetry.exponentialDelay,
    retryCondition: (error) => {
        // Retry on network errors or status code 429 (rate limit)
        return axiosRetry.isNetworkOrIdempotentRequestError(error) || error.response.status === 429;
    }
});
JAVASCRIPT

For generating a PDF document from HTML content, initialize IronPDF with your license key:

const IronPdf = require("@ironsoftware/ironpdf");
var config = IronPdf.IronPdfGlobalConfig;
config.setConfig({ licenseKey: '' });
const document = IronPdf.PdfDocument;
const IronPdf = require("@ironsoftware/ironpdf");
var config = IronPdf.IronPdfGlobalConfig;
config.setConfig({ licenseKey: '' });
const document = IronPdf.PdfDocument;
JAVASCRIPT

Now, use the configured Axios instance to retrieve HTML content from an external API and generate a PDF document with IronPDF:

(async () => {
    try {
        // Fetch HTML content using Axios
        const response = await axiosInstance.get('https://api.example.com/data');
        const htmlContent = response.data;

        // Generate PDF from HTML content using IronPDF
        const pdf = await document.fromHtml(htmlContent);
        await pdf.saveAs("output.pdf");

    } catch (error) {
        console.error('Error fetching HTML content:', error.message);
    }
})();
(async () => {
    try {
        // Fetch HTML content using Axios
        const response = await axiosInstance.get('https://api.example.com/data');
        const htmlContent = response.data;

        // Generate PDF from HTML content using IronPDF
        const pdf = await document.fromHtml(htmlContent);
        await pdf.saveAs("output.pdf");

    } catch (error) {
        console.error('Error fetching HTML content:', error.message);
    }
})();
JAVASCRIPT

Customize the retry options, PDF creation, and error handling to fit your application's requirements. Thoroughly test the integration to ensure reliability and functionality.

By combining Axios Retry with IronPDF using these techniques, you can handle HTTP request retries and generate PDF documents reliably in your Node.js app. This combination offers resilient workflows for PDF production that withstand network errors and service outages.

Here is an output example from the above process:

Axios Retry NPM (How It Works For Developers): Figure 1 - URL to PDF Output with retried requests

Conclusion

To sum up, combining Axios Retry and IronPDF in Node.js applications provides a robust, reliable method for handling HTTP request retries and generating PDF documents. By leveraging Axios Retry's capabilities, developers can enhance the resilience and stability of their HTTP request processes, ensuring graceful handling of temporary network issues, server errors, or rate-limiting conditions.

Overall, Axios Retry and IronPDF together offer a powerful toolkit for building scalable, durable Node.js apps requiring consistent PDF generation and HTTP request handling. By implementing these libraries, developers can mitigate the effects of temporary faults and network disruptions, ensuring the regular delivery of high-quality PDF documents and thereby improving the reliability and user experience of their applications.

IronPDF's package includes a lifetime license at a competitive price. It's available for as low as $749, providing excellent value. License holders receive 24/7 online engineering support. For more details, visit the IronPDF Licensing Page. Explore more about Iron Software's products at the Iron Software Product Overview.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity and problem-solving.

At Iron Software, Darrius enjoys creating new things and simplifying complex concepts to make them more understandable. As one of our resident developers, he has also volunteered to teach students, sharing his expertise with the next generation.

For Darrius, his work is fulfilling because it is valued and has a real impact.

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?