Skip to content

Latest commit

 

History

63 Commits

Folders and files

Repository files navigation

@klnap/cache-invalidation

Framework-agnostic, standards-based, multi-target event-driven cache invalidation, with first-class Payload CMS and Next.js integrations.

Pre-1.0: The public API may change before version 1.0. Pin an exact package version and review the changelog before upgrading. When upgrading producer and consumer applications independently, verify their event and transport compatibility. Coming from 0.4? See Upgrading from 0.4.

Overview

  • One event contract. Every producer emits CloudEvents 1.0; every consumer reads them. Producers never name cache tags, and consumers never depend on how an event travelled.
  • Payload CMS producer. Detects public content changes (drafts, publication, localization, media dependencies) and routes each model to the applications that need it.
  • Signed webhooks. A dispatcher sends Standard Webhooks; a receiver authenticates Standard Webhooks requests itself (a decoder then only converts a custom JSON payload into CloudEvents), and hands requests from other providers, such as Sanity and Contentful, to an application-owned adapter that authenticates them.
  • Consumers. A type-safe Next.js consumer (tags, paths, profiles), and a framework-independent consumer with your own executors. Both accept events over HTTP or directly.

The package does not provide a cache store, durable message queue, event broker, or workflow engine.

Contents

Installation

bun add --exact @klnap/cache-invalidation

Or with npm:

npm install --save-exact @klnap/cache-invalidation

@klnap/revalidation is the former name of this package. It is deprecated on npm; install @klnap/cache-invalidation instead.

Compatibility

Dependency Supported versions
Node.js ^22.23.5 || ^24.22.3 || >=26.13.1
Payload CMS >=3.94.1 <4
Next.js >=16.4.5 <17

Payload and Next.js are optional peer dependencies. Install them only in applications using their respective integrations.

The package is ESM. Bun is used for repository development but is not required by the package.

Architecture

Three independent dimensions: where an event comes from, how it travels, and which cache it invalidates.

Producers                    Transport                          Consumers
---------                    ---------                          ---------
Payload plugin  --+                                        +--> Next.js consumer
Generic producer -+--> CloudEvents --> Webhook dispatcher -+      (tags, paths)
                  |                    or your own transport+--> Generic consumer
                  |                                        |      (your executors)
External CMS -----+--> Webhook receiver: native, decoder   +--> Your callback
(Sanity, Contentful)    or your adapter --> CloudEvents
                                                                 direct consume(events),
                                                                 no HTTP

A native producer reaches a native receiver through the dispatcher. An external CMS does not use the dispatcher: its webhook enters through the receiver, where an authenticated decoder or an application-owned adapter turns it into CloudEvents. After that, every path is identical: shared validation, rule matching, planning and execution.

Entrypoint Responsibility
@klnap/cache-invalidation CloudEvents, generic producer, dispatcher contracts, event selectors, Resource Change V1, errors, delivery outcomes
@klnap/cache-invalidation/producers/payload Payload CMS plugin and transaction deferral
@klnap/cache-invalidation/webhooks Webhook dispatcher and receiver, including decoders and adapters
@klnap/cache-invalidation/consumers Framework-independent cache consumer
@klnap/cache-invalidation/consumers/next Next.js cache definitions, native consumer and Route Handler

The root, /webhooks and /consumers entrypoints do not require Payload or Next.js.

Snippets that use cache, secret, dispatcher, events, payload, invalidateProduct and similar names, or imports such as @/cache, refer to your own application code. A snippet that starts with an options object (custom: { … }, filter: { … }) is a fragment of the call described next to it.

Quick start

Payload CMS to Next.js

This integration connects independently deployed Payload and Next.js applications.

1. Configure a signing secret

Generate a Standard Webhooks secret:

printf 'whsec_%s\n' "$(openssl rand -base64 32 | tr -d '\n')"

Store the generated value as CACHE_INVALIDATION_SECRET in both applications.

In Payload, also configure CACHE_INVALIDATION_URL with the full URL of the Next.js invalidation endpoint, for example:

CACHE_INVALIDATION_URL=https://www.example.com/api/invalidate

Keep signing secrets in server-side environment configuration.

2. Configure Payload

Add the producer plugin to your existing Payload configuration:

import { cacheInvalidation } from '@klnap/cache-invalidation/producers/payload'

const plugin = cacheInvalidation({
  source: 'https://cms.example.com',
  collections: {
    products: true,
  },
  webhooks: {
    targets: {
      website: {
        url: process.env.CACHE_INVALIDATION_URL!,
        secret: process.env.CACHE_INVALIDATION_SECRET!,
      },
    },
  },
})

Include plugin in the plugins array of your Payload configuration.

The products collection must already exist in your application.

Only opted-in resources produce ordinary collection or global change events.

3. Define the Next.js cache

Create src/cache.ts:

import 'server-only'
import { defineCache } from '@klnap/cache-invalidation/consumers/next'

export const cache = defineCache({
  tags: {
    products: 'products',
    product: 'product:[id]',
  },
  rules: ({ tags }) => ({
    'payload.collection.products': [
      tags.products,
      tags.product,
    ],
  }),
})

This definition invalidates the product listing and the affected product detail cache when public product content changes.

4. Create the Route Handler

Create app/api/invalidate/route.ts:

import { createCacheInvalidationHandler } from '@klnap/cache-invalidation/consumers/next'
import { cache } from '@/cache'

export const POST = createCacheInvalidationHandler({
  cache,
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://cms.example.com'],
})

The handler authenticates the request, validates its events, plans cache operations, and invokes native Next.js cache APIs.

5. Tag cached data

Use the same cache helpers when attaching tags:

import { cacheTag } from 'next/cache'
import { cache } from '@/cache'
import { loadProduct, loadProducts } from '@/data/products'

export async function getProducts() {
  'use cache'

  cacheTag(cache.tags.products())
  return loadProducts()
}

export async function getProduct(id: string) {
  'use cache'

  cacheTag(cache.tags.product({ id }))
  return loadProduct(id)
}

The data-loading functions are application-owned.

Enable Cache Components in your Next.js configuration:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

6. Verify invalidation

Load a product page to populate its cache. Update and publish the product in Payload, then revisit the page after the invalidation request has been processed.

The product listing and affected product cache should reflect the changed public content.

Automatic Payload delivery is asynchronous and best effort. It is not a database commit notification. Applications requiring confirmed commit ordering must use the transaction deferral workflow.

A successful webhook response does not imply that every affected route has already regenerated.

Any producer to any consumer

Neither Payload nor Next.js is required. The application that owns the data emits events:

import { createCacheInvalidationProducer } from '@klnap/cache-invalidation'
import { createWebhookDispatcher } from '@klnap/cache-invalidation/webhooks'

export const producer = createCacheInvalidationProducer({
  source: 'https://catalog.example.com',
  dispatcher: createWebhookDispatcher({
    targets: {
      website: {
        url: process.env.CACHE_INVALIDATION_URL!,
        secret: process.env.CACHE_INVALIDATION_SECRET!,
        filter: { type: 'catalog.product.updated' },
      },
    },
  }),
})

const outcome = await producer.emit({
  type: 'catalog.product.updated',
  data: { id: '42' },
})

The receiving application maps events to its own cache operations and mounts the handler wherever it serves requests:

import * as v from 'valibot'
import { createCacheConsumer } from '@klnap/cache-invalidation/consumers'
import { createWebhookHandler } from '@klnap/cache-invalidation/webhooks'
import { invalidateProductCache } from './cache'

const consumer = createCacheConsumer({
  schemas: { 'catalog.product.updated': v.object({ id: v.string() }) },
  allowedSources: ['https://catalog.example.com'],
  rules: {
    'catalog.product.updated': ({ data }) => [{ layer: 'store', value: data.id }],
  },
  execute: {
    store: async ({ value }) => invalidateProductCache(String(value)),
  },
})

export const webhook = createWebhookHandler({
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  consumer,
})

Bun.serve({
  port: 8080,
  fetch(request) {
    if (new URL(request.url).pathname !== '/events') {
      return new Response('Not found', { status: 404 })
    }
    return webhook(request)
  },
})

invalidateProductCache is application-owned. The handler takes a standard Request and returns a Promise<Response>, so it mounts in any server or framework. For a plain callback instead of a consumer, pass onEvents; see Webhook receiver.

Persistent deduplication and crash-safe processing are application responsibilities; see Security and reliability.

Payload CMS producer

Import from:

import { cacheInvalidation } from '@klnap/cache-invalidation/producers/payload'

Configuration

Option Required Default Description
source Yes — Stable absolute CloudEvents source URI
webhooks One of — Native webhook delivery; see Multi-target routing
dispatcher One of — Application-owned dispatcher; mutually exclusive with webhooks
dataschema No Omitted Application-owned absolute schema URI
enabled No true Enable the plugin
collections No No models true, or per-collection configuration
globals No No models true, or per-global configuration
exclude No Nothing excluded Models that never take part, whatever else enables them
excludeFields No [] Comparison exclusions applied to every model
media No Automatic upload collection selection Media dependency handling, or false

An enabled plugin needs exactly one delivery mode: webhooks or dispatcher. A disabled plugin (enabled: false) returns the incoming Payload configuration unchanged and needs no delivery configuration or credentials.

import { cacheInvalidation } from '@klnap/cache-invalidation/producers/payload'

export const plugin = cacheInvalidation({
  source: process.env.CMS_URL!,
  collections: { pages: true, products: true },
  globals: { navigation: true },
  webhooks: {
    targets: {
      website: {
        url: process.env.WEBSITE_INVALIDATION_URL!,
        secret: process.env.WEBSITE_INVALIDATION_SECRET!,
      },
    },
  },
})

webhooks builds the webhook dispatcher internally and accepts all of its options (retries, timeoutMs, deadlineMs, maxEventItems, maxBodyBytes, allowInsecure, …). To use your own transport, pass dispatcher instead; see Custom dispatchers.

Model selection and exclusion

Collections and globals are opt-in: nothing emits ordinary change events unless you select it. The upload collection is the one exception. Unless it is excluded, disabled or media: false is set, it takes part through automatic media dependency handling even when you did not select it; that path reports a changed file together with the models you did enable that use it.

cacheInvalidation({
  source,
  webhooks,
  collections: { products: true, categories: true, articles: { excludeFields: ['internalNote'] } },
  globals: { navigation: true },
})

Select everything explicitly with true:

cacheInvalidation({
  source,
  webhooks,
  collections: true,
  globals: true,
  exclude: {
    collections: ['users', 'auditLogs'],
    globals: ['internalSettings'],
  },
})

