0
0
NextJSframework~15 mins

On-demand revalidation in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - On-demand revalidation
What is it?
On-demand revalidation in Next.js is a way to update static pages after they have been built and served. Instead of rebuilding the entire site or waiting for a scheduled update, you can trigger a specific page to refresh its content when needed. This helps keep pages fresh without slowing down users with long build times.
Why it matters
Without on-demand revalidation, static pages can become outdated until the next scheduled rebuild, causing users to see stale content. This can hurt user experience and business goals, especially for dynamic data like news or product info. On-demand revalidation solves this by letting developers update pages instantly when data changes, keeping content accurate and timely.
Where it fits
Before learning on-demand revalidation, you should understand Next.js static generation and incremental static regeneration (ISR). After mastering this, you can explore advanced caching strategies and serverless functions to optimize content delivery and update triggers.
Mental Model
Core Idea
On-demand revalidation lets you refresh specific static pages instantly by telling Next.js to rebuild them when data changes.
Think of it like...
It's like having a digital bulletin board where you pin notices (static pages). Normally, you replace all notices only at set times (scheduled rebuilds). On-demand revalidation is like having a remote control that lets you update just one notice immediately when new info arrives.
┌─────────────────────────────┐
│ User requests static page   │
├─────────────┬───────────────┤
│             │               │
│  Cache hit  │  Cache miss   │
│  (serve     │  (build page) │
│   cached)   │               │
└─────┬───────┴───────┬───────┘
      │               │
      │               ▼
      │       ┌─────────────────┐
      │       │ On-demand       │
      │       │ Revalidation    │
      │       │ Triggered?      │
      │       └───────┬─────────┘
      │               │ Yes
      │               ▼
      │       ┌─────────────────┐
      │       │ Rebuild page    │
      │       │ and update cache│
      │       └─────────────────┘
Build-Up - 7 Steps
1
FoundationStatic Generation Basics in Next.js
🤔
Concept: Learn how Next.js creates static pages at build time to serve fast content.
Next.js can pre-build pages into static HTML during the build process. These pages load quickly because they don't need server processing on each request. This is called Static Generation. However, the content stays the same until the next build.
Result
Pages load very fast because they are static files, but content can become outdated if data changes after build.
Understanding static generation is key because on-demand revalidation builds on this by updating static pages after build.
2
FoundationIncremental Static Regeneration (ISR) Concept
🤔
Concept: ISR lets Next.js update static pages in the background after a set time without rebuilding the whole site.
With ISR, you specify a 'revalidate' time in seconds for a page. When a user visits after that time, Next.js serves the old page but triggers a rebuild in the background. The next visitor gets the fresh page. This keeps content updated without slowing users.
Result
Pages update automatically over time, balancing freshness and speed.
ISR introduces the idea that static pages can be refreshed incrementally, setting the stage for on-demand control.
3
IntermediateWhat is On-demand Revalidation?
🤔
Concept: On-demand revalidation lets you manually trigger a page rebuild anytime, not just on a timer.
Instead of waiting for the revalidate timer, you can call Next.js API to tell it to rebuild a specific page immediately. This is useful when data changes unpredictably, like after a user edits content or an admin updates a product.
Result
Pages update instantly when you want, keeping content accurate without waiting.
Knowing you can control page updates manually gives you flexibility to keep content fresh exactly when needed.
4
IntermediateUsing Next.js API Route for Revalidation
🤔Before reading on: do you think the revalidation API requires a special server or works with serverless functions? Commit to your answer.
Concept: You create an API route in Next.js that calls the revalidation method to refresh pages on demand.
In Next.js, you write an API route that calls res.revalidate('/page-path') to trigger rebuilding that page. This API can be called from anywhere, like a webhook or admin panel. It works with serverless functions, so no special server setup is needed.
Result
Calling the API route causes Next.js to rebuild and update the specified page's static content.
Understanding that revalidation is triggered via API routes unlocks how to integrate content updates with external systems.
5
IntermediateSecurity Considerations for Revalidation API
🤔Before reading on: do you think anyone can call your revalidation API by default? Commit to your answer.
Concept: Because the revalidation API can rebuild pages, it must be protected to prevent misuse.
You should add secret tokens or authentication checks in your API route to ensure only authorized calls trigger revalidation. Without this, anyone could force rebuilds, causing performance issues or exposing data.
Result
Secure API routes prevent unauthorized page rebuilds and protect your site.
Knowing to secure revalidation endpoints prevents common security and performance problems in production.
6
AdvancedHandling Dynamic Routes with On-demand Revalidation
🤔Before reading on: do you think you must revalidate all dynamic pages at once or can you target individual dynamic pages? Commit to your answer.
Concept: You can target specific dynamic pages for revalidation by specifying their exact path.
For dynamic routes like /posts/[id], you call res.revalidate('/posts/123') to rebuild only that page. This avoids rebuilding unrelated pages and keeps updates efficient. You must know the exact path to revalidate.
Result
Only the changed dynamic page is rebuilt, saving resources and speeding updates.
Understanding path-specific revalidation for dynamic routes helps optimize update scope and performance.
7
ExpertLimitations and Edge Cases of On-demand Revalidation
🤔Before reading on: do you think revalidation triggers block user requests or happen asynchronously? Commit to your answer.
Concept: Revalidation triggers are asynchronous and have limits on frequency and concurrency that affect behavior.
When you call res.revalidate(), Next.js serves the old page while rebuilding the new one in the background. If many revalidations happen simultaneously, some may queue or fail. Also, revalidation only updates static pages, so server-side rendered pages are unaffected. Understanding these limits helps design robust update flows.
Result
Revalidation keeps pages available during updates but requires careful handling of concurrency and timing.
Knowing the asynchronous nature and limits of revalidation prevents bugs and performance issues in complex apps.
Under the Hood
Next.js stores static pages as cached HTML files after build. When on-demand revalidation is triggered via the API, Next.js marks the page as stale and rebuilds it in the background using the original page code and data fetching methods. The new HTML replaces the old cache once ready. During rebuild, users still get the old page, ensuring no downtime.
Why designed this way?
This design balances performance and freshness. Serving cached pages is fast and scalable, while background rebuilds avoid blocking users. The API trigger lets developers update content precisely when needed, avoiding full site rebuilds. Alternatives like full rebuilds or server-side rendering either slow users or increase server load.
┌───────────────┐        ┌─────────────────────┐
│ User requests │───────▶│ Serve cached static  │
│ static page   │        │ HTML page           │
└───────────────┘        └─────────┬───────────┘
                                     │
                                     │
                        ┌────────────▼─────────────┐
                        │ On-demand revalidation    │
                        │ API called triggers rebuild│
                        └────────────┬─────────────┘
                                     │
                        ┌────────────▼─────────────┐
                        │ Rebuild page in background│
                        │ Replace cached HTML       │
                        └──────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does on-demand revalidation immediately block user requests until rebuild finishes? Commit yes or no.
