Incremental Static Regeneration Options in Next JS

No comments

Incremental static regeneration is one of the amazing features available in NextJS – it allows for lightning fast site speed without having to rebuild entire static site when content changes are done. In this article, we’ll take a look at the different ISR options supported by Next JS and how they can be used in Sitecore Next JS rendering host.

Since the release of NextJS v12.1.0 earlier this year, there is a new approach for ISR – which creates static files ‘on-demand’ : sounds interesting isn’t it ? Now, let’s look at both the options in details and their pro’s and cons.

Option 1 : Automatic revalidation

This option will regenerate pages in a fixed interval time and this is a default option that comes along with the Sitecore NextJS app.

// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// revalidation (or fallback) is enabled and a new request comes in.
export const getStaticProps: GetStaticProps = async (context) => {
  const props = await sitecorePagePropsFactory.create(context);
  return {
    props,
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every 5 seconds
    revalidate: 5, // In seconds
    notFound: props.notFound, // Returns custom 404 page with a status code of 404 when true
  };
};
  • All requests to the page after the first request and before 5 seconds renders the static page.
  • After the 5-second window, the first request displays the static page.
  • Next.js triggers a re-generation of the page in the background. Once the page has been successfully generated, Next.js invalidates the cache and displays the updated page.
  • If the regeneration fails in the background, the old page remains unchanged.

Pro’s :

  • Simple to configure as revalidation happens upon request after a specific interval so there is no need of additional configuration.

Con’s :

  • When a user comes to your website, you want them to see the latest version immediately. With this automatic ISR feature, there is no guarantee that user sees the latest version. Same is applicable for search engine crawlers.
  • Currently there is no option to set different expiry time for different paths, meaning – least updated pages will also be revalidated for changes after specific interval.

Option 2: On demand Revalidation

With the name, it is clear that the Static page is revalidated on demand. So how does it differ from above option and first let’s see how it is setup.

Create an api route that is used for revalidation. In the below snippet, you can notice that I am passing multiple paths within the req.body. Make sure this end point is accessible only with a secret token.

export default async function handler(req, res) {
  // Check for secret to confirm this is a valid request
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' })
  }
  
  try {
    const paths = (req.body?.paths).split(',');
    const revalidatedPaths = [];
    paths.forEach(async (path) => {
      await res.unstable_revalidate(path);
      revalidatedPaths.push({ revalidated: true, path: path });
    });
    return res.json({ revalidated: true, paths });
  } catch (err) {
    // If there was an error, Next.js will continue
    // to show the last successfully generated page
    return res.status(500).send('Error revalidating');
  }
}

This api can then be called from "publish:end" event by passing list of pages in request body, sounds familiar isn't it ? 😀 

Let’s say you plan to host multiple sites on the same host, or you have huge publishing activities. In this case, to make the system scalable, I would recommend using event grids or a service bus so that pages are published and processed in a sequential order to preserve the integrity of the published pages.

Now let’s see it’s pro’s and con’s,

Pro’s :

  • Pages are revalidated the moment content is updated in Sitecore CMS and published, making the page that is visible in live site to be always latest.
  • In a site where there are not many page updates, it makes sense not to revalidate every few seconds.
  • Page or Path or Template specific ISR is possible to implement as it is easier to update the revalidate api to handle the requests.
  • In a typical solution with a CMS or E-Commerce solution, some important information like pricing should be revalidated immediately upon changes – which is easier to do in this approach.

Con’s :

  • Event driven approach, so there are chances of page not being updated compared to automatic revalidation which checks every few seconds. But there is an option to have both ! I would recommend to set revalidation time to 60 seconds or more when on demand revalidation is used.

Hope you got an idea of different ISR approaches, now you utilize these powerful feature based on your use case or solution architecture 🙂 !

References:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.