Automatic selection (true) skips authentication collections and Payload system collections (slugs starting with payload-), using Payload's own metadata rather than guessing from names. A model can still opt in explicitly, centrally or through custom.cacheInvalidation.

Automatic selection is not a data-safety guarantee. A custom, non-authentication collection can still hold data you do not want to publish to other applications. For security-sensitive deployments, prefer explicit selection and review public access policies (see Public snapshots).

exclude has absolute precedence. An excluded model does not emit events, is never a media dependency, and cannot be routed to. Local custom.cacheInvalidation, central options, automatic selection and media handling cannot re-enable it. Excluding a slug the Payload config does not contain is a configuration error.

Collections and globals are separate namespaces. A collection and a global may share a slug and are configured, excluded and routed independently.

Resource configuration

Configuration can also be attached directly to an existing collection or global:

export const Products: CollectionConfig = {
  slug: 'products',
  custom: {
    cacheInvalidation: {
      excludeFields: ['stockMetadata'],
      projection: ({ data }) => ({ id: data.id, slug: data.slug, price: data.price }),
    },
  },
  fields: [],
}

custom: { cacheInvalidation: true } enables a model; false disables it.

Resource-level options (central or local):

Option Description
enabled Enable or disable the resource
excludeFields Exclude fields from public-state comparison (combined with every other list)
filter Decide whether a detected public change should emit an event
projection Transform the outgoing public snapshots

The plugin installs every lifecycle hook a correct invalidation needs (afterChange, beforeDelete and afterDelete on collections, afterChange on globals). There is no hook-selection option. To ignore an operation, use filter:

filter: ({ operation }) => operation !== 'delete'

Ignoring deletions is rarely correct: it leaves a deleted resource cached.

Precedence for each model, strongest first:

  1. exclude (absolute).
  2. Local custom.cacheInvalidation: false disables, true enables, an options object enables unless it sets enabled: false.
  3. Central collections / globals configuration.
  4. Automatic selection.

For filter and projection, a local value replaces the central one. excludeFields lists are combined, see Comparison exclusions.

One resolved configuration drives lifecycle hooks, media dependency discovery and routing validation; nothing re-reads custom later.

Multi-target routing

One CMS can serve several independent applications. Each target receives only the events it subscribes to, selected by Payload model:

cacheInvalidation({
  source: process.env.CMS_URL!,
  collections: true,
  globals: true,
  exclude: { collections: ['users'], globals: ['internalSettings'] },
  webhooks: {
    targets: {
      website: {
        url: process.env.WEBSITE_URL!,
        secret: process.env.WEBSITE_SECRET!,
        filter: { collections: ['pages'], globals: ['navigation', 'footer'] },
      },
      shop: {
        url: process.env.SHOP_URL!,
        secret: process.env.SHOP_SECRET!,
        filter: { collections: ['products', 'categories'], globals: ['navigation'] },
      },
      magazine: {
        url: process.env.MAGAZINE_URL!,
        secret: process.env.MAGAZINE_SECRET!,
        filter: { collections: ['articles', 'authors'], globals: ['navigation'] },
      },
    },
  },
})
Configuration Meaning
No filter Every event this producer emits
collections only Those collections, plus events that depend on them (see below)
globals only Those globals, plus events that depend on them
Both The union
Duplicate slugs Delivered once
Same slug as collection and global Distinct models
Unknown, excluded or non-emitting model Configuration error
Empty filter Configuration error, never "everything"

Targets with no matching events receive no request. A shared model (such as navigation above) reaches every subscribed target as the same event with the same (source, id) identity.

A media event carries the resources that use the file in data.affected. A target subscribed to any of those models receives the media event, once, even if several affected entries or the media model itself also match. affected is validated before it is used for routing.

Routing selects recipients; it does not redact. A recipient of a shared media event receives the whole event, including affected entries for models it did not subscribe to. This is appropriate for cooperating applications inside one data trust boundary. It is not tenant isolation.

Targets are validated against the effective configuration when the Payload config is built. A model can only be routed to if it emits events: it must be enabled, or be the upload collection handled through media dependencies.

Functional filters

When model filtering is not enough, for example when several websites share a collection, pass a synchronous predicate:

import type { CloudEvent } from '@klnap/cache-invalidation'

const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null && !Array.isArray(value)

const siteOf = (snapshot: unknown): string | undefined =>
  isRecord(snapshot) && typeof snapshot.site === 'string' ? snapshot.site : undefined

const SHARED = ['payload.collection.pages', 'payload.collection.posts']

export const belongsToSite =
  (site: string) =>
  (event: Readonly<CloudEvent>): boolean => {
    const data: unknown = event.data
    if (!isRecord(data)) return false // missing or malformed: not for this site

    // A shared model's own event: previous or current membership.
    if (SHARED.includes(event.type)) {
      return siteOf(data.before) === site || siteOf(data.after) === site
    }

    // A media event: supported affected resources that currently belong to the site.
    if (event.type === 'payload.collection.media' && Array.isArray(data.affected)) {
      return data.affected.some(
        (entry: unknown) =>
          isRecord(entry) &&
          typeof entry.type === 'string' &&
          SHARED.includes(entry.type) &&
          siteOf(entry.data) === site,
      )
    }
    return false
  }
webhooks: {
  targets: {
    siteA: { url: process.env.SITE_A_URL!, secret: process.env.SITE_A_SECRET!, filter: belongsToSite('a') },
    siteB: { url: process.env.SITE_B_URL!, secret: process.env.SITE_B_SECRET!, filter: belongsToSite('b') },
  },
}

The predicate is application code, so it must be deterministic and free of side effects. It receives a private copy of the event, so it cannot affect other targets. A predicate that throws or returns a non-boolean fails that target with FILTER_FAILED; the event is not skipped silently, and the other targets are delivered as usual.

A document can move between sites, and then both sites need an invalidation: the old one to drop stale content and the new one to refresh. That is why the predicate checks both snapshots:

Operation Snapshots in the event
Create after only
Update before and after (a move changes site between them)
Delete before only
Unpublish before (the published state) and after: null

A media event lists the dependent documents under data.affected, with their current public state only. A document that left a site is therefore not announced to that site by the media event; it was announced when it moved.

The predicate can only read what the event contains. If it routes on site, each model's projection must keep that field, or neither check can see it. The library never queries additional private data to satisfy a predicate.

The repository's tests exercise this predicate against real Payload and real receivers for create, update, move, delete, unpublish and media changes (fixture, integration test).

Public snapshots

Payload events describe public resource changes, not arbitrary database mutations.

The producer obtains public representations before and after the operation using Payload's anonymous Local API access pipeline.

These reads use:

  • overrideAccess: false.
  • showHiddenFields: false.
  • depth: 0.
  • draft: false.
  • Anonymous user context.
  • Configured locale and fallback behavior.
  • The active transaction context when available.

The producer does not substitute privileged hook documents when a public read fails.

Relationships remain unpopulated representations according to Payload's depth-zero behavior, normally identifiers rather than complete related documents.

A genuinely absent public representation is represented by null. Other read failures are logged and do not become deletion events.

Payload mutations remain fail-open when invalidation event preparation or delivery fails.

The public-read mechanism preserves Payload's access-control behavior. It is not a universal sanitizer for arbitrary application data. Review your public collection and field access policies before enabling event delivery.

Drafts and publication

Change Public before Public after
Draft-only creation Absent Absent
Draft-only edit without public change Unchanged Unchanged
First publication null Published representation
Published update Previous representation Current representation
Unpublication Published representation null
Published resource deletion Published representation null

Draft-only changes and unchanged public representations do not emit ordinary change events.

Consumers can invalidate both previous and current identifiers, slugs, or dependencies without having to reconstruct earlier resource state.

Localization

The producer compares effective public representations across configured Payload locales.

When fallback is enabled, it uses Payload's configured default locale for fallback reads. Otherwise, fallback is disabled.

Localized snapshots include their locale.

A single mutation can produce zero, one, or multiple locale-specific changes. Shared-field modifications and fallback-source changes can affect several locale representations.

Configure locale-specific tags or paths when the consumer caches localized resources independently:

tags: {
  product: 'product:[locale]:[id]',
  products: 'products:[locale]',
}

Globals receive an identifier corresponding to their global slug.

Comparison exclusions

Comparison exclusions prevent changes to selected fields from triggering an event on their own.

The configured default exclusion list is empty. Independently of that list, the comparison implementation ignores these technical root-level fields:

  • id
  • createdAt
  • updatedAt
  • _status
  • globalType

Lexical node identifiers are also ignored recursively in Lexical-shaped data.

Publication and public-resource existence transitions are handled separately from ordinary field comparison.

Additional exclusions support dot-separated paths:

excludeFields: [
  'internalNote',
  'seo.internalNotes',
]

Nested exclusion paths traverse plain objects, not individual array elements.

Exclusion lists are combined, never replaced. The effective list for a model is, in order of appearance, the plugin-wide excludeFields, the model's central excludeFields, and the model's local custom.cacheInvalidation.excludeFields, normalized and de-duplicated. For the media collection it also includes the media.excludeFields list. A local list therefore cannot drop a plugin-wide exclusion.

Exclusions affect comparison only. Excluded fields can still appear in emitted public snapshots.

Do not use excludeFields as a security or data-redaction mechanism.

Filtering and projection

filter receives:

{
  before,
  after,
  locale,
  operation,
  resource,
}

It runs after public-state acquisition and comparison. Returning false suppresses the event.

projection receives:

{
  data,
  locale,
  operation,
  resource,
}

It transforms the outgoing snapshots after comparison.

For example, a consumer that depends only on resource identity, slug, and category can use:

custom: {
  cacheInvalidation: {
    projection: ({ data }) => ({
      id: data.id,
      slug: data.slug,
      category: data.category,
    }),
  },
}

Projection must return a non-array object.

If projection omits the resource identifier, the producer restores it from the public input. For localized resources, it preserves the snapshot's locale.

Keep identifiers and fields required by consumer rules stable.

Filtering and projection failures are handled by the producer's fail-open error path. They do not make a failed public read equivalent to deletion.

Projection controls the event representation; Payload access control remains responsible for deciding which fields are publicly readable.

Media dependencies

The plugin can discover opted-in resources that reference a changed or deleted upload.

Media collection selection follows this order:

  1. Explicit media configuration.
  2. The only upload collection.
  3. An upload collection with the slug media.

If multiple upload collections exist and none is selected explicitly or named media, automatic selection is unavailable.

The selected upload collection does not need to be separately enabled in collections for media dependency tracking.

Dependent collections and globals must be enabled in the effective configuration: centrally, locally, or through collections: true / globals: true. Excluded models are never discovered as dependents, so they never appear in affected.

