Blogs

Tools

Quick Links

Mridul.tech

Get Started with Next JS On-demand Revalidation

Mridul Panda

Mridul Panda

Jul 12, 2022

·

1 Min Read

Get Started with Next JS On-demand Revalidation
Next JS On-demand Revalidation

Recently Next JS introduced On-demand Revalidation. On v12.2.0 Next.js supports On-Demand Incremental Static Regeneration to manually purge the Next.js cache for a specific page.

Now you can update your site in the following cases.

  • Updates content from your headless CMS.
  • Creates new content is from your headless CMS.
  • Ecommerce metadata like price, category, reviews, etc changes

To test this we need to disable cache in apollo-link or apollo-client. In the defeultOptions, fetchPolicy as no-cache avoids using the cache. Let’s look at the code.

Also Read: How to Build PWA with Next JS?

Next JS On-demand Revalidation

Now you don’t need to specify revalidate to use on-demand revalidation inside getStaticProps. If revalidate is omitted, Next.js will use the default value of false (no revalidation) and only revalidate the page on-demand when our revalidate function is called.

Also Read: Next JS Project Ideas to Boost Your Portfolio

Secret Token Add

First, we will create a secret token for our Next JS Site in our env file. We will need this secret to prevent unauthorized access to the revalidation API Route.

.env.local
NEXT_SECRET_TOKEN = <SECRET_TOKEN>

You can access the route with the following URL structure

https://<your-site.com>/api/revalidate?path=<SLUG>&secret=<SECRET_TOKEN>

Also Read: How to add Google AdSense in Next JS

Revalidate function

We need to create a new file in our /pages/api folder. The file name will be revalidate.js. In this file, we will define our revalidate function.

// pages/api/revalidate.js

export default async function handler(req, res) {
  if (req.query.secret !== process.env.NEXT_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' });
  }

  try {
    await res.revalidate(req.query.path);
    return res.json({ revalidated: true });
  } catch (err) {
    return res.status(500).send('Error revalidating');
  }
}

req.query.path is the actual path for the revalidated URL. For /blog/[slug] this should be /blog/post-1. If the revalidation is successful we will get a success message. And the content will be updated. If there was an error, Next.js will continue to show the last successfully generated page.

Testing on-Demand Revalidation

When running locally with next dev, getStaticProps is invoked on every request. To verify your on-demand ISR configuration is correct, you will need to create a production build and start the production server. Run the following commands to create a production build and start the server with that build.

$ next build
$ next start

Disable Cache for On-demand Revalidation

If you’re using and cache like Appolo Cache then you might not able to see the changes with revalidate. You need to disable the cache. You need to add the following to your appolo client.

const defaultOptions = {
  watchQuery: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'ignore',
  },
  query: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'all',
  },
};

const client = new ApolloClient({
  link: concat(authMiddleware, httpLink),
  cache: new InMemoryCache(),
  defaultOptions: defaultOptions,
});

Then, you can confirm that static pages have successfully revalidated.

Tags :#isr

You may also like

How to add Google Web Stories in Next JS

How to add Google Web Stories in Next JS

Dec 14, 2023

·

10 Min Read

In the fast-paced digital world, user engagement is key to the success of any website. One effective way to captivate your audience is by incorporating Google Web Stories into your Next JS website. These visually appealing and interactive stories can make your content more engaging and shareable. In this comprehensive guide, we’ll walk you through […]

Read More

How to send Emails in Next JS for Free using Resend

How to send Emails in Next JS for Free using Resend

Nov 10, 2023

·

7 Min Read

Sending emails in web applications is a crucial feature, and in this article, we will explore how to send Emails in Next JS for free using Resend. Next JS is a popular framework for building React applications, and Resend is a handy tool for email integration. By the end of this guide, you’ll have the […]

Read More

How to add Google Login in Next.js with Appwrite

How to add Google Login in Next.js with Appwrite

Nov 01, 2023

·

7 Min Read

Are you looking to enhance user authentication in your Next.js application? Integrating Social Login with Appwrite can be a game-changer. Add Google Login to your Next.js app with Appwrite. This article will guide you through the process, and practical tips to add Google Login in Next.js with Appwrite. GitHub Code: Google Login in Next.js with […]

Read More

How to add Protected Routes in Next JS

How to add Protected Routes in Next JS

Oct 28, 2023

·

5 Min Read

In the world of web development, security is paramount. Whether you are building a simple blog or a complex web application, protecting certain routes and pages from unauthorized access is a crucial step. In this comprehensive guide, we will walk you through the process of adding protected routes in Next JS, ensuring that your web […]

Read More

How to run localhost 3000 on https in Next JS

How to run localhost 3000 on https in Next JS

Oct 20, 2023

·

2 Min Read

In the ever-evolving world of web development, having a secure local development environment is crucial. If you’re working with Next.js and need to run localhost on HTTPS with port 3000, you’re in the right place. In this comprehensive guide, we will walk you through the process step by step, ensuring you have a secure and […]

Read More

How to Generate robots.txt in Next JS?

How to Generate robots.txt in Next JS?

Oct 05, 2023

·

4 Min Read

In the world of web development and search engine optimization (SEO), ensuring that your website is easily accessible and properly indexed by search engines is paramount. One essential tool that aids in this process is the creation of a robots.txt file. In this comprehensive guide, we, the experts, will walk you through the process of […]

Read More

Do you want more articles on React, Next.js, Tailwind CSS, and JavaScript?

Subscribe to my newsletter to receive articles straight in your inbox.

If you like my work and want to support me, consider buying me a coffee.

Buy Me A Coffee

Contact Me ☎️

Discuss A Project Or Just Want To Say Hi?
My Inbox Is Open For All.

Mail : contact@mridul.tech

Connect with me on Social Media

Contact Art