Difficulty with deploying Next.js to Vercel due to restrictions on rate limits when utilizing getStaticProps()

In my Next.js project connected to Apollo, I have around 50 static URLs fetching data using getStaticProps(). The performance is great, and I enjoy how the pages load. However, a problem arises when Vercel builds the static versions of these pages during deployment - I tend to hit the rate limits for the API after about 40 pages are built. Since I cannot control these rate limits, I'm looking for a way to throttle my data calls within each getStaticProps to stagger them at build time. My current getStaticProps function on each page looks something like this:

export async function getStaticProps() {
  const apolloClient = initializeApollo()

  await apolloClient.query({
    query: XXXXXXX,
    variables: {handle: "XXXXXXX"}
  })

  return {
    props: {
      initialApolloState: apolloClient.cache.extract(),
    },
    revalidate: 1,
  }
}

Everything was running smoothly until I had more pages and started hitting the rate limit issue.

Answer №1

During the production build, I successfully managed to slow down my requests by 100ms using a setTimeout function wrapped inside a promise. This approach worked perfectly for me.

const delayRequest = (milliseconds, apolloClient) => {
return (
    new Promise(function(resolve, reject){
        setTimeout(() => {
            const request = apolloClient.query({
                query: XXXXXX,
                variables: {handle: "XXXXXX"}
            });
            resolve(request);
        }, milliseconds)
    });
)

};

export async function getStaticProps() { const apolloClient = initializeApollo()

await delayRequest(200, apolloClient)

return {
  props: {
    initialApolloState: apolloClient.cache.extract(),
  },
  revalidate: 1,
}

}

Answer №2

By default, NextJS tends to engage in multithreading during the build process, leading to multiple simultaneous HTTP requests that may overwhelm the server. The specifics of this default configuration and its implications on the build server are unknown to me.

To mitigate this, you can make adjustments in your next.config.js file to ensure a single-threaded approach when handling getStaticProps and getStaticPaths requests:

    ...
    experimental: {
        workerThreads: false,
        cpus: 1
    },
    ...

You can refer to this link for more insights on this configuration:

In my personal experience, adopting this method has proven effective in reducing rate limit issues with the content server.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

What is the mechanism behind the jQuery ready function that enables its first parameter to transform into a jQuery object?

While browsing today, I came across this interesting code snippet: jQuery(document).ready(function($$){ console.log($$); }); It seems that $$ is recognized as the jQuery object itself. Typically, to achieve this, we would need to pass the jQuery varia ...

Filter your DataTables columns by searching for text within a specific range

Below is the code for implementing a text range filter in SQL: function fnCreateTextRangeInput(oTable) { //var currentFilter = oTable.fnSettings().aoPreSearchCols[i].sSearch; th.html(_fnRangeLabelPart(0)); var sFromId = oTable. ...

Accessing the host in NextJS using _document.js or _app.js

I am currently working on a NextJs website that operates on various hostnames. Upon the application's initialization, I need to fetch data from an API based on the specific URL where NextJS is deployed. For instance, if my NextJS is running on websit ...

Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.tx ...

Parameter within onClick function that includes a dot

I'm attempting to design a table that enables an onClick function for the Change Password column's items so my system administrator can adjust everyone's password. Each onClick triggers the "ChangePassOpen" function which opens a modal with ...

Retrieve an array of information from a firestore database query

I am encountering an issue while trying to retrieve information about all users who are friends of a specific user. I have attempted to gather the data by pushing it to an array and then returning it as a single JSON array. However, it seems that the dat ...

Improving callback functions in Express/NodeJs for a more pleasant coding experience

function DatabaseConnect(req, res) {...} function CreateNewUser(req, res) {...} function ExecuteFunctions (app, req, res) { // If it's a POST request to this URL, run this function var firstFunction = app.post('/admin/svc/DB', func ...

javascript alter css property display to either visible or hidden

I am struggling with a CSS id that hides visibility and uses display: none. The issue arises when I want the element to be visible upon clicking a button, but removing the display:none property is causing design problems due to it being an invisible elemen ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...

Using jQuery in Rails 3 to display the id of a td element

I am working with a 3x3 table that contains td elements with unique id's (id='a1'...id='c3'). I want to enable the user to click on any of these 9 td elements and receive an alert displaying the id of the clicked td. Below is my C ...

Leveraging Forms for Entering Google Maps Information

Recently, I've been working on an app that aims to generate a custom map based on user input from a form. If you'd like to test the functionality yourself, head over to this page. After filling out all required fields and hitting "Submit", the g ...

What is the process for reversing the texture application direction on a CylinderGeometry object?

Is it possible to reverse the orientation of texture mapping on a CylinderGeometry object? var obj = new THREE.Mesh( new THREE.CylinderGeometry(20, 15, 1, 20), new THREE.MeshLambertMaterial({color: 0x000000}) //the material is later changed to the ...

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...

Learn to display multiple collections of data on a webpage using Node.js and MongoDB

Struggling with displaying multiple collections on my webpage. After extensive research, I keep encountering an error message saying "Failed to look up view in views directory." Here is the code snippet causing the issue: router.get('/', functio ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

The component 'ProtectRoute' cannot be utilized within JSX

While using typescript with nextjs, I encountered an issue as illustrated in the image. When I try to use a component as a JSX element, typescript displays the message: ProtectRoute' cannot be used as a JSX component. import { PropsWithChildren } from ...

Is next.js the fastest server-side page rendering solution available?

My website has a hidden page that requires authentication, so SEO isn't a concern. This page involves retrieving a substantial amount of data. I am wondering if the loading speed will be improved by implementing Server Side Rendering (SSR) and fetchi ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...