klnap

cache invalidation

by klnap
Other
v3
>=3.94.1 <4
MIT

Overview

Summary generated from the README

Detects public content changes in Payload collections and globals and emits CloudEvents to named HTTP targets with signed requests. A Next.js consumer maps events to type-safe cache tags and paths and calls native Next.js cache APIs. Generic producers and HTTP consumers work without Payload or Next.js. Requires Payload 3.94.1 or later and Next.js 16.4.5 or later for the integrations. Pre-1.0, so the API may change.

Features

  • Opt-in Payload collections and globals with public before and after snapshots
  • Handles drafts, publication, unpublication and deletion transitions
  • Locale-aware change detection and media dependency tracking
  • Signed HTTP dispatcher with event filtering, batching and retries
  • Declarative Next.js cache tags and rules with a Route Handler
  • Optional deferral until the application confirms transaction commit

Use cases

  • Revalidate Next.js cached product pages and listings when editors publish changes in a separate Payload CMS app
  • Invalidate caches of non-Next.js applications through a framework-independent signed webhook consumer
  • Refresh cached articles when a referenced media upload is updated or deleted

From the author

Declarative, type-safe cache invalidation across applications with a framework-independent event protocol and native Payload CMS, HTTP, and Next.js integrations.

Installation

npm i @klnap/cache-invalidation

0

Stars

0

Forks

0

Open Issues

Yesterday

Last Updated

1.3k

Weekly Downloads

v0.4.3

npm Version

337.9 KB

Unpacked Size

2

Dependencies

GitHub stars

00 since Nov 22

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
npm weekly downloads

966+966 since Nov 25

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026966
Dec 4, 2026642
Dec 3, 2026629
Dec 2, 2026581
Dec 1, 20260
Nov 30, 20261,527
Nov 29, 2026830
Nov 26, 20260
Nov 25, 20260

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

Health Score

77/100Excellent

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

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1469490896-root.svg)](https://payloaddirectory.dev/plugins/1469490896-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1469490896-root"><img src="https://payloaddirectory.dev/badge/1469490896-root.svg" alt="Payload Directory"></a>
Updated Dec 4, 2026Created Nov 24, 2026Published Dec 4, 2026

README

@klnap/cache-invalidation

Event-driven cache invalidation for independent applications, with CloudEvents, signed HTTP delivery, and optional 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.

Contents

Features

  • Framework-independent CloudEvents producers and dispatcher contracts.
  • Automatic public-content change detection in Payload CMS.
  • Support for drafts, publication, localization, and media dependencies.
  • Named HTTP destinations with event filtering, batching, retries, and signed requests.
  • Authenticated HTTP consumers with Standard Schema validation.
  • Declarative, type-safe Next.js cache tags and paths.
  • Automatic invalidation of previous and current resource representations.
  • Programmable cache rules and application-owned executors.
  • Explicit transaction-aware deferral for application-owned Payload transactions.
  • Bounded request processing and structured delivery outcomes.

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

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

DependencySupported 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

Producer
    |
    | CloudEvents
    v
Dispatcher
    |
    | Signed HTTP or application-owned transport
    v
Consumer
    |
    | Application-specific operations
    v
Cache

A producer describes a change. A dispatcher delivers the event. A consumer determines which of its own cache resources need invalidation.

The package separates these responsibilities so that applications can evolve their cache strategies without coupling producers to consumer implementations.

EntrypointResponsibility
@klnap/cache-invalidationGeneric producer, protocol contracts, schemas, errors, and delivery outcomes
@klnap/cache-invalidation/producers/payloadPayload CMS producer
@klnap/cache-invalidation/dispatchersDispatcher implementations
@klnap/cache-invalidation/dispatchers/httpSigned HTTP dispatcher
@klnap/cache-invalidation/consumers/httpFramework-independent HTTP consumer
@klnap/cache-invalidation/consumers/nextNext.js cache definitions and Route Handler

Generic producers, HTTP dispatchers, and generic HTTP consumers do not require Payload or Next.js.

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'
import { http } from '@klnap/cache-invalidation/dispatchers/http'

const plugin = cacheInvalidation({
  source: 'https://cms.example.com',
  collections: {
    products: true,
  },
  dispatcher: http({
    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({
  config: cache.config,
  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

Configure additional Next.js options, including partialPrefetching, according to your application's Next.js version and requirements. They are not cache-invalidation package options.

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.

Framework-independent integration

Neither Payload nor Next.js is required.

Create a producer in the application that owns the data:

import { createCacheInvalidationProducer } from '@klnap/cache-invalidation'
import { http } from '@klnap/cache-invalidation/dispatchers/http'

export const producer = createCacheInvalidationProducer({
  source: 'https://catalog.example.com',
  dispatcher: http({
    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',
  },
})

In the receiving application:

import { createWebhookHandler } from '@klnap/cache-invalidation/consumers/http'
import { invalidateApplicationCache } from './cache'

export const webhook = createWebhookHandler({
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://catalog.example.com'],
  async onEvents(events) {
    await invalidateApplicationCache(events)
  },
})

invalidateApplicationCache is application-owned.

The returned handler accepts a standard Request and returns a Promise<Response>. Mount it in your server or framework.

For example, using Bun:

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

    return webhook(request)
  },
})

Configure the producer to send events to the receiving application's /events endpoint.

Without a configured schema, custom event data is unknown. Validate it before using it in application-specific operations.

Persistent deduplication and crash-safe processing are application responsibilities.

Producer configuration
OptionDescription
sourceRequired stable absolute URI identifying the producer
dispatcherRequired object implementing Dispatcher

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

It accepts:

PropertyDescription
typeRequired nonempty event type
dataOptional JSON-compatible application data
subjectOptional event subject
datacontenttypeOptional data media type
dataschemaOptional schema URI metadata
extensionsOptional 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 either the generic producer or the Payload plugin.

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.

Payload CMS producer

Import from:

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

Configuration

OptionRequiredDefaultDescription
sourceYes—Stable absolute CloudEvents source URI
dispatcherYes—Dispatcher implementation
dataschemaNoOmittedApplication-owned absolute schema URI
enabledNotrueEnable the plugin
collectionsNoNo ordinary collection opt-insPer-collection configuration
globalsNoNo ordinary global opt-insPer-global configuration
excludeFieldsNo[]Default configured comparison exclusions
mediaNoAutomatic upload collection selection when possibleMedia dependency tracking configuration

Setting plugin-level enabled: false returns the incoming Payload configuration without installing plugin hooks.

Resource configuration

Collections and globals are opt-in:

cacheInvalidation({
  source: 'https://cms.example.com',
  dispatcher,
  collections: {
    products: true,
    categories: true,
    articles: {
      excludeFields: ['internalNote'],
    },
  },
  globals: {
    navigation: true,
    homepage: true,
  },
})

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

custom: {
  cacheInvalidation: {
    excludeFields: ['internalNote', 'seo.internalNotes'],
  },
}

Resource-level options:

OptionDescription
enabledEnable or disable the resource
hooksSelect supported lifecycle hooks
excludeFieldsExclude fields from public-state comparison
filterDecide whether a detected public change should emit an event
projectionTransform the outgoing public snapshots

Collections use afterChange and afterDelete by default. Globals support afterChange.

Local custom.cacheInvalidation configuration takes precedence over central configuration:

  • false disables the resource.
  • true enables it while retaining inherited options.
  • An options object overrides the supplied properties and inherits unspecified properties.
  • An options object with enabled: false disables the resource.

The plugin-wide enabled: false disables all plugin behavior regardless of resource configuration.

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

ChangePublic beforePublic after
Draft-only creationAbsentAbsent
Draft-only edit without public changeUnchangedUnchanged
First publicationnullPublished representation
Published updatePrevious representationCurrent representation
UnpublicationPublished representationnull
Published resource deletionPublished representationnull

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.

For ordinary resources, exclusion precedence is:

  1. Explicit local resource exclusions, including an empty array.
  2. Plugin configuration for that collection or global.
  3. Plugin-wide exclusions.
  4. No additional configured exclusions.

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 opted in.

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 resolved from media-local exclusions, applicable dependent collection exclusions, media-specific plugin exclusions, and plugin-wide exclusions.

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

HTTP target filters therefore match the media event's own type and source, not the types of its affected resources.

A consumer requiring media-driven article invalidation must receive the relevant media events.

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.

Next.js consumer

Import from:

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

Cache definitions

defineCache() accepts:

PropertyDescription
configGlobal tag profile configuration
tagsRecursive tag declarations
pathsRecursive path declarations
schemasStandard Schema validators keyed by event type
rulesRequired rule-definition function
executeNamed application-owned executors

The returned object contains:

  • config: normalized handler configuration.
  • tags: typed tag helpers.
  • paths: typed path helpers.

Create the Route Handler separately with createCacheInvalidationHandler({ config: cache.config, secret }).

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({
  config: cache.config,
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://cms.example.com'],
})
OptionDefaultAccepted values
configRequiredConfiguration returned by defineCache()
secretRequiredStandard Webhooks signing secret
allowedSourcesOmittedAbsolute source URIs
maxBodyBytes256 KiBInteger from 1 to 16 MiB in bytes
bodyTimeoutMs15,000Integer from 1 to 60,000
maxEvents100Integer from 1 to 1,000
maxOperations1,000Integer from 1 to 10,000
executionTimeoutMs15,000Integer from 1 to 60,000
loggerOmittedOptional 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.

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.

HTTP dispatcher

import { http } from '@klnap/cache-invalidation/dispatchers/http'

The /dispatchers entrypoint exports the same HTTP implementation.

Named targets

const dispatcher = http({
  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. They do not inspect application data or affected-resource records.

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.

Configuration

OptionDefaultAccepted values
targetsRequiredNamed target configuration
timeoutMs15,000Integer from 1 to 60,000
deadlineMs5,000Integer from 1 to 300,000
retries2Integer from 0 to 10
retryDelayMs200Integer from 0 to 60,000
maxEventItems100Integer from 1 to 1,000
maxBodyBytes256 KiBInteger from 1 to 16 MiB in bytes
allowInsecurefalseBoolean

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

StatusMeaning
acceptedAll attempted deliveries were accepted
partialSome attempted deliveries were accepted and others were not
rejectedAll attempted deliveries were rejected
failedDelivery failed without acceptance or an unresolved ambiguous outcome
unknownDelivery may have caused remote effects, but acceptance is unconfirmed
skippedNo 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.

Generic HTTP consumer

createWebhookHandler() from @klnap/cache-invalidation/consumers/http authenticates and validates incoming CloudEvents before invoking an application-owned callback. The framework-independent integration example shows a minimal receiver; this section documents its options and behavior.

Configuration

OptionDefaultAccepted values
secretRequiredStandard Webhooks signing secret
allowedSourcesOmittedAbsolute source URIs
schemasOmittedStandard Schema validators keyed by event type
onEventsRequiredSynchronous or asynchronous callback
maxBodyBytes256 KiBInteger from 1 to 16 MiB in bytes
bodyTimeoutMs15,000Integer from 1 to 60,000
maxEvents100Integer from 1 to 1,000
loggerOmittedOptional logger

Validation

The consumer:

  1. Checks the HTTP method and content type.
  2. Reads the raw request body within configured byte and time limits.
  3. Verifies the Standard Webhooks signature and timestamp.
  4. Parses and validates CloudEvents.
  5. Applies the configured source policy.
  6. Deduplicates identical event identities within the request.
  7. Validates locally configured event schemas.
  8. Invokes the application callback for accepted events.

Conflicting duplicate events with the same (source, id) identity reject the complete request.

When schemas is omitted or empty, event data remains unknown.

A nonempty schema map validates matching event types and ignores unmapped types.

Any configured schema failure rejects the request before the callback executes.

Empty or fully filtered batches do not invoke the callback.

Typed application events

import * as v from 'valibot'
import { createWebhookHandler } from '@klnap/cache-invalidation/consumers/http'
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)
    }
  },
})

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. It cannot roll back those effects.

A subsequent delivery retry may invoke the callback again.

HTTP responses

Both HTTP consumers accept POST requests with supported structured CloudEvents JSON media types.

StatusMeaning
200Request processed without a reported handler failure
400Invalid event, configured schema, or request; Next.js planning failures also use this status
401Invalid authentication or signature timestamp
403Event source not allowed
405Unsupported HTTP method
408Request body read timed out
413Request body, event, or Next.js operation budget limit exceeded
415Unsupported content type
500Callback, execution, or unexpected handler failure

Responses use JSON and include an X-Cache-Request-Id header.

The generic consumer's success response contains:

{
  requestId: string
  accepted: number
  ignored: number
}

The Next.js consumer reports:

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

Unhandled Next.js events are reported as skipped results.

Next.js execution failures can return per-operation results with HTTP 500. Unexpected handler failures use the generic sanitized error response.

Standard receiver error bodies include a request identifier and a sanitized error string.

The method and content-type rejection bodies contain the error string without a body-level request identifier.

Use the HTTP status, returned results, and request identifier for diagnostics. Do not treat an accepted webhook as proof of cache regeneration.

Logging

Both HTTP 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
}

Receiver diagnostics include request and delivery metadata, status, and error classification.

The HTTP receiver does not log the request body or signing secret. Logger callback failures do not replace the receiver's response.

Payload uses its own logging pipeline. Application-provided errors may contain arbitrary message text, so avoid placing secrets or sensitive data in error messages.

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 trust

Use independently generated Standard Webhooks signing secrets for separately trusted destinations.

Secrets must use the whsec_ prefix followed by a valid, nonempty Base64-encoded key accepted by the Standard Webhooks implementation.

Generate a 32-byte random key for new integrations.

Keep secrets out of:

  • Browser bundles.
  • Event bodies.
  • URLs.
  • Logs.
  • Public repository files.

HTTPS is required for non-loopback HTTP destinations unless allowInsecure: true is explicitly configured.

The built-in loopback exceptions are localhost, 127.0.0.1, and [::1].

Destination URLs containing username or password components are rejected.

Do not use allowInsecure for public production endpoints. Request signing does not encrypt event content or metadata.

The Standard Webhooks implementation used in the verified release environment applies a five-minute timestamp tolerance in either direction. The package does not expose a tolerance override.

Timestamp verification limits old replay attempts but does not prevent replay within the accepted window.

The package performs request-local duplicate detection, not persistent replay protection.

allowedSources restricts event source values after signature verification. It does not independently authenticate the source URI or distinguish different holders of the same signing secret.

Anyone with the signing secret can create a signed event claiming an allowed source.

Review public Payload access policies, outgoing event fields, custom schema validation, and application-owned effects according to your deployment's trust boundaries.

Report vulnerabilities through the security policy.

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.
  • Complete reverse-relationship discovery.
  • Successful regeneration of every invalidated cache entry.
  • Cross-instance cache coordination.
  • External CDN or browser cache invalidation.

Transport retries may duplicate application effects.

A new producer emit() call creates a new event identity. Do not repeat a business mutation solely to retry a failed delivery.

For operations that cannot safely execute more than once, use an application-owned persistent idempotency mechanism keyed by (source, id).

For crash-safe delivery, use application-owned durable event persistence or 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

SymptomCheck
No ordinary Payload eventResource opt-in, plugin enabled state, public visibility, actual public-state change, exclusions, and filter
Draft save produces no eventDraft-only changes are intentionally ignored when public content is unchanged
Media changes do not invalidate related contentMedia selection, dependent resource opt-in, supported reference structures, and delivery of the top-level media event
HTTP 401Matching signing secrets, timestamp freshness, and unmodified request body
HTTP 403Exact configured CloudEvents source
HTTP 400Event contract, local schema, required template values, and profile conflicts
HTTP 413Dispatcher and receiver body/event limits, and the Next.js operation budget
HTTP 500Callback or executor failures, native cache errors, and sanitized diagnostics
Dispatch returns skippedTarget selection and event filters
Dispatch returns unknownAmbiguous transport failure; the receiver may already have acted
Old slug remains cachedRules must cover the previous and current representations
Route-pattern invalidation loses scopePass the declared path helper reference without calling it
Cache remains stale after a Payload saveAutomatic pre-commit race, delivery failure, cache profile, cache attachment, or deployment coordination
Custom effects run more than oncePersistent application-level idempotency is required

Use the local playground to reproduce integration behavior.

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:

ExportPurpose
createCacheInvalidationProducerCreate a framework-independent event producer
CLOUDEVENTS_JSONStructured single-event media type
CLOUDEVENTS_BATCH_JSONStructured batch media type
serializeCloudEventSerialize one CloudEvent
serializeCloudEventBatchSerialize a CloudEvents batch
parseCloudEventsValidate and parse structured CloudEvents values
CloudEventParseErrorCloudEvents parsing error
resourceChangeV1DataSchemaBuilt-in Resource Change V1 Standard Schema
validateStandardSchemaValidate data against a Standard Schema
matchesEventSelectorMatch an event against a source/type selector
aggregateDispatchOutcomesAggregate attempted target delivery results
createDispatchErrorConstruct structured dispatch error information
CacheConfigurationErrorConfiguration error
CacheRequestErrorRequest error
CacheSchemaErrorSchema error
CacheSourceErrorSource-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:

ExportPurpose
cacheInvalidationCreate the Payload plugin
deferCacheInvalidationUntilCommitRegister request-scoped delivery deferral
normalizeExcludeFieldsTrim, filter, and deduplicate exclusion paths
`readCacheInvalidati
README truncated — read the full version on GitHub

Similar plugins