Home > Enterprise >  Statically pre-render most popular queries with NextJS
Statically pre-render most popular queries with NextJS

Time:04-28

I am using NextJS to pre-render pages of the format:

./pages/folder/[variable].js

I have a set of some ~ 8000 possible values for [variable], so it is not practically feasible to statically generate all 8000 of these pages. Because of this, I use getSeverSideProps() whenever this page is loaded. Here is what that looks like:

export async function getServerSideProps(context) {
    const { variable } = context.params
    const { res } = context;
    // Caches response for 15 minutes on the server side
    res.setHeader('Cache-Control', `s-maxage=900, stale-while-revalidate`)

    const { data } = await axios.get(url   variable);
    return { props : {data} }
}

In spite of there being over ~ 8000 values, the top 50 values contain ~90% of queries.

Is there any way to statically pre-render these 50 values with something like getStaticPaths() and getStaticProps(), such that these particular 50 queries are faster to load?

Secondarily, and less concerning, is that the list of the most common requests changes slightly over time. If there was a solution to dynamically determine this list of 50 values, that would be ideal (although is not strictly necessary).

CodePudding user response:

This is exactly the concept of Incremental Static Regeneration in Nextjs:

Next.js allows you to create or update static pages after you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, without needing to rebuild the entire site. With ISR, you can retain the benefits of static while scaling to millions of pages.

and here is how it works:

// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// the path has not been generated.
export async function getStaticPaths() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: blocking } will server-render pages
  // on-demand if the path doesn't exist.
  return { paths, fallback: 'blocking' }
}

Don't forget that you still need to define getStaticProps function on your page.

Here is the official Documentation about Incremental Static Regeneration

  • Related