0
0
NextjsConceptBeginner · 3 min read

On-Demand Revalidation in Next.js: How It Works and When to Use

In Next.js, on-demand revalidation lets you update static pages instantly by triggering a server-side refresh via an API call. This means you can keep pages fresh without waiting for scheduled rebuilds or redeployments.
⚙️

How It Works

On-demand revalidation in Next.js works like a manual refresh button for your static pages. Normally, static pages are built once and served as-is, which is fast but can get outdated. With on-demand revalidation, you can tell Next.js to update a specific page right away by calling a special API route.

Think of it like a newspaper printing press. Usually, the press prints papers on a schedule, but if there's breaking news, you want to print a fresh edition immediately. On-demand revalidation is that urgent reprint triggered by an API call, so your users always see the latest content without waiting for the next scheduled build.

💻

Example

This example shows how to create an API route in Next.js that triggers on-demand revalidation for a page at /posts/[id]. When you call this API with the post ID, Next.js will regenerate that page immediately.

javascript
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req, res) {
  // Check for secret token to secure the API
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' });
  }

  const postId = req.query.id;
  if (!postId) {
    return res.status(400).json({ message: 'Post ID is required' });
  }

  try {
    // Revalidate the page for the given post ID
    await res.revalidate(`/posts/${postId}`);
    return res.json({ revalidated: true });
  } catch (err) {
    return res.status(500).json({ message: 'Error revalidating' });
  }
}
Output
{"revalidated":true}
🎯

When to Use

Use on-demand revalidation when you have static pages that need to update immediately after content changes, but you want to keep the speed benefits of static generation. For example:

  • Blog posts or articles updated by editors
  • Product pages with changing prices or stock
  • Event pages with new schedules

This avoids rebuilding your entire site or waiting for automatic revalidation intervals, giving users fresh content quickly.

Key Points

  • On-demand revalidation lets you refresh static pages instantly via API calls.
  • It keeps the benefits of static pages while allowing dynamic updates.
  • You secure the API route with a secret token to prevent misuse.
  • It is ideal for content that changes unpredictably and needs fast updates.

Key Takeaways

On-demand revalidation updates static pages instantly without full rebuilds.
It uses a secure API route to trigger page regeneration on the server.
Ideal for content that changes often but benefits from static speed.
Helps keep user content fresh without waiting for scheduled updates.