Skip to content

Production Guides & Recipes

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).

OptionTypeDefaultDescription
urlstring | undefined—Base URL of the Next.js app (required when enabled !== false)
secretstringundefinedShared HMAC-SHA256 secret (omit only with allowUnsigned: true behind a private network)
enabledbooleantrueWhen false, hooks, send(), and flush() are no-ops
loggerLogger@nexload-sdk/logger defaultCustom logger instance; a child { module: "payload-revalidate" } is created
endpointstring"/api/revalidate"Receiver path appended to url
timeoutMsnumber3000Per-attempt HTTP request timeout in milliseconds
retriesnumber2Retry count after initial failure (up to 3 total attempts on network errors, aborts, 408, 429, 5xx)

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
};

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.

By default, isPublic(doc) returns doc.deletedAt == null && doc._status !== "draft" (collections without drafts count as public unless trashed).

ChangeResolved snapshots
Draft save or autosave, including over a live docnone
Create published, publish, restore from trashnew doc
Update of a public doc (incl. rename, category move)new doc and previous doc
Unpublish, trash, hard delete of a public doclast 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}`],
});

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:

SetupWhen the batch is sentLong transactionsRollback
afterCommitPlugin() installed (default in nexloadPreset())Exactly on commit, from a runAfterCommit callbackNo capBatch is discarded
Plugin not installedWhen polling sees the transaction endBatch is dropped after 5000 ms with revalidate.batch.droppedBatch 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.

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):

  1. POST method (405)
  2. content-type: application/json (415)
  3. Request body present (400) and <= 8192 bytes UTF-8 (413, enforced while streaming)
  4. HMAC signature and ±60 s timestamp window when signed (401)
  5. Valid JSON schema, 1..50 targets, and safe tag/path patterns (400)

A batch with even one invalid target is rejected with 400 and triggers zero cache calls.

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:

# Traefik
http:
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"
# Nginx
location ^~ /api/revalidate {
return 403;
}
# Caddy
example.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.

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();
  • versions.maxPerDoc: 1: Recovering the prior published snapshot when previousDoc is a draft requires at least two retained versions.
  • localizeStatus: true: _status reaches hooks as a string on single-locale requests and as a per-locale map when locale is "all". Custom isPublic must handle both shapes; snapshot resolution and published-version recovery are not guaranteed in v1. After unpublishing or publishing a renamed draft, call await 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 createRevalidator targets a single url.
  • 5-second transaction wait cap (only without afterCommitPlugin()): Transactions open longer than 5000 ms after a hook runs drop the batch with a revalidate.batch.dropped warning; use context: { skipRevalidate: true } and send() after commit for long jobs.