Revalidate Next.js pages after Wagtail publishes
Send an authenticated POST after the CMS transaction commits. Revalidate the public path and register receivers for concrete Wagtail page models.
A headless Wagtail site can notify Next.js when a page is published or unpublished. The important boundary is the database commit: if Next.js fetches the CMS before the transaction commits, it can regenerate the old page successfully and cache stale content again.
This example keeps the Pages Router ISR API, which remains supported. It assumes pages use getStaticProps and the deployment runs a Next.js server with ISR support. It does not apply to a static export. In the App Router, use revalidatePath in a Route Handler instead; that API has different revalidation timing.
Accept one authenticated POST
Create pages/api/revalidate.ts in the Next.js application:
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method !== "POST") {
res.setHeader("Allow", "POST");
return res.status(405).json({ error: "Method not allowed" });
}
const secret = process.env.CMS_REVALIDATE_TOKEN;
if (!secret || req.headers.authorization !== `Bearer ${secret}`) {
return res.status(401).json({ error: "Unauthorized" });
}
const path = req.body?.path;
if (typeof path !== "string" ||
!/^\/(?:[a-z0-9_-]+\/)*[a-z0-9_-]*\/?$/i.test(path) ||
path.length > 1024) {
return res.status(400).json({ error: "Invalid page path" });
}
try {
await res.revalidate(path);
return res.json({ revalidated: true });
} catch (error) {
console.error("Page revalidation failed", error);
return res.status(500).json({ error: "Revalidation failed" });
}
}
The path grammar deliberately permits only simple slash-separated slugs. Adapt it if your public URLs use Unicode or another routing scheme. Send the actual Next.js page path, not a CMS admin URL or an external URL. The missing-secret check prevents an unconfigured endpoint from accepting a missing credential.
Set the same nonempty secret on both applications. In Django settings, provide FRONTEND_REVALIDATION_URL as the full HTTPS endpoint and FRONTEND_REVALIDATION_TOKEN as that secret. Keep them server-side.
Notify after commit
With requests available in your Django application, create content/signals.py:
import logging
from functools import partial
from django.conf import settings
from django.db import transaction
from django.dispatch import receiver
from wagtail.signals import page_published, page_unpublished
import requests
logger = logging.getLogger(__name__)
def notify_frontend(path):
try:
response = requests.post(
settings.FRONTEND_REVALIDATION_URL,
json={"path": path},
headers={
"Authorization": f"Bearer {settings.FRONTEND_REVALIDATION_TOKEN}"
},
timeout=(3, 10),
)
response.raise_for_status()
except requests.RequestException:
logger.exception("Frontend revalidation failed for %s", path)
@receiver(page_published)
@receiver(page_unpublished)
def page_changed(sender, instance, **kwargs):
parts = instance.get_url_parts()
if parts is not None:
transaction.on_commit(partial(notify_frontend, parts[2]))
This assumes Wagtail’s site-relative path matches the frontend route. Map it explicitly if the frontend adds a locale prefix or uses different slugs. Avoid sender=Page: a receiver restricted to that class will miss signals sent with concrete subclasses. These unrestricted receivers handle all page models.
Load the receivers from content/apps.py:
from django.apps import AppConfig
class ContentConfig(AppConfig):
name = "content"
def ready(self):
from . import signals
Use "content.apps.ContentConfig" in INSTALLED_APPS. The signals import registers the handlers when Django starts.
Check failure and invalidation scope
Test publishing and unpublishing against a production build of Next.js. On unpublish, getStaticProps must return notFound: true when the CMS no longer exposes the page. A CMS client that serves stale cached data can otherwise resurrect it.
The synchronous notifier bounds network waits and logs delivery failure, but does not retry. For guaranteed delivery, persist an event in the publishing transaction and let a worker retry it after commit. Revalidate listing pages as well if publication changes them; page moves also need invalidation of the old path, which these two signals alone do not track.
See Next.js Pages Router ISR, Wagtail publishing signals and Django commit callbacks. For the cache layers involved, read HTTP caching.