Configuration Effect
Media collection not mentioned Takes part through dependency handling
Media collection in collections Same; dependency handling emits the media event, so there is no duplicate
exclude.collections: ['media'] No events from the media collection; absolute
Media disabled (collections: { media: false } or custom.cacheInvalidation: false) Dependency handling stays off and is not re-enabled
media: false Dependency handling is off; the media collection emits ordinary events only if you enabled it

To select an upload collection explicitly, pass its existing Payload collection configuration:

import { Media } from './collections/Media'

cacheInvalidation({
  source: 'https://cms.example.com',
  dispatcher,
  collections: {
    articles: true,
  },
  media: {
    collection: Media,
    excludeFields: ['internalNote'],
  },
})

A collection configuration object can also be passed directly as media.

Discovery supports upload and relationship fields targeting the selected upload collection through:

  • Groups.
  • Rows.
  • Collapsible fields.
  • Tabs.
  • Arrays in collections.
  • Supported direct and has-many references in collections.

It does not provide a general relationship graph.

Blocks, polymorphic relationships, arbitrary JSON, rich-text references, and relationships targeting unrelated collections are outside the discovery contract.

Global dependencies inside arrays or has-many fields are not supported by the global discovery path.

Collection discovery uses stable identifier pagination with pages of 500 documents.

Candidate discovery uses internal privileged queries to identify references. Emitted dependent data is subsequently acquired through anonymous public reads.

Discovery errors can produce incomplete affected-resource coverage. Successful earlier results are retained, and failures are logged. There is no durable discovery retry system or transactionally consistent reverse-reference index.

Media dependency tracking responds to relevant media updates and deletions. Initial media creation does not trigger dependent-resource discovery.

Media comparison exclusions are the plugin-wide list, the media.excludeFields list and the media collection's central and local lists, combined.

Affected resources are carried inside the top-level media event.

A webhook target with a model filter receives the media event when it subscribes to the media collection or to any affected model. A target filtered with a generic selector ({ type }) matches only the media event's own type; use a model filter or a functional filter to route on affected resources.

Routing does not redact the event: a recipient of a media event sees all of its affected entries.

Transaction timing

Ordinary Payload lifecycle hooks run before the database transaction has necessarily committed.

The automatic delivery path schedules events after a fixed one-second delay. That delay is not a commit notification.

A consumer can invalidate its cache, read the previous database state, and refill the cache before the mutation commits. Automatic delivery can also occur before rollback.

Process interruption can lose scheduled events.

Each ordinary hook schedules its own event set; there is no cross-hook automatic batch coalescer.

Explicit deferral

Applications that own the outermost transaction can register deferral before performing its mutations:

import { deferCacheInvalidationUntilCommit } from '@klnap/cache-invalidation/producers/payload'

const pending = deferCacheInvalidationUntilCommit(req)

Pass the exact same request object to all mutations participating in that transaction.

For example, within the application-owned transaction:

await payload.update({
  collection: 'products',
  id: productId,
  data: {
    title,
  },
  req,
  overrideAccess: false,
})

After the application has authoritatively resolved the outermost transaction outcome:

switch (outcome) {
  case 'committed': {
    const result = await pending.flush()
    // Retain result if recovery or delivery reporting is required.
    break
  }

  case 'rolled-back':
    pending.discard()
    break

  case 'unknown':
    // Preserve unresolved state privately.
    // Do not flush, discard, or repeat the mutation.
    break
}

Here, outcome is the authoritative result supplied by the application's transaction owner:

type TransactionOutcome =
  | 'committed'
  | 'rolled-back'
  | 'unknown'

The transaction owner is application-specific. This package does not create, commit, roll back, or inspect the transaction.

It must not replace an existing transaction identifier owned by another operation.

PostgreSQL transaction acknowledgement

In Payload PostgreSQL 3.94.1, the underlying Drizzle transaction adapter can catch a transaction promise rejection while settling its transaction methods.

A fulfilled commitTransaction() promise alone is therefore not sufficient proof that the database committed.

Use authoritative adapter-specific transaction evidence. If the result cannot be established, retain an unknown outcome.

Do not treat an exception or an ambiguous acknowledgement as permission to repeat a business mutation.

Applications needing durable resolution of ambiguous transactions can store a unique operation receipt within the same transaction. Receipt presence on the primary database can establish that the transaction committed. Receipt absence alone is not proof of rollback while the original transaction may still be open.

Such receipts must be protected from ordinary application access and retained until no unresolved operation depends on them.

Transaction receipts establish transaction evidence; they do not persist CloudEvents.

Crash-safe delivery requires separate application-owned durable storage of events or sufficient recovery data.

Deferral lifecycle

Deferral is associated with the exact request-object identity.

  • Register before the participating mutations.
  • Repeated registration while a deferral is active throws.
  • Nested operations using the same request join the active queue.
  • Pending work is deduplicated only when change type, collection or global slug, locale, document, operation, and before/after snapshots are identical. Two transitions of one document are kept separately, so both the old and new slugs can be invalidated.
  • Flush groups deliveries by dispatcher identity, source, and optional schema URI.
  • Concurrent calls to flush() share the in-progress promise.
  • After discard, flush() reports discarded.
  • Repeated discard is a no-op.
  • Discard cannot retract a flush that has already started.
  • An empty flush reports accepted with no deliveries.
  • Repeated flush after completion returns an empty accepted result.
  • New work collected while a flush is in progress falls back to automatic delivery.
  • A resolved deferral does not capture later work on the same request.

Retain the first completed flush result when delivery identities or outcomes are required for recovery.

Each delivery record contains the source, optional schema URI, generated CloudEvents, and dispatch outcome.

The helper is process-local. It does not resolve database transaction outcomes, persist events, guarantee process survival, or provide an outbox.

A dispatch failure after a confirmed commit does not undo the committed mutation.

Generic producer

A producer emits CloudEvents from any application, without Payload. The quick start shows one.

Producer configuration

Option Description
source Required stable absolute URI identifying the producer
dispatcher Required object implementing Dispatcher

Each call to emit() creates one new CloudEvent and returns a Promise<DispatchOutcome>.

It accepts:

Property Description
type Required nonempty event type
data Optional JSON-compatible application data
subject Optional event subject
datacontenttype Optional data media type
dataschema Optional schema URI metadata
extensions Optional CloudEvents extension attributes

The producer generates a new rev_-prefixed identifier, a timestamp, and CloudEvents version 1.0.

Provided data defaults to application/json unless another data content type is supplied.

Producer data must consist of JSON-compatible values. Non-finite numbers, cycles, accessors, symbol properties, non-plain records, and unsupported array shapes are rejected.

Extension names must consist of 1–20 lowercase alphanumeric characters and must not replace standard attributes. Values may be strings, booleans, or finite numbers.

Invalid configuration or event input throws.

If a custom dispatcher throws, the producer returns unknown with the event's identity because the exception does not establish whether a receiver acted.

A new call to emit() creates a new logical event. It is not a retry of an earlier logical event.

Custom dispatchers

Applications can implement their own transport or durable delivery policy using the public dispatcher contract:

import type {
  DispatchInput,
  DispatchOutcome,
  Dispatcher,
} from '@klnap/cache-invalidation'

type CustomDispatcher = {
  dispatch(input: DispatchInput): Promise<DispatchOutcome>
}

DispatchInput contains:

{
  events: readonly CloudEvent[]
}

A custom dispatcher can be supplied to the generic producer or, with dispatcher, to the Payload plugin (instead of webhooks).

Custom dispatchers own their persistence, transport, retry, and delivery guarantees.

There is no implicit default transport or fallback dispatcher.

When durable delivery is required, persist the event itself or sufficient recovery state before performing delivery according to your application's consistency requirements.

Webhooks

Webhooks are the HTTP transport: a dispatcher that signs and sends events, and a receiver that authenticates and reads them. Both live in @klnap/cache-invalidation/webhooks.

Webhook dispatcher

import { createWebhookDispatcher } from '@klnap/cache-invalidation/webhooks'

Named targets

const dispatcher = createWebhookDispatcher({
  targets: {
    website: {
      url: 'https://www.example.com/api/invalidate',
      secret: process.env.WEBSITE_WEBHOOK_SECRET!,
    },
    catalog: {
      url: 'https://catalog.example.com/api/invalidate',
      secret: process.env.CATALOG_WEBHOOK_SECRET!,
      filter: {
        type: [
          'payload.collection.products',
          'payload.collection.categories',
        ],
      },
    },
  },
})

Each target requires a destination URL and signing secret.

Without a filter, a target receives every selected event.

Filters match exact CloudEvents source and type attributes:

filter: {
  source: 'https://cms.example.com',
  type: [
    'payload.collection.products',
    'payload.collection.categories',
  ],
}

Values within one selector are alternatives. When both source and type are supplied, both conditions must match.

Filters operate on individual events before batching.

A filter can also be a synchronous predicate that you own:

filter: (event) => event.type === 'catalog.product.changed' && isRelevant(event)

The predicate must be deterministic and side-effect free. It receives a private copy of the event, so mutating it cannot affect other targets. A predicate that throws or returns a non-boolean fails that target with FILTER_FAILED and zero attempts; it is not a skip, and other targets are delivered as usual. Selector objects do not inspect application data; use a predicate when routing needs data.

For Payload, prefer the model filter described in Multi-target routing.

Explicit target selection

When dispatching already constructed or persisted events directly:

await dispatcher.dispatch({
  events,
  targets: ['website'],
})

Omitting targets selects all configured destinations.

Explicit selection narrows recipients; it does not bypass their filters.

Duplicate target selections are deduplicated.

Unknown targets are rejected before network delivery. If any selected target is unknown, the whole selection is rejected with no deliveries, including to the valid targets in that selection.

Empty event lists, empty target selections, and selections with no matching events produce explicit skipped outcomes. A target with no matching events receives no request.

Dispatcher configuration

Option Default Accepted values
targets Required Named target configuration
timeoutMs 15,000 Integer from 1 to 60,000
deadlineMs 5,000 Integer from 1 to 300,000
retries 2 Integer from 0 to 10
retryDelayMs 200 Integer from 0 to 60,000
maxEventItems 100 Integer from 1 to 1,000
maxBodyBytes 256 KiB Integer from 1 to 16 MiB in bytes
allowInsecure false Boolean

Configuration is validated synchronously.

Target configuration and filters are captured when the dispatcher is created.

At most four deliveries execute concurrently.

The total dispatch deadline includes preparation, filtering, batching, queued work, retry delays, and HTTP delivery.

A shorter remaining deadline can terminate an attempt before its configured attempt timeout expires.

Batching

Events are filtered per target and divided into chunks respecting both event-count and serialized-body limits.

