Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Last active September 25, 2026 19:53
Show Gist options
  • Select an option

  • Save jasonbahl/29fed7353b205f2e4570bf75d216075a to your computer and use it in GitHub Desktop.

Select an option

Save jasonbahl/29fed7353b205f2e4570bf75d216075a to your computer and use it in GitHub Desktop.
On-demand revalidation for a headless front end, driven by WPGraphQL Smart Cache purge events

On-demand revalidation from WPGraphQL Smart Cache purge events

Tells a decoupled front end to rebuild affected pages when content changes, by listening to the purge events WPGraphQL Smart Cache already emits.

Used in production on the CMS behind wpgraphql.com.

The problem

A front end using ISR (Next.js, or anything with a revalidate window) serves a cached page until two things happen: the window lapses, and something requests the page. On a low-traffic URL that can be a long time. Worse, a deleted post keeps rendering at its old address until someone asks for it.

Publishing and then refreshing to find the old version is the usual symptom.

Why hook Smart Cache instead of save_post

Smart Cache has already done the hard part. By the time it emits a purge it has decided the change is public and cache-relevant, skipped revisions and autosaves, and worked out which nodes were touched, including the author and terms of an edited post, not just the post.

Hooking save_post and deleted_post directly means reimplementing that, and you will forget something. The first version of this snippet did, and only revalidated posts, leaving category, tag and author archives stale.

No plugin patch is required. graphql_purge is a public action and the keys are plain Relay::toGlobalId() values, which is base64("type:id").

There is a more general purge webhook proof of concept that sends configurable payloads for any purge event. That is the better shape for a real feature, but it does patch the plugin. This is the small version that runs as a snippet.

What Smart Cache gives you, and what it does not

It emits a cache key, never a URL, because it knows nothing about your front end's routes. Translating keys into paths is the only real work here:

key meaning paths sent
base64("post:123") a single post of any type its permalink path, plus the shared pages
base64("term:4") a term get_term_link()
base64("user:7") a user get_author_posts_url()
list:<type> a collection changed the shared pages
graphql:Query purge everything the shared pages
skipped:<type> key header was truncated ignored, the node purges under its own key

"The shared pages" defaults to / and /blog, since a post appears on more than its own URL. Adjust with the revalidate_always_paths filter.

Trailing slashes matter, and fail silently

WordPress permalinks end in a slash. Next.js defaults to trailingSlash: false and 308s /foo/ to /foo, so its cache is keyed on the unslashed form.

Send the slashed path and the revalidate endpoint will cheerfully report {"revalidated":["/blog/"]} for a path that is not a route. It looks like it works and nothing is rebuilt. This snippet normalizes every path to the unslashed form, leaving / alone. Flip that if your front end sets trailingSlash: true.

On graphql:Query this rebuilds entry points rather than trying to enumerate the site, which would exceed any sane request size.

Batching

A single edit emits several purges: the node, each list it belongs to, its author, its terms. The snippet queues paths and sends one deduplicated, non-blocking request on shutdown, so an editor never waits on the front end and you do not get a dozen HTTP calls per save.

The race, and why it delays

If anything caches between your front end and WordPress (a CDN, a GraphQL proxy like RadiQL, a Varnish layer), that thing also has to be purged when content changes. Its purge and this revalidation both leave WordPress on shutdown, fire and forget, with no ordering between them.

Revalidate too early and the sequence is:

  1. WordPress saves, and fires purges
  2. This snippet tells the front end to rebuild
  3. The front end refetches, through a proxy that has not been purged yet
  4. The front end caches the stale response and gives it a fresh lease

That is worse than doing nothing. Without the revalidation the page would have expired on its own schedule; now it will sit there, confidently wrong, for a full cache lifetime. I watched exactly this happen: the page rebuilt two seconds before the save timestamp and then held the old title while every layer underneath it was correct.

So the send is deferred by revalidate_delay_seconds, 15 by default, through wp_schedule_single_event. Cron granularity means it can run later than asked, which costs freshness but never correctness. Set it to 0 with the filter if your front end talks to WordPress directly with nothing in between.

A delay is a workaround, not a fix. The real fix belongs in whatever sits between: it knows when its own purge has landed, and it should be the thing that triggers the rebuild afterwards. Nothing inside WordPress can know that, because a fire and forget POST tells you nothing about what happened at the other end.

Setup

  1. Your front end needs an endpoint that accepts {"paths": ["/some/path/"]} and calls its own revalidation API. Next.js exposes res.revalidate(path).
  2. Set REVALIDATE_ENDPOINT and REVALIDATE_SECRET. The secret must match whatever the endpoint checks, and the endpoint should reject every request when it is unset rather than defaulting to open.
  3. Paste into a snippets plugin with scope "run everywhere", or use as an mu-plugin. With Code Snippets, omit the opening <?php tag.

