How to Revalidate Next.js ISR Cache? On-Demand Cache Regeneration

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.


How to Revalidate Next.js ISR Cache? On-Demand Cache Regeneration

Image by storyset on Freepik

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. On-demand revalidation which was introduced with version 12.1 was the primary reason I choose Next.js over Nuxt.js when building my headless WordPress setup. A few months later a similar feature was introduced by Nuxt.js which again brings Nuxt(Vue) into the game.

Starting with v12.1.0, Next.js started experimental On-Demand Incremental Static Regeneration to manually purge the Next.js cache for a specific page. With the next version, namely v12.2.0 the feature got the stable status. Changing the function name from unstable_revalidate() to revalidate() was a breaking change for sites using the experimental feature. I spent an hour to fix revalidation when my site suddenly stopped regenerating the cache.

Advantages of On Demand Static Generation

Static Regeneration is a great feature if your content is definitely static. However, most of the time our content is subject to change fully, or at least partially. As a result, developers need to use Server Side Rendering and had to manage cache manually. Incremental Static Regeneration allowed us to create the non-existent content added after build-time in production and even define an expiration time to regenerate the cache. On-demand static generation took this one step ahead and as the name implies it allowed us to regenerate the content whenever requested.

How to use On-Demand Static Regeneration?

First, create a secret token only known by your Next.js app. This secret will be used to prevent unauthorized access to the revalidation API Route. You can access the route (either manually or with a webhook) with the following URL structure:

https://<your-domain-com>/api/revalidate?secret=MY_SECRET_TOKEN

Next, add the secret as an Environment Variable to your application. Finally, create the revalidation API Route:

// pages/api/revalidate.js

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 {
    // this should be the actual path not a rewritten path
    // e.g. for "/blog/[slug]" this should be "/blog/post-1"
    await res.revalidate('/path-to-revalidate')
    return res.json({ revalidated: true })
  } 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')
  }
}

Now you have an API endpoint that you can to use revalidate next.js cache. The way to trigger this endpoint depends on your backend setup. You basically need to post the subject path along with your secret key and need to manage the logic of revalidation on your backend. For my headless WordPress setup, I have created a plugin that triggers my Next.js endpoint whenever I add or update a post, page or category.

For detailed information please refer to Next.Js Incremental Static Regeneration documentation.

Have any question, suggestion or comment?

Evren Bal

I am Evren BAL

I've been an ‘Internet Creature’ since 1996!

More info about About Evren BAL

If you want to meet one-on-one, feel free to contact me via social media.

Reach Me Out

Reach Me Out

  • Have a question?
  • Noticed a mistake in the article?
  • Have a suggestion about the page?
  • Have a suggestion for an aticle topic?

Reach me out using the contact form or via my social media accounts.

Digital Ocean Logo

Want to try a free VPS?

Using my referral link, you may create a new Digital Ocean account with $100 credit valid for 60 days. This gives you the opportunity to try even the highest performing VPS.

My advice will be to start with a VPS that is feasible and affordable to use after the trial, so that the time you spend on setting up the server is not wasted.

Get your free credits here

You don&apos;t have to pay any penny, if you don&apos;t want to continue at the end of 60-day trial. If you prefer to continue with the paid service, your first $25 order will reward me $25 free credit that I can use for my hosting

In other words, you will get 100$ credit anyway, and I&apos;ll get a 25$ credit if you continue with the paid service in the long run.

Copyright © 2022 - Evren BAL