A single-event chunk uses:

application/cloudevents+json

A multiple-event chunk uses:

application/cloudevents-batch+json

An individual event that exceeds the body limit produces a failed result without a network attempt.

Each target chunk receives an independent wh_-prefixed delivery identifier.

Configure receiver limits to accommodate dispatcher chunk sizes.

Retries

retries counts additional attempts after the initial attempt.

The dispatcher retries:

  • HTTP 408.
  • HTTP 429.
  • HTTP 5xx.
  • Network failures.
  • Request timeouts.

Other client errors and redirects are terminal.

Redirects are not followed automatically.

Backoff uses exponential full jitter. A valid Retry-After header can increase the delay.

Both delta-seconds and HTTP-date forms are supported, subject to the retry delay cap and remaining dispatch deadline.

Retries preserve:

  • CloudEvent identity.
  • Serialized request body.
  • Delivery identifier.

Each attempt uses a fresh signature timestamp and signature.

A network error or timeout is an ambiguous outcome: the remote receiver may already have acted.

A subsequent successful attempt does not erase earlier ambiguous attempts from attemptOutcomes.

Delivery outcomes

Status Meaning
accepted All attempted deliveries were accepted
partial Some attempted deliveries were accepted and others were not
rejected All attempted deliveries were rejected
failed Delivery failed without acceptance or an unresolved ambiguous outcome
unknown Delivery may have caused remote effects, but acceptance is unconfirmed
skipped No eligible delivery was attempted

Intentional no-delivery is not reported as transport success.

Skipped results do not participate in attempted-delivery aggregation.

When no delivery was accepted, an unresolved unknown outcome takes precedence over ordinary failure or rejection.

When some deliveries were accepted, the aggregate status is partial even if another delivery is unknown. Per-target results still report unknown, so callers must inspect per-target results before treating an aggregate partial as fully resolved.

Per-target results contain the target name, status, and attempt count, together with available delivery identifiers, event references, attempt outcomes, skip reasons, and error information.

A target can have multiple results when its events are divided into multiple chunks.

HTTP acceptance means a 2xx response was received. It does not establish durable processing, completed cache regeneration, or absence of duplicate application effects.

Webhook receiver

createWebhookHandler() authenticates an incoming request, validates its CloudEvents, and hands them to a cache consumer or to an application callback.

import { createWebhookHandler } from '@klnap/cache-invalidation/webhooks'

Authentication modes

Configure exactly one:

Mode Options Who authenticates Payload
Native { secret } The library (Standard Webhooks) CloudEvents structured JSON or JSON batch
Custom payload { secret, decode } The library (Standard Webhooks) Anything your decoder reads
Custom protocol { adapter } Your adapter Anything your adapter reads

Invalid combinations are rejected at compile time and again at runtime: no authentication, decode without secret, secret with adapter, and adapter with decode all throw when the handler is created. There is no unauthenticated mode, no protocol auto-detection, and no fallback from one mode to another.

Native mode is what the webhook dispatcher and the Payload plugin produce, so a native producer and a native receiver need no extra configuration.

Receiver configuration

Option Default Accepted values
secret — Standard Webhooks signing secret (native and decoder modes)
decode Omitted Decoder, with secret
adapter — Adapter, instead of secret
consumer — A cache consumer, instead of onEvents
onEvents — Synchronous or asynchronous callback, instead of consumer
allowedSources Omitted Absolute source URIs (callback sink only)
schemas Omitted Standard Schema validators keyed by event type (callback sink only)
maxBodyBytes 256 KiB Integer from 1 to 16 MiB in bytes
bodyTimeoutMs 15,000 Integer from 1 to 60,000
maxEvents 100 Integer from 1 to 1,000
maxNormalizedBytes maxBodyBytes Integer from 1 to 16 MiB; limits decoder and adapter output
adapterTimeoutMs 15,000 Integer from 1 to 60,000; limits how long a decoder or adapter is awaited
logger Omitted Optional logger

Provide exactly one of onEvents and consumer.

Ownership. With onEvents, the handler owns source policy and schemas (allowedSources, schemas). With a consumer, the consumer owns them, together with its operation limits, and the handler rejects allowedSources and schemas.

Limits. maxBodyBytes, bodyTimeoutMs and maxEvents bound every request. maxNormalizedBytes and adapterTimeoutMs bound decoder and adapter output; a native request is bounded by its body size instead. A consumer applies its own maxEvents and maxNormalizedBytes to every batch it receives, native batches included, so the stricter of the handler's and the consumer's limits always wins. See How size is measured.

Processing order

Every mode follows the same pipeline, and no application effect runs before the whole batch is validated:

  1. HTTP method (and, in native mode, content type).
  2. Bounded read of the raw body, within byte and time limits.
  3. Authentication: native verification, then the optional decoder, or the adapter.
  4. Decoder and adapter output only: result shape, plain-data copy, event count and normalized size.
  5. CloudEvents envelope validation.
  6. Source policy.
  7. De-duplication by (source, id); conflicting duplicates reject the request.
  8. Local Standard Schema validation.
  9. The callback, or the consumer's planning and execution.

Conflicting events with the same (source, id) reject the complete request. Binary data and a JSON object with the same indexes are different values: Uint8Array([1]) never equals { "0": 1 }.

With no schemas, event data is unknown. A nonempty schema map validates matching event types and ignores unmapped types; any schema failure rejects the request before the callback runs. Empty or fully filtered batches do not invoke the callback.

Typed application events

import * as v from 'valibot'
import { createWebhookHandler } from '@klnap/cache-invalidation/webhooks'
import { invalidateProduct } from './cache'

export const webhook = createWebhookHandler({
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  schemas: {
    'catalog.product.updated': v.object({ id: v.string() }),
  },
  async onEvents(events) {
    for (const event of events) {
      await invalidateProduct(event.data!.id) // present: the schema rejects missing data
    }
  },
})

The callback receives validated schema output. invalidateProduct is application-owned.

If the callback throws after performing some effects, the handler returns a sanitized error response and cannot roll those effects back. A delivery retry may invoke the callback again.

How size is measured

maxNormalizedBytes (receiver) and maxNormalizedBytes (consumer) measure normalized events as the UTF-8 length of every key and string, 8 per number, 1 per boolean or null, and the byte length of binary data.

Decoder and adapter output is measured while it is copied, so an oversized result is rejected before it is fully allocated. Native batches are plain parsed JSON: the receiver does not apply maxNormalizedBytes to them, and a consumer measures them against its own limit without copying them. Because a number counts 8 bytes but needs at least two bytes of JSON, a native batch measures at most four times its body size; a consumer whose limit exceeds that skips measuring.

HTTP responses

All receivers accept POST requests. Native mode requires a supported structured CloudEvents JSON media type; decoder and adapter modes accept whatever their application code supports.

Status Meaning
200 Request processed without a reported failure
400 Invalid event, schema, request or adapter rejection (invalid-event); Next.js planning failures also use this status
401 Invalid authentication, signature timestamp, or adapter rejection (unauthorized)
403 Event source not allowed, or adapter rejection (forbidden)
405 Unsupported HTTP method
408 Request body read timed out
413 Body, event count, normalized size or operation budget exceeded
415 Unsupported content type, or adapter rejection (unsupported-media-type)
500 Callback, executor, adapter or decoder implementation error, or unexpected failure
503 Decoder or adapter exceeded adapterTimeoutMs

Responses use JSON and include an X-Cache-Request-Id header. A callback sink returns { requestId, accepted, ignored }. A consumer sink, including the Next.js handler, returns:

type ConsumerResponse = {
  requestId: string
  results: Array<{
    layer: string
    operation: string
    status: 'success' | 'failed' | 'skipped'
    error?: { code: string; message: string }
  }>
}

Unhandled events are reported as skipped results. Execution failures return per-operation results with HTTP 500; effects that already ran are not rolled back.

Logging

Receivers and consumers accept an optional logger:

type Logger = {
  debug?: (entry: Record<string, unknown>, message: string) => void
  info?: (entry: Record<string, unknown>, message: string) => void
  warn?: (entry: Record<string, unknown>, message: string) => void
  error?: (entry: Record<string, unknown>, message: string) => void
}

Library-owned code logs request and delivery identifiers, the HTTP status, and the error class name. It does not log exception messages, secrets, signatures or event bodies, and its HTTP responses carry fixed messages only. A logger callback that throws does not change the response.

This covers what the library writes. It cannot constrain what your own adapters, decoders, executors, hooks or logger implementation record or forward.

The Payload producer logs through Payload's own logger, recording the failing step, the error class and, when present, a short upper-case machine code such as Error (ECONNREFUSED). It never records the exception message, because messages from Payload, database drivers and your hooks can echo document values, SQL parameters or connection strings. Dispatcher failures are logged by outcome status and error code. Messages written by this package itself, such as an unavailable previous public state, are kept.

Decoders

Use a decoder when a producer signs with Standard Webhooks but sends its own JSON. The library verifies the signature and timestamp of the exact body first; the decoder then converts the payload to CloudEvents. It cannot change authentication, and it cannot replace the verified delivery identity.

import * as v from 'valibot'
import type { WebhookDecoder } from '@klnap/cache-invalidation/webhooks'

const message = v.object({
  eventId: v.pipe(v.string(), v.minLength(1)),
  occurredAt: v.pipe(v.string(), v.isoTimestamp()),
  tenant: v.string(),
  kind: v.picklist(['product.updated', 'product.deleted', 'ping']),
  product: v.optional(v.object({ id: v.pipe(v.string(), v.minLength(1)) })),
})

export const decodeProductEvent: WebhookDecoder = ({ rawBody }) => {
  // Validate at runtime; a type assertion after JSON.parse proves nothing.
  let parsed: v.InferOutput<typeof message>
  try {
    parsed = v.parse(message, JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(rawBody)))
  } catch {
    return { ok: false, reason: 'invalid-event' }
  }

  // Source policy is application-owned: this endpoint serves one tenant.
  if (parsed.tenant !== 'shop') return { ok: false, reason: 'forbidden' }

  // Authentic, but there is nothing to invalidate.
  if (parsed.kind === 'ping') return { ok: true, events: [] }

  if (!parsed.product) return { ok: false, reason: 'invalid-event' }
  return {
    ok: true,
    events: [
      {
        specversion: '1.0',
        // The producer's event id: stable across retries and covered by the signature.
        // The delivery id only correlates one HTTP delivery; it is not an event identity.
        id: parsed.eventId,
        source: `urn:example:${parsed.tenant}`,
        type: 'shop.product.changed',
        time: parsed.occurredAt,
        subject: parsed.product.id,
        data: {
          id: parsed.product.id,
          operation: parsed.kind === 'product.deleted' ? 'delete' : 'update',
        },
      },
    ],
  }
}

