0
0
NextjsHow-ToBeginner · 4 min read

How to Revalidate Cache in Next.js for Fresh Data

In Next.js, you can revalidate cache by using Incremental Static Regeneration (ISR) with the revalidate property in getStaticProps. For on-demand revalidation, use the res.revalidate(path) method inside API routes to refresh specific pages programmatically.
📐

Syntax

Next.js provides two main ways to revalidate cache for static pages:

  • ISR with revalidate in getStaticProps: Automatically regenerates the page after a set number of seconds.
  • On-demand revalidation with res.revalidate(path) in API routes: Manually triggers regeneration of a specific page.

Here is the syntax for both:

javascript
export async function getStaticProps() {
  // fetch data
  return {
    props: { /* your props */ },
    revalidate: 10, // seconds after which page re-generates
  };
}

// API route example for on-demand revalidation
export default async function handler(req, res) {
  // Validate request
  await res.revalidate('/path-to-revalidate');
  return res.json({ revalidated: true });
}
💻

Example

This example shows a Next.js page that uses ISR to revalidate every 15 seconds and an API route to trigger on-demand revalidation of the homepage.

javascript
// pages/index.js
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  return {
    props: { data },
    revalidate: 15, // regenerate page every 15 seconds
  };
}

export default function Home({ data }) {
  return <div>Data: {JSON.stringify(data)}</div>;
}

// pages/api/revalidate.js
export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: 'Method not allowed' });
  }
  try {
    await res.revalidate('/'); // revalidate homepage
    return res.json({ revalidated: true });
  } catch (err) {
    return res.status(500).json({ message: 'Error revalidating' });
  }
}
Output
<div>Data: { /* JSON data from API */ }</div>
⚠️

Common Pitfalls

  • Forgetting to set revalidate in getStaticProps causes pages to never update after build.
  • Calling res.revalidate outside API routes or without proper authentication can cause errors or security issues.
  • Not handling errors in the API route can make debugging difficult.
  • Using revalidate with dynamic routes requires passing the correct path to res.revalidate.
javascript
// Wrong: Missing revalidate in getStaticProps
export async function getStaticProps() {
  return { props: { data: [] } };
}

// Right: Add revalidate
export async function getStaticProps() {
  return { props: { data: [] }, revalidate: 10 };
}

// Wrong: Calling res.revalidate outside API route
// This will cause an error
// res.revalidate('/');

// Right: Use inside API route handler
export default async function handler(req, res) {
  await res.revalidate('/');
  res.json({ revalidated: true });
}
📊

Quick Reference

FeatureUsageNotes
ISR with revalidaterevalidate: seconds in getStaticPropsAuto regenerates page after given seconds
On-demand revalidationres.revalidate(path) in API routeManually triggers regeneration of specific page
API Route MethodPOST request recommendedSecure with authentication to avoid abuse
Dynamic RoutesPass correct path to res.revalidateUse exact route string like /posts/1

Key Takeaways

Use revalidate in getStaticProps to enable automatic cache refresh with ISR.
Use API routes with res.revalidate(path) for manual, on-demand cache revalidation.
Always secure your on-demand revalidation API routes to prevent unauthorized use.
Remember to handle errors in API routes to avoid silent failures.
Pass exact paths when revalidating dynamic routes to ensure correct pages update.