Contact us
Frontend 1 min read · 10/2022

Next.js and Revalidating Pre-Generated Pages When Content Changes

How do you regenerate statically pre-generated pages other than periodically? Typically when content changes in an API or CMS? There is the revalidate() function.

Next.js >=12.2 lets you invalidate a specific dynamically generated page via an API route. Internally, Next.js does this by invalidating the original cache of that file. However, the next request for that page still returns the original version, and only at that moment does it start regenerating the content in the background. So to make sure the next user actually gets the regenerated page, we can request the page ourselves. If revalidation fails, Next.js keeps serving the original version from the cache, so there is no need to worry about the page becoming unavailable.

It is a good idea to add a check that the request is valid to protect the endpoint against possible abuse. This can be done with a simple comparison of a key sent in a query parameter against a predefined key, e.g. in the .env file. After that, you can revalidate the given path.

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

    try {
        await res.revalidate('/article-2');
        await fetch('http://localhost/article-2');
        return res.json({revalidated: true});
    } catch (err) {
        return res.status(500).json({revalidated: false, error: err});
    }
}

An important caveat: revalidation only works on the domain on which you called it. If you use several domains (e.g. for localization), you need to call revalidation for each of them.

Share
LinkedIn Facebook

Need more than an article?

Get in touch with no obligation – a few sentences about what you are dealing with are enough.

Read on

Similar articles

More notes from operations and development.

All advice