// createWebhookHandler({ secret, decode: decodeProductEvent, consumer })

Context: method, url, headers, rawBody (Uint8Array), signal, and deliveryId. Result: { ok: true, events }, or { ok: false, reason } with reason one of forbidden, invalid-event, unsupported-media-type. A decoder cannot return unauthorized, because the library already authenticated the delivery, and it cannot return a deliveryId.

events: [] is an authenticated delivery that needs no invalidation. Decoder output is untrusted data; see Output validation.

Adapters

Use an adapter when the request is not Standard Webhooks: the provider has its own signature scheme, headers or SDK. The adapter owns authentication and normalization.

This is the contract, as a type listing rather than runnable code:

type WebhookAdapter = (context: {
  readonly method: 'POST'
  readonly url: string // as reported by the runtime; see below
  readonly headers: Headers
  readonly rawBody: Uint8Array // the exact bytes received
  readonly signal: AbortSignal // aborted when adapterTimeoutMs elapses
}) => WebhookAdapterResult | Promise<WebhookAdapterResult>

type WebhookAdapterResult =
  | { ok: true; events: readonly CloudEvent[]; deliveryId?: string }
  | { ok: false; reason: 'unauthorized' | 'forbidden' | 'invalid-event' | 'unsupported-media-type' }

A working adapter must, in this order: verify the request's authenticity against rawBody; reject anything it cannot authenticate with unauthorized; only then read and validate the payload; and bind the event source to a verified identity or to configuration. External CMS examples contains complete adapters for Contentful and Sanity.

  • rawBody is the original body as bytes. Check signatures against it, never against re-serialized JSON.
  • url is the URL the runtime reports. Behind a proxy or rewrite it can differ from the URL the sender signed; forwarding headers are neither trusted nor applied.
  • events: [] is an authenticated delivery that needs no invalidation. Return it only after authentication succeeded.
  • deliveryId is for correlation. It never replaces CloudEvent.id.
  • Either function may be synchronous or asynchronous, so provider SDKs that verify and parse in one step fit directly.
  • An adapter cannot return an arbitrary Response and cannot bypass validation, limits or a consumer's budgets.

Trust boundary

An adapter is trusted application code. The library validates what an adapter returns, but it cannot prove that the adapter authenticated the request correctly, and a mistake there is outside the library's control. Prefer a decoder whenever Standard Webhooks already fits.

Bind the event source to a verified identity or to configuration, never to an unsigned header. allowedSources is a policy check, not authentication. Use separate endpoints and credentials for independent trust boundaries.

Standard Webhooks signs the delivery id, timestamp and body, not other headers. The native receiver therefore reads only structured JSON, where all event metadata is inside the signed body. CloudEvents binary mode puts metadata in ce-* headers; support it in an adapter only when that adapter's authentication covers those headers.

Output validation

Decoder and adapter results are checked at runtime even though TypeScript describes them. A malformed result (true, a Response, an unknown reason, extra properties, accessors, a non-array events) is an implementation error and answers 500; it is never read as success. An exception thrown by application code answers 500 with a fixed message.

Events are copied as plain data without running accessors, limited by maxEvents and maxNormalizedBytes (see How size is measured), and validated as CloudEvents. Cyclic structures, class instances such as Date, functions, symbols, non-finite numbers, sparse arrays and invalid binary data are rejected; an invalid individual event answers 400.

adapterTimeoutMs bounds how long the handler waits. On timeout it aborts signal, answers 503, and never invokes the callback or consumer, even if the adapter resolves later. Cancellation is cooperative: JavaScript cannot interrupt synchronous code, and the library does not sandbox decoders or adapters.

Generic cache consumer

createCacheConsumer() from @klnap/cache-invalidation/consumers maps events to your own cache operations. It needs no HTTP, Payload or Next.js.

import * as v from 'valibot'
import { createCacheConsumer } from '@klnap/cache-invalidation/consumers'

const consumer = createCacheConsumer({
  schemas: {
    'catalog.product.changed': v.object({ id: v.string() }),
  },
  rules: {
    'catalog.product.changed': ({ data }) => [
      { layer: 'redis', value: `product:${data.id}` },
      { layer: 'redis', value: 'products' },
    ],
  },
  execute: {
    redis: async ({ value, signal }) => {
      await invalidateRedisKey(String(value), { signal })
    },
  },
})

invalidateRedisKey is application-owned; the package has no Redis dependency.

  • schemas: Standard Schema per event type. Data in rules is typed from them.
  • rules: exact event type to a synchronous function returning operations ({ layer, value }). Every rule type needs a schema, and a rule may only use layers declared in execute. This is checked at compile time and again at runtime.
  • execute: layer name to executor. Executors receive event, data, value and an AbortSignal.
  • Limits: allowedSources, maxEvents (100), maxOperations (1,000), maxNormalizedBytes (256 KiB), executionTimeoutMs (15,000), logger.

Operations for one event run in order. If one fails, the rest of that event's operations are skipped and reported; other events still run. Effects that already ran are not rolled back, and custom operations are never de-duplicated, because they may not be interchangeable. A timed-out executor receives an aborted signal.

Direct consumption

const result = await consumer.consume(events, { signal })
// result.status: 'ok' | 'failed'
// result.results: per-operation { layer, operation, status, error? }

consume() takes already obtained CloudEvents, for example from a queue you operate. Events are validated like any other ingress: envelope, normalized size and event count, source policy, de-duplication, schemas and operation budgets all apply. An invalid batch rejects as a whole before any effect runs (CacheSchemaError, CacheSourceError, CacheForbiddenError or CacheConfigurationError).

Direct consumption is a trusted application-code boundary. It does not authenticate anything. If events arrive from a broker, authenticating and authorizing that transport is your responsibility.

Over HTTP

import { createWebhookHandler } from '@klnap/cache-invalidation/webhooks'

export const webhook = createWebhookHandler({ consumer, secret })
// or: createWebhookHandler({ consumer, adapter: contentfulAdapter })

The handler authenticates and validates the request, then calls consumer.consume(). Schemas and source policy come from the consumer, so neither is validated twice. The handler's body, time and event-count limits apply to the request, its maxNormalizedBytes applies to decoder and adapter output, and the consumer's own maxEvents and maxNormalizedBytes apply to every batch, so the stricter limit wins. See How size is measured.

Next.js consumer

Import from:

import {
  createCacheInvalidationHandler,
  defineCache,
} from '@klnap/cache-invalidation/consumers/next'

Cache definitions

defineCache() accepts:

Property Description
config Global tag profile configuration
tags Recursive tag declarations
paths Recursive path declarations
schemas Standard Schema validators keyed by event type
rules Required rule-definition function
execute Named application-owned executors

The returned CacheDefinition exposes:

  • tags: typed tag helpers.
  • paths: typed path helpers.

It also carries the prepared state the consumer reads; that state is not part of the public contract. The input type is CacheConfig.

Pass the definition itself to createCacheInvalidationHandler({ cache, secret }) or createNextCacheConsumer({ cache }).

Keep cache definitions and signing secrets in server-side modules.

Tag and path declarations

Declarations support nested groups, static strings, and parameterized templates.

export const cache = defineCache({
  tags: {
    products: {
      listing: 'products:[locale]',
      detail: 'product:[locale]:[id]',
    },
  },
  paths: {
    products: {
      listing: '/[locale]/products',
      detail: '/[locale]/products/[slug]',
    },
  },
  rules: ({ tags, paths }) => ({
    'payload.collection.products': {
      tags: [
        tags.products.listing,
        tags.products.detail,
      ],
      paths: [
        paths.products.listing,
        paths.products.detail,
      ],
    },
  }),
})

Call a helper to obtain a concrete value:

cache.tags.products.detail({
  locale: 'en',
  id: '42',
})

cache.paths.products.detail({
  locale: 'en',
  slug: 'example-product',
})

Group names organize helpers; they do not automatically become part of the rendered value.

Placeholders use the form [name]. Names start with an ASCII letter and may contain ASCII letters, digits, and underscores.

For automatic snapshot expansion, values are obtained from the corresponding snapshot fields. String values are supported, and numeric resource identifiers are converted to strings.

Missing, null, empty, or invalid required template values fail planning.

Generated tag helpers fit overlong tag values to 256 characters using a stable hash suffix. Literal tag strings supplied directly to rules must not exceed 256 characters.

Paths are limited to 1024 characters.

Dynamic path values reject unsafe path separators, dot segments, control characters, malformed percent encoding, query delimiters, and fragment delimiters. Brackets in values are percent-encoded.

Declarative rules

Rules match exact CloudEvents event types.

Rules may be grouped under arbitrary organizational labels, but duplicate leaf event types are invalid.

Array shorthand is exclusively for tags:

rules: ({ tags }) => ({
  'payload.collection.products': [
    tags.products,
    tags.product,
  ],
})

An explicit tag-only descriptor is also valid:

rules: ({ tags }) => ({
  'payload.collection.products': {
    tags: [tags.product],
  },
})

Path-only rules use an explicit paths property:

rules: ({ paths }) => ({
  'payload.collection.products': {
    paths: [paths.product],
  },
})

Combined rules use both properties:

rules: ({ tags, paths }) => ({
  'payload.collection.products': {
    tags: [tags.product],
    paths: [paths.product],
  },
})

Do not mix path references into tag arrays or tag references into path arrays.

Pass a declared helper reference without invoking it when automatic snapshot expansion is required.

Scoped route patterns

A string path template expands to a concrete URL.

A tuple declaration represents a native Next.js route pattern with a page or layout scope:

const cache = defineCache({
  paths: {
    productPages: ['/products/[slug]', 'page'],
  },
  rules: ({ paths }) => ({
    'payload.collection.products': {
      paths: [paths.productPages],
    },
  }),
})

Pass the uncalled helper reference to preserve its native route scope.

Calling paths.productPages() returns a string without that scope metadata.

Use concrete paths when only specific old and new URLs need invalidation. Use scoped route patterns when intentionally invalidating the broader route pattern.

Tag profiles

The default tag profile is:

{ expire: 0 }

Configure a different default:

const cache = defineCache({
  config: {
    tags: {
      profile: 'max',
    },
  },
  tags: {
    products: 'products',
  },
  rules: ({ tags }) => ({
    'payload.collection.products': [tags.products],
  }),
})

Override the profile for a group of tags within a rule:

const cache = defineCache({
  config: {
    tags: {
      profile: { expire: 0 },
    },
  },
  tags: {
    products: 'products',
    product: 'product:[id]',
  },
  rules: ({ tags }) => ({
    'payload.collection.products': [
      ['max', [tags.products]],
      tags.product,
    ],
  }),
})

Profile precedence:

  1. Rule-level profile group.
  2. Global config.tags.profile.
  3. { expire: 0 }.

Profiles use Next.js's native revalidateTag() profile type.

Conflicting profiles for the same rendered tag fail planning before cache operations execute.

Paths do not accept tag profiles.

Resource Change V1 expansion

The consumer automatically recognizes event types beginning with:

  • payload.collection.
  • payload.global.

The prefix must have a nonempty suffix.

These events are validated against the built-in Resource Change V1 contract.

Declarative rules expand independently against each non-null before and after snapshot.

This allows a slug change to invalidate both old and new paths, and a relationship change to invalidate both previous and current dependencies.

An absent snapshot does not produce its own snapshot operations.

A custom event type can also use this expansion behavior by registering the exported resourceChangeV1DataSchema object as its local schema.

For automatically recognized Payload events with an additional custom schema, the validated output must still satisfy Resource Change V1.

Affected resources

Affected resources are matched against their own exact event types.

Their declarative rules can run even when the top-level event has no corresponding rule.

Only declarative tag and path operations are expanded for affected resources. Programmable rules and custom executors are not invoked for them.

Affected resources form a flat list, not a recursive dependency graph.

The consumer does not infer relationships that the producer did not include.

Custom schemas

Register application-owned Standard Schema V1 validators by exact event type.

The package does not require a particular schema library.

For example, install Valibot in the receiving application if you choose to use it:

bun add valibot

Or:

npm install valibot

Then define the schema and rule:

import * as v from 'valibot'
import { defineCache } from '@klnap/cache-invalidation/consumers/next'

const productChanged = v.object({
  id: v.string(),
  slug: v.string(),
  categoryIds: v.array(v.string()),
})

export const cache = defineCache({
  schemas: {
    'catalog.product.changed': productChanged,
  },
  tags: {
    product: 'product:[id]',
    category: 'category:[id]',
  },
  paths: {
    product: '/products/[slug]',
  },
  rules: ({ tags, paths, on }) => ({
    'catalog.product.changed': on(
      'catalog.product.changed',
      ({ data }) => ({
        tags: [
          tags.product({ id: data.id }),
          ...data.categoryIds.map((id) =>
            tags.category({ id }),
          ),
        ],
        paths: [
          paths.product({ slug: data.slug }),
        ],
      }),
    ),
  }),
})

The resolver's data type is inferred from the configured schema's output.

Schemas may transform data. The consumer uses the validated output.

Schemas are selected from trusted local configuration by event type. Incoming dataschema values are metadata and are never fetched.

Valibot is an example application dependency, not a runtime dependency of this package.

Programmable rules

Use on(type, resolver) for application-specific dependency expansion.

The resolver receives:

{
  event,
  data,
  tags,
  paths,
}

It can return:

{
  tags,
  paths,
  operations,
}

Each property is optional. Returning null or undefined plans no operations.

Resolvers must be synchronous and side-effect-free.

The consumer plans the entire authenticated request before executing cache operations. Returning a Promise from a resolver is invalid.

Unknown event types without applicable rules are ignored.

Custom executors

Use custom executors when a cache operation depends on application-owned work.

For example, a consumer may need to refresh a search index before invalidating cached search results:

import * as v from 'valibot'
import { defineCache } from '@klnap/cache-invalidation/consumers/next'
import { refreshSearchIndex } from '@/search'

const productChanged = v.object({
  id: v.string(),
})

export const cache = defineCache({
  schemas: {
    'catalog.product.changed': productChanged,
  },
  tags: {
    product: 'product:[id]',
  },
  rules: ({ tags, on }) => ({
    'catalog.product.changed': on(
      'catalog.product.changed',
      ({ data }) => ({
        operations: [
          { layer: 'search', value: data.id },
        ],
        tags: [
          tags.product({ id: data.id }),
        ],
      }),
    ),
  }),
  execute: {
    search: async ({ value, signal }) => {
      if (typeof value !== 'string') {
        throw new TypeError('Expected a product ID')
      }

      await refreshSearchIndex(value, { signal })
    },
  },
})

refreshSearchIndex is application-owned.

A custom operation has the form:

{
  layer: 'executorName',
  value: applicationValue,
}

Its layer must identify a configured executor.

Executors receive:

{
  event,
  data,
  value,
  signal,
}

Execution behavior:

  • All event planning completes before execution starts.
  • Custom operations execute sequentially within their plan.
  • Custom operations are not deduplicated.
  • A failed or timed-out executor prevents subsequent custom operations and native cache operations in that plan.
  • Independent plans continue.
  • Eligible native cache operations are deduplicated before execution.
  • Other eligible native operations continue after an individual native failure.
  • Execution failures produce an unsuccessful handler response.
  • Completed application effects are not rolled back.

Execution timeouts apply per custom executor operation.

The provided AbortSignal is aborted on timeout. Cancellation is cooperative; an executor that ignores the signal may continue running.

The signal is not automatically linked to the incoming request's abort signal.

Custom effects that are unsafe to repeat require application-owned idempotency.

Handler configuration

createCacheInvalidationHandler({
  cache,
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://cms.example.com'],
})

cache is the value returned by defineCache(). The handler accepts any authentication mode:

createCacheInvalidationHandler({ cache, secret, decode }) // Standard Webhooks, custom payload
createCacheInvalidationHandler({ cache, adapter })        // application-owned authentication
Option Default Accepted values
cache Required Value returned by defineCache()
secret / decode / adapter Required One authentication mode
allowedSources Omitted Absolute source URIs
maxBodyBytes 256 KiB Integer from 1 to 16 MiB in bytes
bodyTimeoutMs 15,000 Integer from 1 to 60,000
maxEvents 100 Integer from 1 to 1,000
maxNormalizedBytes 256 KiB for the consumer; maxBodyBytes for the receiver One value, passed to both. The receiver applies it to decoder and adapter output; the consumer applies it to every batch, native ones included, so the stricter effective limit wins
adapterTimeoutMs 15,000 Integer from 1 to 60,000
maxOperations 1,000 Integer from 1 to 10,000
executionTimeoutMs 15,000 Integer from 1 to 60,000
logger Omitted Optional logger

The operation budget counts rendered tag, path, and custom operations before deduplication.

Exceeding the operation budget fails planning before cache execution.

Configuration limits are validated when the handler is created.

The handler is the Next.js consumer wired to the webhook receiver; it adds no execution logic of its own.

Direct Next.js consumption

import { createNextCacheConsumer } from '@klnap/cache-invalidation/consumers/next'

const consumer = createNextCacheConsumer({ cache })
await consumer.consume(events)

createNextCacheConsumer() runs the same validation, planning and execution as the handler without an HTTP request. It calls revalidateTag() and revalidatePath(), which only work inside a running Next.js application (a Route Handler or Server Action). It cannot invalidate a Next.js cache from an external worker or a standalone Node.js process. Direct consumption does not authenticate; see the trust boundary.

Native Next.js behavior

The consumer invokes:

  • revalidateTag(tag, profile).
  • revalidatePath(path, type?).

The default { expire: 0 } profile immediately expires matching tagged data. A subsequent read performs regeneration according to Next.js behavior.

The 'max' profile uses stale-while-revalidate behavior.

cacheLife() controls cached-data lifetime independently of on-demand invalidation.

The adapter does not invoke updateTag() from a Route Handler.

Invalidation does not synchronously regenerate every route, refresh open browsers, invalidate an external CDN, or coordinate independent deployments.

Those responsibilities belong to Next.js and the hosting environment.

External CMS examples

Both adapters below are complete and run in the repository's test suite against signatures produced by the providers' official SDKs (Contentful, Sanity and their tests). Install the SDK you use in your application; this package depends on neither. valibot stands in for any Standard Schema library.

No hosted delivery from either provider has been used to verify them. Each section lists the assumptions about the provider's payloads that you should confirm against your own webhook before relying on them.

What the SDKs actually do (@contentful/node-apps-toolkit 4.1.0, @sanity/webhook 4.0.4), which is why the adapters add checks:

Behavior Contentful Sanity
Signed input Method, path including the query string, body, and the headers named in x-contentful-signed-headers ${timestamp}.${body} and nothing else
Freshness Rejects signatures older than the TTL (it throws) but accepts timestamps in the future None: an old signature stays valid
Timestamp unit Milliseconds Milliseconds
Body A string; verify the original bytes, not re-serialized JSON Same

Headers that the signature does not cover can be set by anyone, so the adapters take neither identity nor source from them.

Contentful

import { verifyRequest } from '@contentful/node-apps-toolkit'
import * as v from 'valibot'
import type { WebhookAdapter } from '@klnap/cache-invalidation/webhooks'

const payload = v.object({
  sys: v.object({
    id: v.pipe(v.string(), v.minLength(1)),
    space: v.object({ sys: v.object({ id: v.string() }) }),
    environment: v.object({ sys: v.object({ id: v.string() }) }),
    revision: v.optional(v.number()),
    version: v.optional(v.number()),
    updatedAt: v.optional(v.string()),
    deletedAt: v.optional(v.string()),
    contentType: v.optional(v.object({ sys: v.object({ id: v.string() }) })),
  }),
})

const OPERATIONS = {
  'ContentManagement.Entry.publish': 'publish',
  'ContentManagement.Entry.unpublish': 'unpublish',
  'ContentManagement.Entry.delete': 'delete',
} as const

