Production Guides & Recipes
Sender setup
Section titled “Sender setup”Create a single revalidator instance in your Payload server and share it across collections, globals, and jobs:
import { createRevalidator } from "@nexload-sdk/payload-revalidate";
const secret = process.env.WEB_REVALIDATION_SECRET;if (!secret) { throw new Error("WEB_REVALIDATION_SECRET is required");}
export const revalidator = createRevalidator({ url: process.env.WEB_URL, secret,});When enabled is not false and url is undefined or empty, createRevalidator throws TypeError at creation time. Because secret is optional on the sender, a missing or empty WEB_REVALIDATION_SECRET silently sends unsigned requests that a signed receiver rejects with 401 (hooks only log the failure), so fail fast at startup in signed mode before passing secret. Omit secret only when the receiver uses allowUnsigned: true. Set enabled: false to disable revalidation without removing hooks (hooks(), globalHooks(), send(), and flush() become no-ops and one debug log is emitted at creation).
| Option | Type | Default | Description |
|---|---|---|---|
url | string | undefined | — | Base URL of the Next.js app (required when enabled !== false) |
secret | string | undefined | Shared HMAC-SHA256 secret (omit only with allowUnsigned: true behind a private network) |
enabled | boolean | true | When false, hooks, send(), and flush() are no-ops |
logger | Logger | @nexload-sdk/logger default | Custom logger instance; a child { module: "payload-revalidate" } is created |
endpoint | string | "/api/revalidate" | Receiver path appended to url |
timeoutMs | number | 3000 | Per-attempt HTTP request timeout in milliseconds |
retries | number | 2 | Retry count after initial failure (up to 3 total attempts on network errors, aborts, 408, 429, 5xx) |
Collection and global hooks
Section titled “Collection and global hooks”Hooks resolve public snapshots, enqueue targets into a per-transaction batch, and return doc immediately without awaiting HTTP requests or throwing on network errors.
Spread hooks(slug, rules) alongside your existing collection hooks:
import type { CollectionConfig } from "payload";import { revalidator } from "../lib/revalidator";
const productHooks = revalidator.hooks("products", { tags: ({ doc }) => ["products", `product:${doc.slug}`], paths: ({ doc }) => [`/shop/${doc.slug}`],});
export const Products: CollectionConfig = { slug: "products", hooks: { afterChange: [myExistingAfterChangeHook, ...productHooks.afterChange], afterDelete: [...productHooks.afterDelete], }, // ...fields};Use globalHooks(slug, rules) for Payload globals:
import type { GlobalConfig } from "payload";import { revalidator } from "../lib/revalidator";
const settingsHooks = revalidator.globalHooks("site-settings", { tags: ["site-settings"], paths: [{ path: "/", type: "layout" }],});
export const SiteSettings: GlobalConfig = { slug: "site-settings", hooks: { afterChange: [...settingsHooks.afterChange], }, // ...fields};Locale-scoped tags
Section titled “Locale-scoped tags”Ctx provides locales (all configured locale codes, or [] when localization is off) and locale (the active request locale, default locale when omitted, or null when localization is off; "all" is passed through as-is, in which case localized fields on doc are locale maps). Because a save in one locale can stale other locales via non-localized fields, emit tags across locales:
const productHooks = revalidator.hooks("products", { tags: ({ doc, locales }) => [ "products", ...locales.map((l) => `product:${l}:${doc.id}`), ],});Keep tag builders in a shared as const CACHE_TAGS object so Payload hooks and Next.js "use cache" / cacheTag() calls stay aligned.
Visibility and isPublic
Section titled “Visibility and isPublic”By default, isPublic(doc) returns doc.deletedAt == null && doc._status !== "draft" (collections without drafts count as public unless trashed).
| Change | Resolved snapshots |
|---|---|
| Draft save or autosave, including over a live doc | none |
| Create published, publish, restore from trash | new doc |
| Update of a public doc (incl. rename, category move) | new doc and previous doc |
| Unpublish, trash, hard delete of a public doc | last public doc |
Rules run once per resolved snapshot with doc set to that snapshot; results are unioned and deduplicated.
When previousDoc is a draft (for example, publishing after a renamed draft or unpublishing after saving a draft), the hook performs one extra version lookup (findVersions or findGlobalVersions within the same transaction) to recover the prior published snapshot. Collections or globals configured with versions: { maxPerDoc: 1 } retain only the latest version, so older published snapshots cannot be recovered.
Override isPublic in Rules for flag-based visibility (such as isActive) or collections with localizeStatus: true:
const postHooks = revalidator.hooks("posts", { isPublic: (doc) => doc.deletedAt == null && doc.isActive === true, tags: ({ doc }) => [`post:${doc.slug}`],});Batching, bulk jobs, and flush()
Section titled “Batching, bulk jobs, and flush()”Targets collected by hooks are batched per req and transactionID, deduplicated, and sent after the transaction commits. How the package learns about the commit depends on your config:
| Setup | When the batch is sent | Long transactions | Rollback |
|---|---|---|---|
afterCommitPlugin() installed (default in nexloadPreset()) | Exactly on commit, from a runAfterCommit callback | No cap | Batch is discarded |
| Plugin not installed | When polling sees the transaction end | Batch is dropped after 5000 ms with revalidate.batch.dropped | Batch is sent anyway |
Install the plugin from @nexload-sdk/payload-hooks for production:
import { afterCommitPlugin } from "@nexload-sdk/payload-hooks";
export default buildConfig({ plugins: [afterCommitPlugin()], // ...});For bulk operations, pass context: { skipRevalidate: true } to skip per-document hooks, then call await revalidator.send(...) only after the owning transaction has committed (when a top-level Local API call without an open-transaction req returns, or after await commitTransaction(req) if you opened the transaction with initTransaction):
await payload.update({ collection: "products", where: { category: { equals: categoryId } }, data: { discountPercent: 10 }, context: { skipRevalidate: true },});
await revalidator.send({ tags: ["products", `category:${categorySlug}`],});Never call revalidator.send(...) from inside a hook or someone else’s transaction (such as a job step sharing req): unlike hooks, send() posts immediately before commit and throws on failure (TypeError on invalid targets or request errors on HTTP/network failure).
await revalidator.flush() waits for in-flight HTTP sends. Without afterCommitPlugin() it also waits for pending transaction waiters (bounded by the 5000 ms wait cap). With the plugin, a batch whose transaction has not committed yet is not waited for, so call flush() after the write returns. Use it in tests, CLI scripts, or Next.js after() / waitUntil(). Never call flush() from inside a hook: without the plugin the database commit waits on the hook while flush() waits on the transaction, which hits the 5000 ms cap and drops the batch; with the plugin it returns before anything was sent.
Receiver (signed and unsigned)
Section titled “Receiver (signed and unsigned)”Mount createRevalidateHandler at app/api/revalidate/route.ts in your Next.js App Router app (Node.js runtime; do not set runtime = "edge").
// Signed mode (publicly reachable Next.js or separate hosts)import { createRevalidateHandler } from "@nexload-sdk/payload-revalidate/next";
export const POST = createRevalidateHandler({ secret: process.env.WEB_REVALIDATION_SECRET!,});During secret rotation, pass secret: [newSecret, oldSecret]; the receiver accepts a valid signature from any listed key.
For private Docker-internal deployments where /api/revalidate is blocked at the public reverse proxy:
import { createRevalidateHandler } from "@nexload-sdk/payload-revalidate/next";
export const POST = createRevalidateHandler({ allowUnsigned: true });createRevalidateHandler throws TypeError at creation if neither secret nor allowUnsigned: true is provided (including secret: undefined), or if both are specified.
The receiver validates in order before calling revalidateTag(tag, "max") or revalidatePath(path, type):
POSTmethod (405)content-type: application/json(415)- Request body present (
400) and<= 8192bytes UTF-8 (413, enforced while streaming) - HMAC signature and
±60s timestamp window when signed (401) - Valid JSON schema,
1..50targets, and safe tag/path patterns (400)
A batch with even one invalid target is rejected with 400 and triggers zero cache calls.
Proxy blocking for unsigned mode
Section titled “Proxy blocking for unsigned mode”In allowUnsigned: true mode, anyone who can reach /api/revalidate can trigger cache invalidation. Block public access to /api/revalidate at your reverse proxy while keeping the internal container URL reachable from Payload:
# Traefikhttp: routers: web-block-revalidate: rule: "Host(`example.com`) && PathPrefix(`/api/revalidate`)" priority: 100 service: block-service middlewares: - deny-revalidate middlewares: deny-revalidate: ipAllowList: sourceRange: - "127.0.0.1/32"# Nginxlocation ^~ /api/revalidate { return 403;}# Caddyexample.com { @revalidate path /api/revalidate /api/revalidate/* respond @revalidate 403
reverse_proxy web:3000}Verify that a public POST https://example.com/api/revalidate returns 403 or 404 while the CMS container can still reach the internal service URL.
Testing
Section titled “Testing”Use createTestRevalidator from @nexload-sdk/payload-revalidate/testing to capture dispatched WireBatch objects in memory with zero network calls, then await revalidator.flush():
import { createTestRevalidator } from "@nexload-sdk/payload-revalidate/testing";
const { revalidator, calls, clear } = createTestRevalidator();// Run collection operations using `revalidator`, then:await revalidator.flush();Limitations
Section titled “Limitations”versions.maxPerDoc: 1: Recovering the prior published snapshot whenpreviousDocis a draft requires at least two retained versions.localizeStatus: true:_statusreaches hooks as a string on single-locale requests and as a per-locale map when locale is"all". CustomisPublicmust handle both shapes; snapshot resolution and published-version recovery are not guaranteed in v1. After unpublishing or publishing a renamed draft, callawait revalidator.send({ tags, paths })with old targets after the owning transaction commits.- No durable delivery: Batches live in memory per transaction with bounded retries; process crashes or exhausted retries drop and log the batch.
- No multi-target fan-out: Each
createRevalidatortargets a singleurl. - 5-second transaction wait cap (only without
afterCommitPlugin()): Transactions open longer than 5000 ms after a hook runs drop the batch with arevalidate.batch.droppedwarning; usecontext: { skipRevalidate: true }andsend()after commit for long jobs.