Common Belief:On-demand revalidation blocks user requests until the page is rebuilt, causing delays.
Tap to reveal reality
Reality:Revalidation happens in the background; users continue to see the old page until the new one is ready.
Why it matters:Believing it blocks users may cause developers to avoid using it, missing out on fast updates without downtime.
Quick: Can you revalidate any page without specifying its exact path? Commit yes or no.
Common Belief:You can trigger revalidation for all pages or dynamic routes without specifying exact paths.
Tap to reveal reality
Reality:You must specify the exact path of the page to revalidate; there is no wildcard revalidation.
Why it matters:Misunderstanding this leads to inefficient or failed updates, as developers may expect all pages to refresh automatically.
Quick: Is the revalidation API route public by default and safe to call from anywhere? Commit yes or no.
Common Belief:The revalidation API is secure by default and does not need extra protection.
Tap to reveal reality
Reality:The API route is public unless you add authentication or secret tokens; otherwise, anyone can trigger rebuilds.
Why it matters:Ignoring security can lead to abuse, performance issues, or data leaks.
Quick: Does on-demand revalidation update server-side rendered pages? Commit yes or no.
Common Belief:On-demand revalidation updates all pages, including server-side rendered ones.
Tap to reveal reality
Reality:It only updates static pages generated by static generation or ISR, not server-side rendered pages.
Why it matters:Confusing this causes wasted effort trying to revalidate pages that don't support it.
Expert Zone
1
On-demand revalidation calls are rate-limited internally to prevent excessive rebuilds, so batching triggers can improve efficiency.
2
Revalidation triggers do not guarantee immediate cache update; there can be slight delays depending on serverless cold starts or build times.
3
Using on-demand revalidation with dynamic routes requires careful path management to avoid stale or orphaned pages.
When NOT to use
Avoid on-demand revalidation if your site relies heavily on real-time data or user-specific content; use server-side rendering or client-side fetching instead. Also, if your update frequency is very high, consider a fully dynamic approach rather than static regeneration.
Production Patterns
In production, on-demand revalidation is often triggered by CMS webhooks when content changes, or by admin dashboards after edits. It is combined with authentication and logging to monitor rebuilds. Developers also batch multiple page revalidations in one API call to optimize performance.
Connections
Caching Strategies
On-demand revalidation builds on caching by selectively refreshing cached content.
Understanding caching helps grasp why revalidation updates only specific pages instead of rebuilding everything.
Webhooks
On-demand revalidation is often triggered by webhooks from external systems.
Knowing how webhooks work clarifies how content changes outside Next.js can automatically update static pages.
Event-driven Architecture
On-demand revalidation exemplifies event-driven updates where actions trigger specific reactions.
Recognizing this pattern helps design scalable systems that react to changes efficiently.
Common Pitfalls
#1Leaving the revalidation API route unprotected, allowing anyone to trigger rebuilds.
Wrong approach:export default async function handler(req, res) { await res.revalidate('/'); res.json({ revalidated: true }); }
Correct approach:export default async function handler(req, res) { if (req.query.secret !== process.env.REVALIDATE_SECRET) { return res.status(401).json({ message: 'Invalid token' }); } await res.revalidate('/'); res.json({ revalidated: true }); }
Root cause:Not understanding that API routes are public by default and need explicit security.
#2Calling res.revalidate() without specifying the exact page path for dynamic routes.
Wrong approach:await res.revalidate('/posts/[id]');
Correct approach:await res.revalidate('/posts/123');
Root cause:Misunderstanding that dynamic routes require concrete paths, not parameter placeholders.
#3Expecting on-demand revalidation to update server-side rendered pages.
Wrong approach:Using res.revalidate() on pages with getServerSideProps expecting content refresh.
Correct approach:Use client-side fetching or server-side rendering without static regeneration for dynamic content.
Root cause:Confusing static generation with server-side rendering and their update mechanisms.
Key Takeaways
On-demand revalidation lets you update static pages instantly by triggering rebuilds via API routes.
It works asynchronously, serving old content while rebuilding to avoid blocking users.
You must specify exact page paths, especially for dynamic routes, to revalidate correctly.
Securing the revalidation API is critical to prevent unauthorized rebuilds and performance issues.
On-demand revalidation complements static generation and ISR, giving precise control over content freshness.