Revalidating Data

Next.js allows you to update specific static routes without needing to rebuild your entire site. Revalidation (also known as Incremental Static Regeneration) allows you to retain the benefits of static while scaling to millions of pages.

There are two types of revalidation in Next.js:

  • Background: Revalidates the data at a specific time interval.
  • On-demand: Revalidates the data based on an event such as a data update.

Background Revalidation

To revalidate cached data at a specific interval, you can use the next.revalidate option in fetch(). The default unit is seconds.

fetch('https://...', { next: { revalidate: 60 } });

If you want to revalidate data that does not use fetch (i.e. using an external package or query builder), you can use the route segment config.

app/page.tsx
export const revalidate = 60; // revalidate this page every 60 seconds

How it works

  1. When a request is made to the route that was statically rendered at build time, it will initially show the cached data.
  2. Any requests to the route after the initial request and before 60 seconds are also cached and instantaneous.
  3. After the 60-second window, the next request will still show the cached (stale) data.
  4. Next.js will trigger a regeneration of the data in the background.
  5. Once the route generates successfully, Next.js will invalidate the cache and show the updated route. If the background regeneration fails, the old data would still be unaltered.

When a request is made to a route segment that hasn’t been generated, Next.js will dynamically render the route on the first request. Future requests will serve the static route segments from the cache.

Note: Check if your upstream data provider has caching enabled by default. You might need to disable (e.g. useCdn: false), otherwise a revalidation won't be able to pull fresh data to update the ISR cache. Caching can occur at a CDN (for an endpoint being requested) when it returns the Cache-Control header. ISR on Vercel persists the cache globally and handles rollbacks.

On-demand Revalidation

If you set a revalidate time of 60, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is if someone visits the page after the minute has passed.

Starting with v12.2.0, Next.js supports On-Demand Incremental Static Regeneration to manually purge the Next.js cache for a specific page. This makes it easier to update your site when:

  • Content from your headless CMS is created or updated.
  • Ecommerce metadata changes (price, description, category, reviews, etc).

Using On-Demand Revalidation

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-site.com>/api/revalidate?secret=<token>

Next, add the secret as an Environment Variable to your application.

.env
MY_SECRET_TOKEN=<token>

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');
  }
}

Note: For now, you need to create the API route inside the pages directory.

View our demo to see on-demand revalidation in action and provide feedback.

Testing On-Demand Revalidation During Development

To verify your on-demand ISR configuration is correct when running locally with next dev, you will need to create a production build and start the production server:

$ next build
$ next start

Then, you can confirm that the static route has been successfully revalidated.

Error Handling and Revalidation

If an error is thrown while attempting to revalidate, the last successfully generated route will continue to be used. On the next subsequent request, Next.js will retry revalidating.