export const contentfulAdapter: WebhookAdapter = ({ method, url, headers, rawBody }) => {
  let body: string
  try {
    body = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(rawBody)
  } catch {
    return { ok: false, reason: 'unauthorized' }
  }

  // The SDK rejects old signatures but accepts future ones.
  const timestamp = headers.get('x-contentful-timestamp') ?? ''
  if (!/^\d+$/.test(timestamp) || Number(timestamp) > Date.now() + 5_000) {
    return { ok: false, reason: 'unauthorized' }
  }

  // Only headers named in x-contentful-signed-headers are covered by the signature.
  // Mirror the verifier: it splits the list on ',' and matches names exactly as written.
  const signed = new Set((headers.get('x-contentful-signed-headers') ?? '').trim().split(','))
  if (!signed.has('x-contentful-topic')) return { ok: false, reason: 'unauthorized' }

  const target = new URL(url)
  try {
    const authentic = verifyRequest(
      process.env.CONTENTFUL_WEBHOOK_SECRET!, // 64 characters
      {
        method,
        path: `${target.pathname}${target.search}`,
        headers: Object.fromEntries(headers),
        body,
      },
      60,
    )
    if (!authentic) return { ok: false, reason: 'unauthorized' }
  } catch {
    return { ok: false, reason: 'unauthorized' } // expired signature
  }

  const operation = OPERATIONS[headers.get('x-contentful-topic') as keyof typeof OPERATIONS]
  if (!operation) return { ok: true, events: [] } // authentic, nothing to invalidate

  let sys: v.InferOutput<typeof payload>['sys']
  try {
    sys = v.parse(payload, JSON.parse(body)).sys
  } catch {
    return { ok: false, reason: 'invalid-event' }
  }
  if (sys.space.sys.id !== 'my-space' || sys.environment.sys.id !== 'master') {
    return { ok: false, reason: 'forbidden' }
  }

  // Identity: a provider idempotency key, but only when the signature covers it; otherwise
  // derived from the signed body. An unsigned header is never used.
  const signedKey = signed.has('x-contentful-idempotency-key')
    ? headers.get('x-contentful-idempotency-key')
    : null
  const marker = sys.revision ?? sys.version ?? sys.updatedAt ?? sys.deletedAt
  if (!signedKey && marker === undefined) return { ok: false, reason: 'invalid-event' }

  return {
    ok: true,
    events: [
      {
        specversion: '1.0',
        id: signedKey ?? `${operation}:${sys.id}:${marker}`,
        source: 'urn:contentful:my-space:master', // fixed by configuration
        type: 'contentful.entry.changed',
        subject: sys.id,
        data: {
          id: sys.id,
          operation,
          ...(sys.contentType ? { contentType: sys.contentType.sys.id } : {}),
        },
      },
    ],
  }
}

Wire it with a cache whose rules are keyed by contentful.entry.changed:

export const POST = createCacheInvalidationHandler({
  cache,
  adapter: contentfulAdapter,
  allowedSources: ['urn:contentful:my-space:master'],
})

Identity. A derived id operation:entry:revision is the same on redelivery and differs between distinct operations on one entry, because each publish or unpublish advances the revision (the tests cover publish, unpublish, publish, unpublish at revisions 4 to 7). That is a property of the provider's revisions, not a universal guarantee: two deliveries carrying the same operation, entry and revision are indistinguishable, and so are coalesced when they arrive in one request. De-duplication across requests is your application's job.

Assumptions to confirm against your webhook. That publish, unpublish and delete payloads carry sys.id, sys.space and sys.environment; that a deletion carries a revision, version or deletedAt; and whether x-contentful-idempotency-key is sent and listed in x-contentful-signed-headers (it is used only if it is). A deletion or unpublish never carries a previous slug in this adapter's event; a rule that needs one must read it from your own data. The adapter does not invent previous snapshots.

Sanity

Configure the webhook to deliver raw snapshots, with no domain normalization in the hosted configuration:

{ "before": before(), "after": after() }

Narrow the documents with a projection if they are large: the whole body counts toward maxBodyBytes. Exclude drafts in the webhook filter; the adapter also ignores any drafts. document.

import { decodeSignatureHeader, isValidSignature, SIGNATURE_HEADER_NAME } from '@sanity/webhook'
import * as v from 'valibot'
import type { WebhookAdapter } from '@klnap/cache-invalidation/webhooks'

const snapshot = v.looseObject({
  _id: v.pipe(v.string(), v.minLength(1)),
  _type: v.pipe(v.string(), v.minLength(1)),
  _rev: v.pipe(v.string(), v.minLength(1)),
})
const payload = v.object({ before: v.nullable(snapshot), after: v.nullable(snapshot) })

export const sanityAdapter: WebhookAdapter = async ({ headers, rawBody }) => {
  const header = headers.get(SIGNATURE_HEADER_NAME)
  if (!header) return { ok: false, reason: 'unauthorized' }

  let body: string
  try {
    body = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(rawBody)
    // The SDK has no freshness check; enforce one in both directions.
    const { timestamp } = decodeSignatureHeader(header)
    if (Math.abs(Date.now() - timestamp) > 5 * 60_000) return { ok: false, reason: 'unauthorized' }
    if (!(await isValidSignature(body, header, process.env.SANITY_WEBHOOK_SECRET!))) {
      return { ok: false, reason: 'unauthorized' }
    }
  } catch {
    return { ok: false, reason: 'unauthorized' }
  }

  let parsed: v.InferOutput<typeof payload>
  try {
    parsed = v.parse(payload, JSON.parse(body))
  } catch {
    return { ok: false, reason: 'invalid-event' }
  }
  const { before, after } = parsed
  const current = after ?? before
  if (!current) return { ok: false, reason: 'invalid-event' }
  if (before && after && (before._id !== after._id || before._type !== after._type)) {
    return { ok: false, reason: 'invalid-event' }
  }
  if (current._id.startsWith('drafts.')) return { ok: true, events: [] } // not public content

  // Create, update and delete come from the snapshots themselves.
  const operation = !before ? 'create' : !after ? 'delete' : 'update'
  return {
    ok: true,
    events: [
      {
        specversion: '1.0',
        // The operation is part of the identity: a deletion carries the revision that the
        // previous update produced, so the revision alone would collide with that update.
        id: `${operation}:${current._id}:${current._rev}`,
        source: 'urn:sanity:my-project:production', // bound by configuration
        type: `sanity.document.${current._type}`,
        subject: current._id,
        data: { operation, before, after }, // Resource Change V1
      },
    ],
  }
}

The event data is a Resource Change V1 object, so a Next.js rule can map it as described in Resource Change V1 expansion:

export const cache = defineCache({
  schemas: { 'sanity.document.article': resourceChangeV1DataSchema },
  tags: { articles: 'articles', article: 'article:[id]' },
  rules: ({ tags, on }) => ({
    'sanity.document.article': on('sanity.document.article', ({ data }) => ({
      tags: [
        tags.articles,
        ...[data.before, data.after].flatMap((doc) =>
          typeof doc?._id === 'string' ? [tags.article({ id: doc._id })] : [],
        ),
      ],
    })),
  }),
})

export const POST = createCacheInvalidationHandler({
  cache,
  adapter: sanityAdapter,
  allowedSources: ['urn:sanity:my-project:production'],
})

Verified by the tests: official signature verification, freshness in both directions, identity stable across retries, no collision between an update and a later deletion, rejection of a missing, empty or non-string _rev, of both snapshots being null, and of snapshots that disagree on id or type.

Source binding. sanity-project-id and idempotency-key are not covered by the signature, so the adapter ignores them. The project and dataset are bound to the endpoint and its secret: use one endpoint per project and dataset, and set allowedSources on the consumer as a second check.

Assumptions to confirm against your webhook. That before() and after() return documents carrying _id, _type and _rev for creates, updates and deletes in your configuration, and that the trigger filter delivers the operations you expect. The adapter never invents a previous state: for a create, before is null.

Event protocol

CloudEvents

The package uses CloudEvents 1.0 structured JSON.

A typical event:

{
  "specversion": "1.0",
  "id": "rev_8e64f3ed-95a3-4f4b-8e4d-b92b61c6381a",
  "source": "https://catalog.example.com",
  "type": "catalog.product.updated",
  "time": "2026-12-02T10:00:00.000Z",
  "datacontenttype": "application/json",
  "data": {
    "id": "42"
  }
}

Required envelope attributes:

  • specversion
  • id
  • source
  • type

Event identity is the pair (source, id).

Event types belong to producer applications. Consumers match exact event types according to their own configuration.

Producer helpers require an absolute source URI. The general CloudEvents parser accepts valid URI-reference sources according to its envelope contract.

The envelope supports optional standard attributes and valid extension attributes.

data and data_base64 are mutually exclusive.

The low-level serialization functions support binary Uint8Array data through the structured CloudEvents data_base64 representation. The parser decodes base64 event data.

The generic emit() helper accepts JSON-compatible application data.

Resource Change V1

Resource Change V1 is an optional package-provided data contract used by the Payload adapter.

It is not a Payload-native event format.

type ResourceChangeV1<
  T = Record<string, unknown>,
> = {
  operation: string
  before: T | null
  after: T | null
  affected?: Array<{
    type: string
    data: Record<string, unknown>
  }>
}

For example:

{
  "operation": "update",
  "before": {
    "id": "42",
    "slug": "old-product"
  },
  "after": {
    "id": "42",
    "slug": "new-product"
  }
}

The built-in schema requires:

  • A nonempty operation string.
  • Explicit before and after properties.
  • Plain-object snapshots or null.
  • At least one non-null snapshot.
  • Valid affected-resource entries when supplied.

The snapshot fields remain open application document data.

Affected resources are represented as a flat array of event types and resource data.

The validator excludes prototype-sensitive keys at the outer copied record level. It is not a general-purpose recursive data sanitizer.

Use the exported resourceChangeV1DataSchema to validate this contract in custom integrations.

Standard Schema

Custom event data validation uses Standard Schema V1.

The package implements its built-in Resource Change V1 validator directly.

Consumers may register any compatible Standard Schema implementation.

Validators are resolved exclusively through trusted local event-type configuration.

An event's dataschema attribute is optional metadata. It is never fetched and does not establish trust.

Standard Webhooks

HTTP delivery uses Standard Webhooks.

Requests include:

  • Content-Type
  • webhook-id
  • webhook-timestamp
  • webhook-signature

Signatures authenticate the delivery identifier, timestamp, and exact serialized request body.

The signing key is not transmitted.

The receiver verifies the original body before parsing JSON.

Security and reliability

Report vulnerabilities through the security policy. Security defects in this documentation's examples are in scope for that policy.

Authentication and secrets

  • Use independently generated Standard Webhooks secrets for separately trusted destinations. A secret is whsec_ followed by a nonempty Base64 key; generate 32 random bytes for new integrations.
  • Keep secrets out of browser bundles, event bodies, URLs, logs and public repositories.
  • HTTPS is required for non-loopback destinations unless allowInsecure: true is set. The loopback exceptions are localhost, 127.0.0.1 and [::1]. Destination URLs with credentials are rejected. Do not use allowInsecure for public endpoints. Signing does not encrypt event content.
  • Standard Webhooks verification applies a five-minute timestamp tolerance in either direction, without an override. That limits old replays but does not prevent replay inside the window.
  • Standard Webhooks signs the delivery id, timestamp and body, not other headers. The native receiver therefore reads only structured JSON, where all event metadata is inside the signed body.
  • Authentication is the library's responsibility in native and decoder modes. An adapter is application code the library cannot verify; see the trust boundary. Its output is validated as untrusted data and bounded by maxEvents, maxNormalizedBytes and adapterTimeoutMs.
  • There is no fallback between authentication modes: a failed verification never reaches another mechanism.

