gecut

payload revalidate

by gecut
nexload-sdk
Other
v3
>=3.85.0 <4.0.0
MIT

Overview

Summary generated from the README

Provides collection and global hooks that collect cache tags and paths per transaction and post them to a Next.js receiver that calls revalidateTag and revalidatePath. Requests are signed with HMAC-SHA256 and retried on failure. Requires Payload 3.85 or newer and, for the receiver, Next.js 16 on the Node.js runtime.

Features

  • Collection and global hooks that resolve public snapshots and batch tags and paths per transaction
  • Signed requests with HMAC-SHA256, timestamp window and secret rotation support
  • Next.js route handler that validates method, content type, size, signature and targets before revalidating
  • Optional commit-exact delivery that skips batches after a rollback
  • Manual send and flush for bulk jobs with a skip flag in request context
  • In-memory test revalidator that makes no network calls

Use cases

  • Invalidate Next.js cached pages when editors publish, rename or unpublish Payload documents
  • Revalidate locale-specific tags across all configured locales after a save
  • Refresh storefront caches after bulk updates by sending one batch once the write has committed

From the author

Per-transaction Payload CMS cache revalidation hooks and Next.js route handler.

Installation

npm i @nexload-sdk/payload-revalidate

3

Stars

0

Forks

0

Open Issues

Today

Last Updated

202

Weekly Downloads

v1.0.0

npm Version

527.3 KB

Unpacked Size

2

Dependencies

Repository stars

3+2 since Sep 6

Show data
Repository stars by day (UTC)
DateStars
Dec 5, 20263
Dec 4, 20263
Dec 3, 20263
Dec 2, 20263
Dec 1, 20263
Nov 30, 20263
Nov 29, 20263
Nov 28, 20263
Nov 27, 20263
Nov 26, 20263
Nov 25, 20263
Nov 24, 20263
Nov 23, 20263
Nov 22, 20263
Nov 21, 20263
Nov 20, 20263
Nov 19, 20263
Nov 18, 20263
Nov 17, 20262
Nov 16, 20262
Nov 15, 20262
Nov 14, 20262
Nov 13, 20262
Nov 12, 20262
Nov 11, 20262
Nov 10, 20262
Nov 9, 20262
Nov 8, 20262
Nov 7, 20262
Nov 6, 20262
Nov 5, 20262
Nov 4, 20262
Nov 3, 20262
Nov 2, 20262
Nov 1, 20262
Oct 31, 20262
Oct 30, 20262
Oct 29, 20262
Oct 28, 20262
Oct 27, 20262
Oct 26, 20262
Oct 25, 20262
Oct 24, 20262
Oct 23, 20262
Oct 22, 20262
Oct 21, 20262
Oct 20, 20262
Oct 19, 20262
Oct 18, 20262
Oct 17, 20261
Oct 16, 20261
Oct 15, 20261
Oct 14, 20261
Oct 13, 20261
Oct 12, 20261
Oct 11, 20261
Oct 10, 20261
Oct 9, 20261
Oct 8, 20261
Oct 7, 20261
Oct 6, 20261
Oct 5, 20261
Oct 4, 20261
Oct 3, 20261
Oct 2, 20261
Oct 1, 20261
Sep 30, 20261
Sep 29, 20261
Sep 28, 20261
Sep 27, 20261
Sep 26, 20261
Sep 25, 20261
Sep 24, 20261
Sep 23, 20261
Sep 22, 20261
Sep 21, 20261
Sep 20, 20261
Sep 19, 20261
Sep 18, 20261
Sep 17, 20261
Sep 16, 20261
Sep 15, 20261
Sep 14, 20261
Sep 13, 20261
Sep 12, 20261
Sep 11, 20261
Sep 10, 20261
Sep 9, 20261
Sep 8, 20261
Sep 7, 20261
Sep 6, 20261

Shared by 8 plugins in gecut/nexload-sdk.

npm weekly downloads

Trends appear after 7 days of data. Collecting since Dec 5 — 1 daily snapshot so far.

