Home Projects Portfolio Dashboard Export PDF Log in

Optimizing Data Freshness in Next.js with Strapi Cache Revalidation

Managing data consistency between a headless CMS and a frontend framework can be tricky, especially when your users expect to see real-time updates without sacrificing the performance benefits of static generation.

In the strapi-project, we recently addressed a bottleneck where stale data was persisting in the Next.js cache, leading to a disconnect between content updates in Strapi and what the end user experienced.

The Challenge: Stale Content

Next.js relies heavily on caching to serve pages at blistering speeds. While this is great for SEO and load times, it can be problematic when content editors update information in the Strapi dashboard, but the frontend continues to serve the cached version of the page for an extended period.

The Implementation

To ensure our content is always current, we implemented a revalidation strategy that targets our data fetch requests. By leveraging the revalidate option in our Next.js data fetching logic, we can instruct the framework to re-verify the cache periodically.

// lib/api.js
export async function getPageData(slug) {
  const res = await fetch(`https://api.example.com/pages/${slug}`, {
    next: {
      revalidate: 3600 // Revalidate cache every hour
    }
  });
  return res.json();
}

This configuration ensures that Next.js will attempt to re-fetch the data from our Strapi backend at the specified interval, guaranteeing that our users are never more than an hour away from seeing the latest content edits.

Fine-Tuning the Strategy

While fixed-interval revalidation works for many use cases, we also explored programmatic revalidation. This allows us to trigger a cache clear the moment a webhook from Strapi notifies us that an entry has been published or updated.

// app/api/revalidate/route.js
export async function POST(req) {
  const body = await req.json();
  const { path } = body;
  
  if (path) {
    revalidatePath(path);
    return Response.json({ revalidated: true });
  }
  return Response.json({ revalidated: false }, { status: 400 });
}

Takeaways

By integrating selective revalidation, we've successfully balanced the need for high-speed page delivery with the requirement for content accuracy. The key is choosing the right balance between revalidation frequency and server load. Always monitor your API request volume when lowering revalidation times to prevent overwhelming your backend infrastructure.


Generated with Gitvlg.com

Optimizing Data Freshness in Next.js with Strapi Cache Revalidation
G

Gregory Subero

Author

Share: