Home > Software engineering >  is it possible to create a delay between each page build? (Next.js ISR)
is it possible to create a delay between each page build? (Next.js ISR)

Time:12-14

I am working on some project that I need to use ISR on, the pages critical info come from a third-party API, the problem is that this API allows only a maximum of 15 requests per second while the pages I need to be generated are hundreds and it needs hundreds of requests at build time, (by the fetching code ran inside getStaticProps()), so this obviously exceeds the limit of the APIs allowed requests per second,

How can I possibly solve that?? Is there any configuration for this matter that I don't know of or something to create a time gap between each page build?

Btw, I already tried making a delay before an API request happens using promises and timeout but that just doesn't work for some reason, would be glad if there is someone explained...

CodePudding user response:

Try this

const delay = 1000; // 1 second

export async function getStaticPaths() {
  // Get the list of pages to generate
  const pages = getPagesList();

  // Loop through the pages, adding a delay before building each one
  for (const page of pages) {
    await new Promise((resolve) => setTimeout(resolve, delay));
    await getStaticPropsForPage(page);
  }

  // Return the list of paths to generate
  return { paths, fallback: false };
}

CodePudding user response:

Yes, it is possible to create a delay between each page build in Next.js using server-side rendering (SSR). One way to do this is to use the setTimeout() function to add a delay before making the API request in the getStaticProps() method. Here is an example:

import fetch from 'node-fetch';

export async function getStaticProps() {
  await new Promise((resolve) => setTimeout(resolve, 1000)); // delay for 1 second

  const res = await fetch('https://third-party-api.com/data');
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

In this example, the getStaticProps() method waits for 1 second before making the API request using fetch(). This will add a delay of 1 second between each page build, which should help to prevent exceeding the API's request limit.

You can adjust the delay to a value that works for your specific use case. Keep in mind that adding too long of a delay may slow down the build process, so it's important to find a balance that works for your needs.

  • Related