Believemy logo purple

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 December 9, 2024
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: Development
Believemy logo
Comments (0)

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

Try for Free

Whether you're scaling your startup, building your first website, or transitioning to a developer role, Believemy is your new home. Join us, grow, and let’s build your project together.

Believemy is with anyone