Sources, identity and routing

  • allowedSources restricts the event source after authentication. It does not authenticate the source or tell holders of the same secret apart: anyone with the secret can sign an event claiming an allowed source. Use a separate secret, and where appropriate a separate endpoint, for each independently trusted producer.
  • Event identity is (source, id). The package de-duplicates within one request or batch and rejects conflicting duplicates; it does not persist anything, so it is not replay protection.
  • Routing is not authorization. A model filter or predicate chooses recipients; it does not hide fields from them. Recipients that must not see each other's data need separate events or an application-owned projection.
  • Review public Payload access policies, outgoing event fields, schemas and application-owned effects against your trust boundaries. Automatic model selection (collections: true) skips authentication and system collections but cannot judge your custom data.

Limits and logging

Request bodies, read time, event counts, normalized size, operations, executor time and adapter time are bounded; see the option tables. Library-owned code never logs exception messages, secrets, signatures or event bodies, and its HTTP responses carry fixed messages; see Logging. What your own adapters, decoders, executors, hooks and logger implementation record is outside that guarantee.

Reliability boundaries

The package provides bounded, observable, best-effort event delivery. It does not guarantee:

  • Durable or exactly-once delivery.
  • Persistent idempotency or replay prevention.
  • Global event ordering.
  • Automatic detection of database transaction commits.
  • Atomic execution across systems, or rollback of effects after a later operation fails.
  • Complete reverse-relationship discovery.
  • Successful regeneration of every invalidated cache entry.
  • Cross-instance cache coordination, or external CDN and browser cache invalidation.

Transport retries may duplicate application effects, and a new emit() creates a new event identity: do not repeat a business mutation solely to retry a failed delivery. For operations that cannot safely run twice, use an application-owned persistent idempotency mechanism keyed by (source, id). For crash-safe delivery, persist events yourself or use an outbox with appropriate transaction boundaries. For confirmed Payload commit ordering, use explicit deferral and flush only after authoritative commit evidence.

A successful invalidation request is not a substitute for verifying the resulting public content.

Troubleshooting

Symptom Check
No ordinary Payload event Resource opt-in, plugin enabled state, public visibility, actual public-state change, exclusions, and filter
Draft save produces no event Draft-only changes are intentionally ignored when public content is unchanged
Media changes do not invalidate related content Media selection, dependent resource opt-in, supported reference structures, and delivery of the top-level media event
HTTP 401 Matching signing secrets, timestamp freshness, and unmodified request body
HTTP 403 Exact configured CloudEvents source
HTTP 400 Event contract, local schema, required template values, and profile conflicts
HTTP 413 Dispatcher and receiver body/event limits, and the Next.js operation budget
HTTP 500 Callback or executor failures, native cache errors, an adapter or decoder that threw or returned a malformed result
HTTP 503 Adapter or decoder exceeded adapterTimeoutMs
FILTER_FAILED dispatch result A functional target filter threw or returned a non-boolean
Payload plugin throws while building the config An unknown, excluded or non-emitting model in exclude or a target filter, or the removed hooks option
A target receives nothing for a model The model is excluded, not enabled, or not in that target's filter; media events reach a target only through the media or an affected model
Dispatch returns skipped Target selection and event filters
Dispatch returns unknown Ambiguous transport failure; the receiver may already have acted
Old slug remains cached Rules must cover the previous and current representations
Route-pattern invalidation loses scope Pass the declared path helper reference without calling it
Cache remains stale after a Payload save Automatic pre-commit race, delivery failure, cache profile, cache attachment, or deployment coordination
Custom effects run more than once Persistent application-level idempotency is required

Use the local playground to reproduce integration behavior.

Upgrading from 0.4

0.5.0 consolidates the public surface before 1.0. These changes are intentional and have no compatibility aliases.

0.4 0.5
@klnap/cache-invalidation/dispatchers and /dispatchers/http @klnap/cache-invalidation/webhooks
@klnap/cache-invalidation/consumers/http @klnap/cache-invalidation/webhooks
http({ targets }) createWebhookDispatcher({ targets })
HttpDispatcher, HttpDispatcherConfig, HttpDispatchInput, TargetConfig, CacheInvalidationTarget WebhookDispatcher, WebhookDispatcherConfig, WebhookDispatchInput, WebhookTargetConfig, WebhookTarget
createCacheInvalidationHandler({ config: cache.config, … }) createCacheInvalidationHandler({ cache, … }); the definition no longer has a config property
DefineCacheInput CacheConfig
Payload dispatcher: http({ … }) webhooks: { targets: { … } } (a custom dispatcher is still supported)
Payload hooks: ['afterChange', 'afterDelete'] Removed. All lifecycle hooks are installed; use filter to ignore operations. Setting hooks now throws
Local excludeFields replaced the central list Global, central, local and media lists are combined
resolveExcludeFields, readCacheInvalidationExcludeFields Removed. normalizeExcludeFields remains
Dependent discovery re-read each model's custom Discovery uses the effective configuration; centrally enabled globals are now discovered
Webhook secret always required { secret }, { secret, decode } or { adapter }

Behavior fixes worth knowing about:

  • De-duplication no longer treats binary data and a JSON object with the same indexes as identical.
  • media collections other than the slug media no longer fall back to media during locale resolution.
  • A globally excluded or explicitly disabled media collection no longer re-enables itself through media dependency handling.
  • Centrally enabled globals are now found as media dependents.
  • Payload log lines no longer contain exception messages, only the error class and a short code. Alerts that match message text must match the class or code instead.
  • A consumer applies its own maxEvents and maxNormalizedBytes to every batch, native batches included.
  • CacheForbiddenError is exported; it is thrown by consume() for a disallowed source.

Payload and Next.js applications upgrade independently: the event protocol is unchanged, so a 0.4 producer still delivers to a 0.5 receiver and the reverse.

Public API reference

Only the package's declared export entrypoints are supported. Do not deep-import internal source or distribution modules.

Root entrypoint

@klnap/cache-invalidation

Runtime exports:

Export Purpose
createCacheInvalidationProducer Create a framework-independent event producer
CLOUDEVENTS_JSON Structured single-event media type
CLOUDEVENTS_BATCH_JSON Structured batch media type
serializeCloudEvent Serialize one CloudEvent
serializeCloudEventBatch Serialize a CloudEvents batch
parseCloudEvents Validate and parse structured CloudEvents values
CloudEventParseError CloudEvents parsing error
resourceChangeV1DataSchema Built-in Resource Change V1 Standard Schema
validateStandardSchema Validate data against a Standard Schema
matchesEventSelector Match an event against a source/type selector
aggregateDispatchOutcomes Aggregate attempted target delivery results
createDispatchError Construct structured dispatch error information
CacheConfigurationError Configuration error
CacheForbiddenError Disallowed event source
CacheRequestError Request error
CacheSchemaError Schema error
CacheSourceError Source-policy error

Low-level helper signatures:

serializeCloudEvent(event: CloudEvent): string

serializeCloudEventBatch(
  events: readonly CloudEvent[],
): string

parseCloudEvents(
  value: unknown,
  contentType: string,
): CloudEvent[]

matchesEventSelector(
  event: CloudEvent,
  selector: EventSelector,
): boolean

createDispatchError(
  code: string,
  message: string,
): DispatchError

aggregateDispatchOutcomes(
  results: readonly TargetDispatchResult[],
  skippedReason?: DispatchSkippedReason,
): DispatchOutcome

parseCloudEvents() accepts an already parsed value and its content type, not a raw JSON request body.

validateStandardSchema() accepts a Standard Schema and an unknown value, returning a Promise of the validated schema output.

Exported types:

  • CloudEvent
  • CacheInvalidationEventInput
  • CacheInvalidationProducer
  • CacheInvalidationProducerConfig
  • JsonValue
  • EventSelector
  • ResourceChangeV1
  • ResourceChangeV1Data
  • StandardSchemaMap
  • StandardSchemaOutput
  • DeliveryStatus
  • DispatchSkippedReason
  • DispatchError
  • Dispatcher
  • DispatchInput
  • DispatchOutcome
  • EventReference
  • Logger
  • TargetDispatchResult

Payload producer

@klnap/cache-invalidation/producers/payload

Runtime exports:

Export Purpose
cacheInvalidation Create the Payload plugin
deferCacheInvalidationUntilCommit Register request-scoped delivery deferral
normalizeExcludeFields Trim, filter, and deduplicate exclusion paths

Exported types:

  • CacheInvalidationDeferral
  • CacheInvalidationDeferralResult
  • MediaPluginConfig
  • PayloadCacheInvalidationPluginConfig
  • PayloadModelOptions
  • PayloadModelFilter
  • PayloadWebhookConfig
  • PayloadWebhookTarget
  • PayloadCacheInvalidationCustom
  • PayloadCacheInvalidationOptions

Webhooks

@klnap/cache-invalidation/webhooks

Runtime exports:

  • createWebhookDispatcher
  • createWebhookHandler

Exported types:

  • WebhookDispatcher
  • WebhookDispatcherConfig
  • WebhookDispatchInput
  • WebhookTarget
  • WebhookTargetConfig
  • WebhookHandlerOptions
  • WebhookIngressOptions
  • WebhookAdapter
  • WebhookAdapterContext
  • WebhookAdapterResult
  • WebhookDecoder
  • WebhookDecoderContext
  • WebhookDecoderResult
  • WebhookEvent

Generic cache consumer

@klnap/cache-invalidation/consumers

Runtime export:

  • createCacheConsumer

Exported types:

  • CacheConsumer
  • CacheConsumerConfig
  • CacheConsumerLimits
  • ConsumeOptions
  • ConsumeResult
  • ExecutionContext
  • Executor
  • ExecutorMap
  • Operation
  • OperationResult
  • Rule
  • RuleContext

Next.js consumer

@klnap/cache-invalidation/consumers/next

Runtime exports:

  • defineCache
  • createNextCacheConsumer
  • createCacheInvalidationHandler

Exported types:

  • CacheConfig
  • CacheDefinition
  • CacheInvalidationExecutionContext
  • CacheInvalidationExecutor
  • CacheInvalidationHandlerOptions
  • CacheInvalidationRuleContext
  • CacheInvalidationRuleResult
  • CacheProfile
  • PathTemplate
  • TagTemplate

CacheConfig is the declarative input to defineCache(). CacheDefinition is the prepared result: typed tag and path helpers (cache.tags, cache.paths) plus state the consumer reads.

The package's TypeScript declarations provide the exact generic contracts and inferred helper types.

Internal supporting declaration types are not additional public named exports.

Performance

See PERFORMANCE.md for measured workloads, methodology, historical provenance, and reproduction commands.

License

MIT.