The header name is x-wpgraphql-revalidate-secret. Change it in the snippet if your endpoint expects something else.

Checking it works

Edit a published post, then request it on the front end and look at the cache header. On Vercel a x-vercel-cache: HIT with a very low age right after saving means the page was just rebuilt. Watching whether a new post appears on the archive immediately, rather than minutes later, is the easier test.

/**
* Tell a Next.js front end to revalidate when WPGraphQL Smart Cache purges.
*
* Paste into a snippets plugin with scope "run everywhere", or use as an
* mu-plugin. With Code Snippets, omit the opening <?php tag.
*
* Without this, a decoupled front end using ISR serves stale pages until its
* revalidate window lapses AND something requests the page. On a low-traffic
* URL that can be a long time, and a deleted post keeps rendering at its old
* address in the meantime.
*
* This hooks Smart Cache's `graphql_purge` rather than WordPress's save and
* delete hooks, so it inherits all of Smart Cache's work: it already decided
* the change is public and cache-relevant, and it already tracks terms, users,
* menus and media, not just posts. Smart Cache emits a cache KEY rather than a
* URL, so the only job left here is turning keys into paths.
*
* No plugin patch needed. `graphql_purge` is a public action and the keys are
* plain `Relay::toGlobalId()` values, which is `base64("type:id")`.
*
* A more general purge-webhook approach lives at
* https://gist.github.com/jasonbahl/684f4a39ee7988086559df67d1bdab35
*/
define( 'REVALIDATE_ENDPOINT', 'https://example.com/api/revalidate' );
// The same value as WPGRAPHQL_REVALIDATE_SECRET in the front end's environment.
define( 'REVALIDATE_SECRET', '' );
/**
* Paths that are affected by any content change.
*
* A post appears on more than its own URL, so revalidating only the permalink
* leaves the archive and the home page stale.
*/
function revalidate_always_paths() {
return apply_filters( 'revalidate_always_paths', [ '/', '/blog' ] );
}
/**
* Whether to log what is queued and what the front end reported back.
*
* Failures are always logged. This only controls the chatty lines: the paths
* in each batch and the endpoint's success count. Turn it on while wiring this
* up, because a revalidation that silently does nothing looks exactly like one
* that worked.
*
* add_filter( 'revalidate_debug', '__return_true' );
*/
function revalidate_debug() {
return (bool) apply_filters( 'revalidate_debug', defined( 'WP_DEBUG' ) && WP_DEBUG );
}
function revalidate_log( $message ) {
if ( ! revalidate_debug() ) {
return;
}
error_log( '[revalidate] ' . $message );
}
/**
* Path portion of a URL, or null.
*
* Only the path is sent. get_permalink() and friends build on home_url(), so
* on a headless install where home_url points at the front end these are
* already the right origin, but the front end should decide what a path maps
* to regardless.
*/
function revalidate_path( $url ) {
if ( ! $url || is_wp_error( $url ) ) {
return null;
}
$path = wp_parse_url( $url, PHP_URL_PATH );
if ( ! $path ) {
return null;
}
// Match the front end's route exactly. WordPress permalinks end in a
// slash; Next.js defaults to `trailingSlash: false` and 308s `/foo/` to
// `/foo`, so its cache is keyed on the unslashed form. Sending the slashed
// path is the worst kind of wrong here: the endpoint happily reports
// `revalidated` for a path that is not a route, so it looks like it works
// while nothing is rebuilt. Flip this if your front end sets
// `trailingSlash: true`.
$path = '/' . trim( $path, '/' );
return $path;
}
/**
* Archive paths a post appears on: its terms and its author.
*
* Smart Cache purges term and user nodes when a RELATIONSHIP changes, but a
* plain content edit only purges the post node itself. Without this, renaming
* a post never reaches /category/x or /author/y, and those pages sit on the
* old title until their ISR window lapses and someone requests them.
*
* Filterable because a post with many terms can push a batch toward the
* endpoint's 100 path limit.
*/
function revalidate_archive_paths_for_post( $post ) {
if ( ! apply_filters( 'revalidate_post_archives', true, $post ) ) {
return [];
}
$paths = [];
foreach ( get_object_taxonomies( $post->post_type, 'objects' ) as $taxonomy ) {
if ( empty( $taxonomy->public ) ) {
continue;
}
$terms = get_the_terms( $post, $taxonomy->name );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
continue;
}
foreach ( $terms as $term ) {
$paths[] = revalidate_path( get_term_link( $term ) );
}
}
if ( ! empty( $post->post_author ) ) {
$paths[] = revalidate_path( get_author_posts_url( (int) $post->post_author ) );
}
return array_values( array_filter( $paths ) );
}
/**
* Turn one Smart Cache key into the paths it affects.
*
* Keys come in four shapes:
* - base64("post:123") / ("term:4") / ("user:7") for a single node
* - "list:<type>" when a collection of that type changed
* - "skipped:<type>" when the key header was truncated, no new information
* - "graphql:Query" a purge-everything
*
* @param string $key
* @return string[]
*/
function revalidate_paths_for_key( $key ) {
if ( ! is_string( $key ) || '' === $key ) {
return [];
}
// Truncated-header bookkeeping, the node itself is purged separately.
if ( 0 === strpos( $key, 'skipped:' ) ) {
return [];
}
// Purge everything. Rebuild the entry points rather than trying to
// enumerate the site, which would blow past the endpoint's path limit.
if ( 'graphql:Query' === $key ) {
return revalidate_always_paths();
}
if ( 0 === strpos( $key, 'list:' ) ) {
// A collection changed. The individual node that caused it is purged
// under its own key, so this only needs the shared pages.
return revalidate_always_paths();
}
// Single node. Relay global IDs are base64("type:id").
$decoded = base64_decode( $key, true );
if ( false === $decoded || false === strpos( $decoded, ':' ) ) {
return [];
}
list( $type, $id ) = array_pad( explode( ':', $decoded, 2 ), 2, null );
$id = absint( $id );
if ( ! $id ) {
return [];
}
$paths = [];
switch ( $type ) {
case 'post':
$post = get_post( $id );
// Only content the front end actually renders. Revisions and
// autosaves never reach it.
if ( $post && ! wp_is_post_revision( $post ) ) {
$type_object = get_post_type_object( $post->post_type );
if ( $type_object && $type_object->public ) {
$paths[] = revalidate_path( get_permalink( $id ) );
$paths = array_merge( $paths, revalidate_always_paths() );
$paths = array_merge( $paths, revalidate_archive_paths_for_post( $post ) );
}
}
break;
case 'term':
$paths[] = revalidate_path( get_term_link( $id ) );
break;
case 'user':
$paths[] = revalidate_path( get_author_posts_url( $id ) );
break;
}
$paths = array_values( array_filter( $paths ) );
revalidate_log( sprintf( 'key %s -> %s', $key, $paths ? implode( ', ', $paths ) : '(none)' ) );
return $paths;
}
/**
* Where pending paths live between the edit request and the cron flush.
*
* An option rather than the in-request queue alone, so that several edits made
* before the flush runs all ride the same rebuild. See the scheduling note in
* the shutdown handler for why that matters.
*/
const REVALIDATE_PENDING_OPTION = 'revalidate_pending_paths';
/**
* Queue paths for this request, flushed once on shutdown.
*
* Smart Cache emits several purges for a single edit: the node, the lists it
* belongs to, its author, its terms. Batching means one HTTP call with a
* deduplicated list rather than a dozen.
*/
function revalidate_queue( $paths = null ) {
static $queue = [];
if ( null === $paths ) {
return $queue;
}
foreach ( (array) $paths as $path ) {
if ( is_string( $path ) && '' !== $path && ! in_array( $path, $queue, true ) ) {
$queue[] = $path;
}
}
return $queue;
}
add_action(
'graphql_purge',
function ( $key ) {
revalidate_queue( revalidate_paths_for_key( $key ) );
},
10,
1
);
/**
* How long to wait before telling the front end to rebuild.
*
* This exists because of a race. If a CDN or proxy sits between the front end
* and WordPress, its purge and this revalidation both leave WordPress on
* `shutdown`, fire and forget, with no ordering between them. Revalidate too
* early and the front end refetches through a proxy that has not been purged
* yet, caches the stale response, and gives it a fresh lease. That is worse
* than not revalidating at all: without this the page would have expired
* normally, and now it will not.
*
* Set to 0 if the front end talks to WordPress directly.
*/
function revalidate_delay_seconds() {
return (int) apply_filters( 'revalidate_delay_seconds', 15 );
}
const REVALIDATE_CRON_HOOK = 'revalidate_send_paths';
/**
* Add paths to the pending set. Returns the merged set.
*/
function revalidate_add_pending( array $paths ) {
$pending = get_option( REVALIDATE_PENDING_OPTION, [] );
if ( ! is_array( $pending ) ) {
$pending = [];
}
$merged = array_values( array_unique( array_merge( $pending, $paths ) ) );
update_option( REVALIDATE_PENDING_OPTION, $merged, false );
return $merged;
}
/**
* Take the pending set and clear it in one step.
*/
function revalidate_take_pending() {
$pending = get_option( REVALIDATE_PENDING_OPTION, [] );
delete_option( REVALIDATE_PENDING_OPTION );
return is_array( $pending ) ? $pending : [];
}
add_action(
REVALIDATE_CRON_HOOK,
function () {
$paths = revalidate_take_pending();
// Cron is not user facing, so this call can block long enough to read
// the response and report what the front end actually did.
revalidate_send( $paths, true );
},
10,
0
);
/**
* Hand off at the end of the request.
*/
add_action(
'shutdown',
function () {
$paths = revalidate_queue();
if ( empty( $paths ) ) {
return;
}
$delay = revalidate_delay_seconds();
if ( $delay <= 0 ) {
revalidate_send( $paths );
return;
}
// Accumulate into the pending set, then schedule ONE flush with no
// arguments.
//
// wp_schedule_single_event() refuses an event whose hook and args match
// one already scheduled within ten minutes, keyed on
// md5( serialize( $event->args ) ). Passing the paths as args would
// make that key change per edit, so editing two different posts would
// book two rebuilds, while editing the SAME post twice would produce an
// identical key and the second edit would be silently dropped. Neither
// is what we want.
//
// With no args the key is constant, so one pending flush coalesces
// every edit made before it runs, across posts. That is correct rather
// than merely cheap: revalidation refetches whatever WordPress holds at
// send time, not at queue time, so a single rebuild already reflects
// every edit that landed before it.
revalidate_add_pending( $paths );
$scheduled = wp_schedule_single_event( time() + $delay, REVALIDATE_CRON_HOOK );
if ( false !== $scheduled ) {
return;
}
// Core refused it. Usually that means a flush is already pending and
// will carry these paths, which is the coalescing above working.
//
// The exception is an event stuck in the past, which happens when cron
// is not draining. Core counts ALL past identical events as duplicates
// when scheduling a near-future one, so a single stuck entry would
// block every later revalidation, silently and indefinitely.
$next = wp_next_scheduled( REVALIDATE_CRON_HOOK );
if ( $next && $next >= time() ) {
revalidate_log( 'flush already pending, paths merged into it' );
return;
}
error_log( '[revalidate] no usable scheduled event, sending immediately' );
revalidate_send( revalidate_take_pending() );
}
);
/**
* POST the paths to the front end.
*
* @param string[] $paths Paths to rebuild.
* @param bool $blocking Whether to wait for and report the response. Safe
* from cron, never from a request an editor is
* waiting on.
*/
function revalidate_send( array $paths, $blocking = false ) {
if ( empty( $paths ) || ! REVALIDATE_SECRET || ! REVALIDATE_ENDPOINT ) {
return;
}
// The endpoint accepts at most 100 paths per call.
$paths = array_slice( array_values( array_unique( $paths ) ), 0, 100 );
revalidate_log( sprintf( 'sending %d paths: %s', count( $paths ), implode( ', ', $paths ) ) );
$response = wp_remote_post(
REVALIDATE_ENDPOINT,
[
'headers' => [
'Content-Type' => 'application/json',
'x-wpgraphql-revalidate-secret' => REVALIDATE_SECRET,
],
'body' => wp_json_encode( [ 'paths' => $paths ] ),
'timeout' => $blocking ? 15 : 5,
// Do not make an editor wait on the front end to rebuild.
'blocking' => (bool) $blocking,
]
);
if ( is_wp_error( $response ) ) {
error_log( '[revalidate] request failed: ' . $response->get_error_message() );
return;
}
if ( ! $blocking ) {
return;
}
$code = (int) wp_remote_retrieve_response_code( $response );
$raw = wp_remote_retrieve_body( $response );
if ( 200 !== $code ) {
error_log( sprintf( '[revalidate] endpoint returned %d: %s', $code, $raw ) );
return;
}
$body = json_decode( $raw, true );
// A path the front end could not rebuild is the failure mode this whole
// snippet exists to prevent, and it is invisible unless we look. A path
// that is not a route is reported as revalidated, so an empty `failed`
// list is necessary but not sufficient: check the page too.
if ( ! empty( $body['failed'] ) && is_array( $body['failed'] ) ) {
foreach ( $body['failed'] as $failure ) {
error_log(
sprintf(
'[revalidate] path failed: %s (%s)',
isset( $failure['path'] ) ? $failure['path'] : '?',
isset( $failure['error'] ) ? $failure['error'] : '?'
)
);
}
}
revalidate_log(
sprintf(
'endpoint rebuilt %d, failed %d',
isset( $body['revalidated'] ) ? count( (array) $body['revalidated'] ) : 0,
isset( $body['failed'] ) ? count( (array) $body['failed'] ) : 0
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment