Engineering

Headless WordPress Caching & Revalidation in Next.js

Master multi-tier caching for Headless WordPress. An engineering guide to HTTP headers, ISR, tag-based purging, and edge invalidation in Next.js.

Blogitems
By Blogitems Team
··Updated Nov 26, 2026·8 min read
On this page (10)
Headless WordPress Caching & Revalidation in Next.js
πŸ’‘

Key Takeaways (TL;DR)

Naive caching strategies in headless WordPress lead to two disastrous extremes: stale content that frustrates editors, or uncached database queries that crash origin servers. By architecting a multi-tier caching strategy combining Next.js fetch tags, stale-while-revalidate edge headers, and atomic WordPress webhooks, you achieve sub-50ms global latency with instant content freshness.

Ask an engineering team how they cache their headless WordPress site, and you will usually uncover one of two catastrophic extremes.

The first camp is terrified of stale content. They set cache: 'no-store' or revalidate: 0 on every fetch call because their marketing director threw a fit when a homepage typo didn’t update instantly.

The result? Every single page view hits the origin WordPress REST API directly. A minor traffic spike floods your PHP workers, MySQL CPU pins at 100%, and your origin server drops dead from an unmitigated self-inflicted denial of service.

The second camp went to the other extreme: they configured aggressive time-based caching (revalidate: 86400) and told their editorial team that content updates take twenty-four hours to appear on the live site. Editorial velocity collapses, and writers stop trusting the platform entirely.

Both approaches are architectural failures.

In computer science, cache invalidation is famously one of the two hard problems. But in modern web engineering, you do not have to choose between instant content freshness and sub-50ms edge performance.

Here is the masterclass on architecting a battle-tested, multi-tier caching and revalidation pipeline between Headless WordPress and Next.js App Routerβ€”complete with edge CDN invalidation, surgical fetch tags, and zero-downtime deployment safety.

Editorial Transparency: We independently test, compare, and recommend software tools based on hands-on evaluation. When you purchase through our links, we may earn an affiliate commission at no additional cost to you.

The Mental Model: The 4 Tiers of Modern Headless Caching

Caching in headless WordPress is not a single toggle switch. It is a multi-layered defense-in-depth architecture where each tier protects the layer behind it:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 1: THE BROWSER RUNTIME CACHE                      β”‚
β”‚ Cache-Control: public, max-age=0, must-revalidate      β”‚
β”‚ (Ensures browser always asks edge for fresh version)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚ HTTP Request
                            β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 2: THE GLOBAL EDGE CDN CACHE (Vercel / Cloudflare)β”‚
β”‚ s-maxage=31536000, stale-while-revalidate=86400        β”‚
β”‚ (Serves pre-rendered static HTML from edge RAM in 35ms)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚ On-Demand Revalidation Webhook
                            β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 3: NEXT.JS DATA CACHE (fetch Cache Tags)          β”‚
β”‚ next: { tags: ['post-slug', 'blog-feed'] }             β”‚
β”‚ (Caches raw WordPress JSON responses across builds)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚ Surgical Cache Miss
                            β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TIER 4: THE ORIGIN WORDPRESS CMS & REDIS OBJECT CACHE  β”‚
β”‚ Redis Object Cache in RAM + HPOS Indexed MySQL Tables  β”‚
β”‚ (Executes API queries in <40ms when edge cache misses) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

When all four tiers work in concert:

  1. 98% of users hit Tier 2 (the global edge CDN), receiving pre-rendered static HTML in under 40 milliseconds.
  2. Edge cache misses hit Tier 3 (the Next.js Data Cache), resolving from pre-fetched JSON without touching WordPress.
  3. True cache purges hit Tier 4, where Redis object caching protects your origin MySQL database from query exhaustion.

Tier 3 in Depth: Granular Tag-Based Revalidation

Next.js App Router completely replaced legacy page-level caching with granular fetch cache tags.

Instead of clearing the cache for an entire URL route or rebuilding your entire static site, you assign semantic tags to your underlying data queries:

// lib/wordpress.ts
interface Post {
  id: number;
  slug: string;
  title: { rendered: string };
  content: { rendered: string };
}

export async function getPostBySlug(slug: string): Promise<Post> {
  const endpoint = `https://cms.internal.yoursite.com/wp-json/wp/v2/posts?slug=${slug}&_embed`;

  const res = await fetch(endpoint, {
    headers: {
      'User-Agent': 'NextJS-Headless-Client/2.0',
    },
    next: {
      // Assign two specific cache tags to this fetch request:
      tags: [
        `post-${slug}`,   // Surgical tag: Invalidate only this exact article
        'blog-archive',   // Collection tag: Invalidate feeds when any post updates
      ],
      // Do NOT set a time-based expiration; cache indefinitely until webhook purges
      revalidate: false,
    },
  });

  if (!res.ok) {
    throw new Error(`WordPress REST API error: ${res.status} ${res.statusText}`);
  }

  const posts: Post[] = await res.json();
  if (!posts.length) notFound();
  return posts[0];
}

By setting revalidate: false paired with cache tags, your data cache never expires on a timer.

It remains cached at the edge indefinitelyβ€”protecting your WordPress server from constant background pollingβ€”until an editor actually makes a change in WordPress.

The Webhook Bridge: Atomic Edge Purging

How does Next.js know when an editor clicks β€œUpdate” in WordPress? Through an atomic revalidation webhook.

1. The WordPress Action Hook

Add this clean, lightweight webhook trigger to your WordPress functionality plugin or child theme:

/**
 * Fire an atomic cache invalidation webhook to Next.js on post save.
 */
add_action( 'transition_post_status', 'blogitems_trigger_edge_revalidation', 10, 3 );

function blogitems_trigger_edge_revalidation( $new_status, $old_status, $post ) {
    // Only trigger for published blog posts or revisions transitioning to publish
    if ( $post->post_type !== 'post' || $new_status !== 'publish' ) {
        return;
    }

    $frontend_webhook_url = 'https://yoursite.com/api/revalidate';
    $secret = defined( 'HEADLESS_REVALIDATE_SECRET' ) ? HEADLESS_REVALIDATE_SECRET : '';

    $body = wp_json_encode( array(
        'slug'    => $post->post_name,
        'post_id' => $post->ID,
        'action'  => $new_status === $old_status ? 'update' : 'publish',
    ) );

    // Fire non-blocking asynchronous POST request to frontend
    wp_remote_post( $frontend_webhook_url . '?secret=' . $secret, array(
        'method'      => 'POST',
        'timeout'     => 5,
        'blocking'    => false, // Do not block the editor's save UI
        'headers'     => array( 'Content-Type' => 'application/json' ),
        'body'        => $body,
    ) );
}

Notice the 'blocking' => false parameter. In traditional monoliths, slow webhooks make the Gutenberg editor freeze while saving. A non-blocking asynchronous request returns control to the editor instantly while your server dispatches the payload in the background.

2. The Next.js Revalidation Route Handler

Build the receiving endpoint in Next.js App Router:

// app/api/revalidate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { revalidateTag } from 'next/cache';

export async function POST(request: NextRequest) {
  const secret = request.nextUrl.searchParams.get('secret');

  // Validate shared secret to prevent malicious cache-clearing attacks
  if (secret !== process.env.HEADLESS_REVALIDATE_SECRET) {
    return NextResponse.json({ message: 'Invalid revalidation token' }, { status: 401 });
  }

  const payload = await request.json();
  const slug = payload.slug;

  if (!slug) {
    return NextResponse.json({ message: 'Missing post slug' }, { status: 400 });
  }

  try {
    // Invalidate the exact article and the archive listing
    revalidateTag(`post-${slug}`);
    revalidateTag('blog-archive');

    return NextResponse.json({
      revalidated: true,
      purgedTags: [`post-${slug}`, 'blog-archive'],
      timestamp: Date.now(),
    });
  } catch (err) {
    return NextResponse.json({ message: 'Error revalidating cache' }, { status: 500 });
  }
}

When the editor clicks β€œUpdate,” the Next.js edge network invalidates the cache tags in under 80 milliseconds globally. The very next visitor receives fresh HTML, while the rest of your site remains cached.

Production Reality: What Breaks Under Real Load

Let’s look at the failure modes that emerge when multi-tier caching meets high-volume production traffic:

1. The Cache Stampede (Dog-Piling)

If a high-traffic breaking news post expires while receiving 1,000 requests per second, a naive caching implementation will allow all 1,000 concurrent requests to hit your WordPress REST API simultaneously to β€œregenerate” the page.

Your MySQL database connection pool will exhaust instantly, throwing Error establishing a database connection.

The Architectural Fix: Next.js App Router handles this natively through stale-while-revalidate locking. When a tag is purged, Next.js continues serving the stale version to all concurrent incoming visitors while spawning exactly one background worker to fetch fresh data from WordPress. The origin server receives a single API request, not a thousand.

2. Origin Redis Object Caching (The Unsung Hero)

If your origin WordPress database does not run persistent object caching (Redis or Memcached), every REST API request forces MySQL to execute dozens of metadata joins.

Install Redis Object Cache on your WordPress server. This stores transient query results directly in server RAM, cutting REST API response latency from 450ms down to under 45ms.

If your WordPress admin dashboard is currently sluggish, resolve that first using our blueprint on how to speed up a slow WooCommerce admin dashboard.

The Minimal Implementation Checklist

  1. Tag All Fetch Queries: Assign surgical identifiers (post-${slug}) and collection identifiers (blog-archive) to all WordPress data calls.
  2. Set Zero Background Polling: Set revalidate: false on data calls that do not change on a clock schedule.
  3. Configure Cryptographic Webhooks: Ensure both WordPress and Next.js share a secure, high-entropy secret token.
  4. Deploy Redis at Origin: Confirm that persistent object caching is active in wp-admin > Settings > Redis.
  5. Verify Edge Headers: Inspect production responses with curl -I to confirm that x-vercel-cache returns HIT across repeat visits.

The Final Verdict

Caching in headless WordPress is not about hoping your server survives traffic spikes; it is about building a deterministic, multi-tier defense system.

By combining Next.js fetch tags, non-blocking asynchronous WordPress webhooks, and origin Redis object caching, you achieve the ultimate engineering victory:

Your content editors get instant, real-time publishing without waiting for builds. Your visitors get sub-50ms global edge delivery. And your origin database stays cool, quiet, and completely protected from traffic storms.

Tags:#Next.js#WordPress#Caching#App Router#Web Performance
Blogitems

Blogitems Team

Engineering high-speed decoupled architectures, edge caching, and headless WordPress platforms delivering sub-second global speeds. Focused on making modern cloud-native web infrastructure fast and intuitive.

Blogitems Journal

Build Faster, Scale Smarter

Skip the trial-and-error, cancel the useless $29/month subscriptions, and run a blazing-fast site using tools that actually pay for themselves.