Each point is npm's rolling 7-day download count.

Health Score

75/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1086380959-payload-revalidate.svg)](https://payloaddirectory.dev/plugins/1086380959-payload-revalidate)
HTML
<a href="https://payloaddirectory.dev/plugins/1086380959-payload-revalidate"><img src="https://payloaddirectory.dev/badge/1086380959-payload-revalidate.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Oct 30, 2025Published Dec 3, 2026

README

@nexload-sdk/payload-revalidate

Per-transaction Payload CMS cache revalidation hooks and Next.js route handler.

npm version License: MIT Module: ESM + CJS Runtime: Node | Payload 3 | Next 16

Table of contents

Install

pnpm add @nexload-sdk/payload-revalidate payload
# or
npm install @nexload-sdk/payload-revalidate payload

In your Next.js storefront app (for the ./next subpath):

pnpm add @nexload-sdk/payload-revalidate next
PackageRangeRequired / Optional
payload>=3.85.0 <4.0.0Required
next>=16.0.0 <17Optional (@nexload-sdk/payload-revalidate/next only)

Runtime constraints

  • Module format: Dual ESM (import) and CJS (require).
  • Sender (@nexload-sdk/payload-revalidate): Runs in Node.js on the Payload CMS server. The root entry never imports next or next/*.
  • Receiver (@nexload-sdk/payload-revalidate/next): Runs in the Next.js Node.js runtime (next/cache). Do not configure the route handler with runtime = "edge".
  • Testing (@nexload-sdk/payload-revalidate/testing): In-memory test revalidator with zero network calls.

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

If enabled is not false and url is undefined or empty, createRevalidator throws TypeError at creation time. Because the sender's secret is optional, a missing or empty WEB_REVALIDATION_SECRET silently makes the CMS send 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. Leave secret out only when the receiver uses allowUnsigned: true. Set enabled: false in environments where revalidation should be disabled without removing hooks.

RevalidatorOptions

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

Collection and global hooks

Hooks resolve public snapshots, collect targets into a per-transaction batch, and return immediately without awaiting HTTP requests or throwing on network errors.

Composing with existing hooks

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

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}`),
  ],
});

When slugs are localized, build cross-locale tags from a non-localized identifier or resolve each locale's slug yourself.

Global hooks

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

Visibility and isPublic

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 / 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 in those cases.

Custom isPublic and localizeStatus

Override isPublic in Rules for flag-based visibility (such as isActive) or collections with localizeStatus: true (where _status is a per-locale map rather than a string):

const postHooks = revalidator.hooks("posts", {
  isPublic: (doc) => doc.deletedAt == null && doc.isActive === true,
  tags: ({ doc }) => [`post:${doc.slug}`],
});

Bulk jobs and flush()

Bulk jobs with skipRevalidate

Skip per-document hooks inside bulk operations with req.context.skipRevalidate = true, then call await revalidator.send(...) only after the transaction that owns the write has committed: for a top-level Local API call that does not receive a req with an open transaction (as below), that is when the call returns, or after await commitTransaction(req) if you pass a req whose transaction you opened yourself (initTransaction). If your code runs inside someone else's transaction (for example inside a hook or a job step sharing req), do not call send() there at all.

await payload.update({
  collection: "products",
  where: { category: { equals: categoryId } },
  data: { discountPercent: 10 },
  context: { skipRevalidate: true },
});

await revalidator.send({
  tags: ["products", `category:${categorySlug}`],
});

[!CAUTION] 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 if any target in targets is invalid, or a request error if delivery fails), which would fail the save. Call send() only after the transaction that owns the write 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 yourself (initTransaction).

flush()

await revalidator.flush() waits for all pending transaction waiters and in-flight HTTP sends (bounded by the 5000 ms wait cap). With afterCommitPlugin() installed, it waits only for sends already started by a commit. Use it in tests, CLI scripts, or Next.js after() / waitUntil().

[!CAUTION] Never call flush() from a hook. Inside an open transaction, the database commit waits on the hook while flush() waits on the transaction to clear, causing flush() to hit the 5000 ms wait cap and drop the batch.

Exact commit timing with afterCommitPlugin

Without extra setup, the sender polls req.transactionID to learn that a transaction ended, and it cannot tell a commit from a rollback. Install afterCommitPlugin() from @nexload-sdk/payload-hooks (or use nexloadPreset(), which installs it) to make batches commit-exact:

import { afterCommitPlugin } from "@nexload-sdk/payload-hooks";

export default buildConfig({
  plugins: [afterCommitPlugin()],
  // ...
});

With the plugin installed on the Payload instance, a batch created inside a transaction is:

  • sent exactly when the transaction commits (the HTTP send starts after the commit and the commit does not wait for it);
  • never sent after a rollback (the batch is discarded silently, with no revalidate.batch.dropped warning);
  • not subject to the 5-second transaction wait cap, so long transactions still revalidate.

Requests without a transaction behave the same with or without the plugin. flush() waits for in-flight sends; it does not wait for transactions that have not committed yet.

Receiver

Mount createRevalidateHandler at app/api/revalidate/route.ts in your Next.js App Router app:

// 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 an array of secrets (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 or revalidatePath:

  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 every tag/path matches the safe pattern (400)

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

Security

[!WARNING] In allowUnsigned: true mode, anyone who can reach /api/revalidate can trigger cache invalidation and force database load. You must block public access to /api/revalidate at your reverse proxy while keeping the internal container URL reachable from Payload.

Traefik

Block /api/revalidate on the public router using a middleware or lower-priority deny router:

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

Return 403 (or 404) for /api/revalidate in the public server block:

location ^~ /api/revalidate {
  return 403;
}

Caddy

Respond with 403 before reverse_proxy in your Caddyfile:

example.com {
  @revalidate path /api/revalidate /api/revalidate/*
  respond @revalidate 403

  reverse_proxy web:3000
}

Verify with curl

Confirm a public POST is blocked by the proxy (403 or 404), while the CMS container can still reach the internal service URL:

# Public edge (must return 403 or 404)
curl -i -X POST https://example.com/api/revalidate \
  -H "content-type: application/json" \
  -d '{"tags":["products"]}'

Shared tag map pattern

Keep tag builders in a shared contracts package as an as const object so Payload hooks and Next.js "use cache" / cacheTag() calls cannot drift:

export const CACHE_TAGS = {
  products: "products",
  product: (locale: string, slug: string) => `product:${locale}:${slug}`,
  siteSettings: "site-settings",
} as const;

Wire format

Requests are sent as POST {url}{endpoint} with:

  • content-type: application/json
  • x-revalidate-timestamp: Unix seconds as a decimal string (TIMESTAMP_HEADER)
  • x-revalidate-signature: base64url HMAC-SHA256 (no padding) over `${timestamp}.${rawBody}` (SIGNATURE_HEADER, signed mode only)
  • x-trace-id: trace header from @nexload-sdk/logger

Body JSON:

{
  "tags": ["products", "product:fa:میز"],
  "paths": [{ "path": "/shop/%D9%85%DB%8C%D8%B2", "type": "page" }]
}
  • Max targets per request: 50 (MAX_TARGETS)
  • Max body size: 8192 bytes UTF-8 (MAX_BODY_BYTES)
  • Timestamp window: ±60 seconds (TIMESTAMP_WINDOW_SECONDS)
  • Path encoding: Sender normalizes with encodeURI(decodeURI(path)); invalid tags or paths in hooks are dropped with a warning log.

Logging events

All logs use @nexload-sdk/logger with child bindings { module: "payload-revalidate" }.

EventSideLevelMeaning
revalidate.client.disabledSenderdebugcreateRevalidator created with enabled: false
revalidate.batch.flushedSenderinfoTransaction batch flushed to sender
revalidate.batch.droppedSenderwarnOnly without afterCommitPlugin: transaction wait cap exceeded; the pending batch is discarded (outcome: "dropped")
revalidate.flush.timeoutSenderwarnflush() hit its wait cap before pending work finished (outcome: "timeout"); nothing is dropped
revalidate.target.droppedSenderwarnInvalid tag or path dropped in hook (outcome: "dropped")
revalidate.hook.failedSendererrorHook rule or snapshot resolution threw
revalidate.request.sentSenderinfoBatch POST succeeded
revalidate.request.retriedSenderwarnRetryable failure (408, 429, 5xx, network, timeout)
revalidate.request.failedSender, ReceivererrorSender: non-retryable response or retries exhausted. Receiver: revalidateTag/revalidatePath threw (outcome: "cache_error", response 500 { error: "cache_error" })
revalidate.request.handledReceiverinfoValid request revalidated tags/paths (200)
revalidate.request.rejectedReceiverwarnRequest rejected (400, 401, 405, 413, 415)

Testing

Use createTestRevalidator from @nexload-sdk/payload-revalidate/testing to capture dispatched WireBatch objects in memory without making HTTP requests:

import { createTestRevalidator } from "@nexload-sdk/payload-revalidate/testing";

const { revalidator, calls, clear } = createTestRevalidator();

Limitations

  • versions.maxPerDoc: 1: When previousDoc is a draft, recovering the prior published snapshot requires at least two retained versions; setting maxPerDoc: 1 prevents recovering older published snapshots.
  • localizeStatus collections: With localizeStatus, _status reaches the hooks as a string for a normal single-locale request (localized fields are flattened) and as a per-locale map when the request locale is "all". A custom isPublic predicate in Rules must handle both shapes (string: compare to "published"; map: check the locale(s) you care about). Snapshot resolution and published-version recovery are not guaranteed to be correct for localizeStatus collections in v1, and stable or id-based tags alone do not fix this because when no snapshot is public the hook emits no targets. After unpublishing, or after publishing a renamed draft, in such a collection, call await revalidator.send({ tags, paths }) with the old targets only after the transaction that owns the write has committed (when a top-level Local API call without an open-transaction req returns, or after await commitTransaction(req) if you passed a req opened with initTransaction); if your code runs inside someone else's transaction (such as a hook or a job step sharing req), do not call send() there at all because it posts before commit and throws on failure.
  • No durable delivery: Batches are held in memory per transaction and retried with bounded backoff; if the process crashes or all retries fail, the batch is dropped and logged.
  • No multi-target fan-out: Each createRevalidator instance posts to a single url (instantiate multiple revalidators if you need to notify multiple frontends).
  • Never call flush() from a hook, or send() inside an open transaction: Calling flush() inside a collection or global hook deadlocks against the open transaction until the 5000 ms wait cap expires. Calling revalidator.send(...) inside someone else's transaction (such as a hook or a job step sharing req) posts immediately before commit and throws on failure; call send() only after the transaction that owns the write has committed (when a top-level Local API call without an open-transaction req returns, or after await commitTransaction(req) if you passed a req opened with initTransaction).
  • 5-second transaction wait cap (only without afterCommitPlugin): Without afterCommitPlugin() installed, a batch whose transaction stays open longer than 5 seconds after the hook ran is dropped with a revalidate.batch.dropped warning (sending early could refill the cache with uncommitted data); long bulk jobs should use context.skipRevalidate and call await revalidator.send(...) only after the transaction that owns the write has committed (when a top-level Local API call without an open-transaction req returns, or after await commitTransaction(req) if you passed a req opened with initTransaction). If your code runs inside someone else's transaction (for example inside a hook or a job step sharing req), do not call send() there at all.

Agent skills

This package ships agent skills that match its version. After install they are at node_modules/@nexload-sdk/payload-revalidate/skills/:

  • payload-revalidate — skills/payload-revalidate/SKILL.md

Point your coding agent at them from AGENTS.md, or install from the repository with npx skills add gecut/nexload-sdk --skill <name>.

License

MIT

Similar plugins