Implementing over-request revalidation with NextJS

If you're a web developer, you probably know how important it is to have a fast, responsive site to deliver an optimal user experience. In this article, we're going to show you how to set up on-demand revalidation with NextJS, a feature that refreshes your site's data only when necessary. Using this method, you can save resources and improve the performance of your website, while offering up-to-date data to your users.
•
Updated on August 14, 2026
•
6 min read
Believemy logo

If you are a web developer, you surely know how important it is to have a fast and responsive website to offer an optimal user experience. In this article, we will present how to implement on-demand revalidation with NextJS, a feature that allows you to refresh your site's data only when necessary. With this method, you can save resources and improve your website's performance while providing up-to-date data to your users.

We will guide you step by step in setting up this feature, using concrete examples and detailed explanations. Let's dive right in to see how to implement on-demand revalidation with NextJS.

 

Static Generation?

NextJS is undoubtedly the most widely used technology at the moment, at least for creating websites with React.

One of the greatest strengths of this framework lies in its features that allow you to create a website optimized for SEO and display speed.

This speed is made possible - notably - by static page generation.

These pages are essentially "pre-rendered" at the time of the website's launch (or during a code update). Unlike a "classic" page that is generally rendered on each request from a new visitor, a static page will be reused each time. There's no need to recreate the page for every visit.

From this perspective, one might think that everything would be better in an ideal world by making all our pages static... Yes. But no.

 

The Problem with Static Page Generation

The reality is that there's a significant problem with static pages: they are no longer modified once they have been created. This simply means that when you write a blog post, for example, and you edit that post from your editing space... the update of that post will never appear to your visitors.

Indeed, the page is already created; it's frozen in time. Therefore, theoretically, you would need to perform a complete reinstallation of your website to see the changes to your post. This is a very time-consuming and costly solution, and it becomes impossible if you have a large project with updates to your static pages every three minutes.

There was a relatively simple solution: using the revalidate property with a value in seconds to specify to NextJS that the page should be recreated after x seconds when a user accesses it.

The problem with this solution is as follows:

  • The shorter your delay, the more static generation loses its benefit: if you regenerate your page every second, needless to say, you lose performance, and you end up generating on the fly like "classic" pages;
  • The longer your delay, the longer your visitors will have to wait to see the latest update of your page: imagine waiting for a page to reload an hour after correcting spelling mistakes, for example, and you'll understand how this isn't a solution.

 

The Miracle Solution: On-Demand Generation

That's where the miracle solution comes in: on-demand generation.

This feature appeared in NextJS version 12.2.0. It finally allows us to generate a static page when we launch our website and regenerate it when we request it: for example, when we modify a post.

Thanks to this feature, you can offer all your articles, sales pages, products in a static manner while ensuring that your pages are always fully up-to-date.

 

How Does NextJS's On-Demand Generation Work?

To understand how on-demand generation works, let's look at these steps together:

  • The article is modified;
  • We send a request to our API to update the article's data;
  • Once the modification is successfully made, we call a second API to tell it to regenerate the modified article's page.
  • The article is fully regenerated, your update is taken into account, and your page will now be reused for each user. You gain in display speed and thus in SEO.

 

How to Implement It?

To use the on-demand generation feature, you need to start by creating a security key.

A security key is a sort of code that you will provide to NextJS to ensure that only you and no one else can regenerate requested pages by accessing your URL.

I invite you to create this variable in your .env or next.config.js file:

JAVASCRIPT
NEXT_REVALIDATION: "CODE";

Of course, feel free to modify the value of this code.

Now, you need to create the API that will allow you to regenerate the page you request. Here it is - /api/next/revalidate.js (or any other name):

JAVASCRIPT
export default async function handler(req, res) {
    // Check for secret to confirm this is a valid request
    if (req.query.secret != process.env.NEXT_REVALIDATION) {
        return res.status(401).json({ message: "Invalid code" });
    }

    // Check for data
    const { path } = req.body;

    if (!path) {
        res.status(400).json({
            message: "A required field is missing.",
        });
        return;
    }

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

In the first part of this code, we verify if the code is indeed received in the URL and then check if the code matches the one we set in our configuration.

JAVASCRIPT
if (req.query.secret != process.env.NEXT_REVALIDATION) {
    return res.status(401).json({ message: "Invalid code" });
}

Next, it's important to verify if we receive the path. This is the path of the page we want to regenerate.

JAVASCRIPT
const { path } = req.body;

if (!path) {
    res.status(400).json({
        message: "A required field is missing.",
    });
    return;
}

Once we know that the person requesting to regenerate the page is authorized to do so and that we have the path of the page we want to regenerate, all that's left is to make the request to NextJS.

JAVASCRIPT
try {
    await res.revalidate(path);
    return res.json({ revalidated: true });
} catch (err) {
    return res.status(500).send("Unable to recreate this page.");
}

As we do things by the book, we ask NextJS for this regeneration within a try catch block: if a problem occurs, we stop the code and display an error message.

Now, all that's left is to call your new API - /api/next/revalidate?secret=CODE by passing the page you wish to regenerate in the path variable (using the POST method in our small example) to regenerate a page that will be fully updated.

Let's help you out with what it looks like:

JAVASCRIPT
const valid = await fetch(
    `https://website.com/api/next/revalidate?secret=${process.env.NEXT_REVALIDATION}`,
    {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            path: `/r/${slug}`,
        }),
    },
);

const revalidation = await valid.json();

if (!valid.ok) {
    res.status(400).json({
        message: revalidation.message,
    });
    return;
}

To learn more, start our completely free dedicated NextJS course!

Category: Developers

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.

Believemy logo
Comments (0)

You need to be logged in to comment on this article: log in or sign up.

Read next

Setting up a loader when changing a Nextjs page

Have you ever been on a site where you click on a link and nothing happens? Or perhaps you've wondered whether your request was actually received? This is where having a loader comes in. In this article, we'll explain why it's important to have a loader on your website, how to set it up in your Nextjs project and create a function that will display the loader until the page is loaded. If you want to improve the user experience on your website and reassure your visitors, this article is for you.

December 11, 2024

How to use localStorage in a NextJs or React application

The aim of this article is to teach you how to use localStorage in a Next.JS or React application. Indeed, there are a few differences with the normal use, in a vanilla application.

December 11, 2024

Why you should learn NextJS in 2025: all the benefits!

Explore why Next.js is a must-have framework for developers in 2025. Learn about its benefits, unique features and why the job market is increasingly adopting it.

December 6, 2024

What's new in NextJS 15

NextJS 15 was presented to the world on October 24, 2024 in San Francisco. Here's everything we know about NextJS 15's powerful new features!

December 5, 2024

How to use Server Actions with NextJS

Discover why and how NextJS Server Actions improve performance on both Client Components and Server Components, and learn how to use them in your projects.

December 9, 2024

React vs NextJS: what should you choose for your project in 2025?

Which technology should you use, React or NextJS? Discover their advantages and disadvantages to choose the one best suited to your projects.

December 9, 2024

Understanding .env files with ReactJS

Find out how to really use the .env file with React or NextJS so you never make a mistake again.

December 9, 2024

Send an email with NextJS and SendGrid for free

Have you always wanted to send emails with JavaScript? Or more specifically, how to send emails with React or NextJS? Then let's find out together how to use SendGrid! It's a quick and easy solution to set up that will help us ensure that our emails are sent and, most importantly, received.

December 9, 2024

Become the solopreneur you dream of being.

First project, career change, business launch: access our courses, practice on real-world cases, and move forward with clear guidance.