Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions .changeset/events-and-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
---

Add the events & hooks system. Synchronous collection hooks gain the
`preValidate` / `postValidate` / `preDelete` / `postRead` stages (the existing
`beforeValidate` / `beforeChange` / `beforeDelete` / `afterRead` names stay as
aliases). A new durable async event system delivers `defineEventHandler`
`preValidate` / `postValidate` / `preDelete` / `postRead` stages. A new durable async event system delivers `defineEventHandler`
handlers after commit: event rows are written to a transactional outbox in the
same transaction as the content change, then claimed and delivered at-least-once
with exponential backoff, dead-lettering, and per-handler auto-disable. Handlers
Expand Down
25 changes: 25 additions & 0 deletions .changeset/hooks-events-framing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
'@tanstack/cms-core': minor
---

Hooks are the pre-commit consultation ("anything we should know before we go
in?"); events are the post-commit announcement. The API now says so.

**Breaking:** the legacy collection hook aliases are removed. Rename them:

| Removed | Use |
| ---------------- | -------------- |
| `beforeValidate` | `preValidate` |
| `beforeChange` | `postValidate` |
| `beforeDelete` | `preDelete` |
| `afterRead` | `postRead` |

**Deprecated:** the synchronous post-commit hooks `afterChange` and
`afterDelete`. They still run, but will be removed before 1.0. Move the work to
a durable `defineEventHandler` in `defineCms({ eventHandlers })`, on
`document.created` / `document.updated` (for `afterChange`) or
`document.deleted` (for `afterDelete`).

Outside production (`NODE_ENV !== 'production'`), a hook that takes longer
than the documented 50ms guideline logs a warning once per collection and
stage per process.
22 changes: 14 additions & 8 deletions .claude/skills/payload-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,21 @@ reads. Public writes (`create: () => true` for form submissions) belong in an
app server function that calls `commitDocument` from
`@tanstack/cms-core/server`, not in `collection.access`.

**Hooks.** `beforeValidate`, `beforeChange`, `afterChange`, `afterRead`,
`beforeDelete`, `afterDelete` map 1:1 and may be async. Arguments differ:
**Hooks.** Core hooks are a pre-commit consultation; anything after the
commit is an event. Payload `beforeValidate` → `preValidate`, `beforeChange`
→ `postValidate`, `beforeDelete` → `preDelete`, `afterRead` → `postRead`; all
may be async. Payload `afterChange` / `afterDelete` → a durable
`defineEventHandler` on `document.created` / `document.updated` /
`document.deleted` in `defineCms({ eventHandlers })` (core's own
`afterChange` / `afterDelete` hooks are deprecated). Arguments differ:
Payload `{ data, originalDoc, req, operation }` → core
`{ doc, id, operation, actor }` (before/after change), `{ doc, id }`
(`afterRead`), `{ id, actor }` (delete hooks). Return the transformed doc from
`before*`/`afterRead`; throw to abort a write. Replace `req.payload.find(…)`
with `queryDocuments`/`readDocument` from `@tanstack/cms-core/server`. Hooks
that only fan out to other systems (cache purges, search indexing) usually
become `defineCms({ webhooks })` instead. No equivalent: `beforeOperation`,
`{ doc, id, operation, actor }` (`preValidate` / `postValidate`),
`{ doc, id }` (`postRead`), `{ id, actor }` (`preDelete`). Return the
transformed doc from `preValidate` / `postValidate` / `postRead`; throw to
abort a write. Keep hooks under about 50ms. Replace `req.payload.find(…)` with
`queryDocuments`/`readDocument` from `@tanstack/cms-core/server`. Hooks that
only fan out to other systems (cache purges, search indexing) usually become
`defineCms({ webhooks })` instead. No equivalent: `beforeOperation`,
`afterOperation`, `beforeRead`, `afterError`, auth hooks.

**Auth.** Payload's `users` collection becomes
Expand Down
2 changes: 1 addition & 1 deletion app/prm/src/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const person = defineCollection({
// Search priority: headline, role, name, aliasesText, notes
search: { fields: ['headline', 'role', 'name', 'aliasesText', 'notes'] },
hooks: {
beforeValidate: ({ doc }) => {
preValidate: ({ doc }) => {
const next = { ...doc }
const rawAliases = Array.isArray(next.aliases) ? next.aliases : []
const cleaned = rawAliases
Expand Down
2 changes: 1 addition & 1 deletion docs/agents/review-queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ runOp(name, input, actor) permission, collection, and field rules
│
▼
stageWrite({ collection, docId, type, doc, actor, instruction })
├─ runs beforeValidate hooks and validates against the collection schema
├─ runs preValidate hooks and validates against the collection schema
├─ checks field rules (unique, min/max, validate)
├─ records the `before` snapshot and the document's current revision
└─ inserts or coalesces one pending change per document
Expand Down
2 changes: 1 addition & 1 deletion docs/api/cms-core-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ Paginated summaries for one collection: the admin list view. Pending creates (st
function readDocument(collectionName: string, id: string): Promise<Doc | null>
```

The committed document, after `afterRead` hooks.
The committed document, after `postRead` hooks.

### `readDocumentWithPending(collection, id)`

Expand Down
2 changes: 1 addition & 1 deletion docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ function isFieldVisible(field: Field, siblings: Record<string, JsonValue | undef
| `StandardSchemaV1Like` | The subset of the Standard Schema v1 interface the engine calls (`'~standard'.validate`). |
| `Collection` | A collection definition (`name`, `label`, `titleField`, `fields`, `path?`, `isSingleton?`, `readOnly?`, `storage?`, `migrations?`, `access?`, `hooks?`, `admin?`, and field-role overrides). See [Collection options](../schema/collections-and-fields#collection-options). |
| `CollectionAdmin` | `{ columns?: Array<string>; defaultSort?: { field: string; dir?: 'asc' \| 'desc' } }`. |
| `CollectionHooks` | Synchronous lifecycle hooks: `preValidate`, `postValidate`, `preDelete`, `postRead` (and the legacy aliases `beforeValidate`, `beforeChange`, `beforeDelete`, `afterRead`), plus `afterChange` / `afterDelete`. See [Events & Hooks](../architecture/events-and-hooks). |
| `CollectionHooks` | Pre-commit lifecycle hooks: `preValidate`, `postValidate`, `preDelete`, plus the `postRead` response transform. `afterChange` / `afterDelete` are deprecated in favour of `defineEventHandler`. See [Events & Hooks](../architecture/events-and-hooks). |
| `ChangeHookArgs` | `{ doc, id, operation, actor }` — what a pre-commit mutating hook receives. |
| `BlockType` | `{ type, label, fields, component? }`. |
| `Block` | `{ _type: string } & { [key: string]: JsonValue }`. |
Expand Down
51 changes: 40 additions & 11 deletions docs/architecture/events-and-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Events & Hooks
id: events-and-hooks
order: 5
description: "The two halves of reacting to content changes in TanStack CMS: synchronous collection hooks that run inside the write transaction and may mutate or veto, and durable asynchronous event handlers delivered after commit with at-least-once retries, loop prevention, and cron schedules."
description: "The two halves of reacting to content changes in TanStack CMS: collection hooks, a pre-commit consultation that may mutate or veto a write, and durable asynchronous event handlers, a post-commit announcement delivered with at-least-once retries, loop prevention, and cron schedules."
keywords:
- tanstack cms
- events
Expand All @@ -15,16 +15,18 @@ keywords:
- causationId
---

TanStack CMS reacts to content changes on two sides of one bright line — **the commit**.
TanStack CMS reacts to content changes on two sides of one bright line: **the commit**. Think of a write as a game.

- **Before commit:** synchronous **hooks** run inside the write request (and, for the pre-commit stages, inside the database transaction). They may rewrite the document and they may veto the write by throwing. Use them for work that must be fast, deterministic, and part of the write itself — normalizing input, deriving fields, enforcing an invariant.
- **After commit:** asynchronous **event handlers** run off the write path. They receive an immutable record of what already happened. They can cause *new* writes but can never alter or undo the change that fired them. Use them for anything slow, networked, or allowed to fail — sending mail, calling an API, recomputing a derived collection.
- **Hooks ask "we're about to go into the game: anything you want to make us aware of before we do?"** They are a pre-commit consultation. Collection hooks run inside the write request (and, for the pre-commit stages, inside the database transaction). They may rewrite the document, and they may veto the write by throwing. Use them for work that must be fast, deterministic, and part of the write itself: normalizing input, deriving fields, enforcing an invariant.
- **Events announce "we won the game!"** They are a post-commit announcement. Event handlers run asynchronously, off the write path, and receive an immutable record of what already happened. They can cause *new* writes but can never alter or undo the change that fired them. Use them for anything slow, networked, or allowed to fail: sending mail, calling an API, recomputing a derived collection.

The commit is a firewall between the two. Nothing a hook does survives a vetoed write, and nothing an event handler does can reach back across the commit.

The rule of thumb: *if it can be slow or fail, it is an event, not a hook.*

## Synchronous hooks
## Hooks: before the game

Hooks live on a collection. Every hook may be async; the engine awaits it. Throwing from a pre-commit hook aborts the write and rolls back the transaction — no document, no revision, no events.
Hooks live on a collection. Every hook may be async; the engine awaits it. Throwing from a pre-commit hook aborts the write and rolls back the transaction: no document, no revision, no events.

```ts
import { defineCollection, slugify } from '@tanstack/cms-core'
Expand Down Expand Up @@ -58,11 +60,38 @@ export const post = defineCollection({
| `preDelete` | before the delete transaction | — | throw → rollback |
| `postRead` | after a read, before the response | yes — response only, never stored | — |

The older names `beforeValidate`, `beforeChange`, `beforeDelete`, and `afterRead` remain as stable aliases for `preValidate`, `postValidate`, `preDelete`, and `postRead`. When both a new name and its alias are set, the new name runs first and the alias sees its output (a pipeline). `afterChange` / `afterDelete` still fire post-commit, but prefer an async handler for anything that can be slow or fail.
`postRead` runs on reads rather than writes, so it is not part of the consultation before a commit. It is a response transform that shares the hook shape.

> **The 50ms guideline.** Hooks must be fast and deterministic. Network calls, LLM calls, or any unbounded work in a hook blocks the request and risks the transaction, so move it to an event handler. Outside production (`NODE_ENV !== 'production'`), the engine times every hook and logs one warning per hook (per collection and stage, per process) that takes longer than 50ms.

### Deprecated: `afterChange` and `afterDelete`

`afterChange` and `afterDelete` run synchronously *after* the commit, inside the request. That is announcing the result in the style of a consultation: the work blocks the response, isn't retried, and is lost on a crash. Both are deprecated and will be removed before 1.0. Move the work to a durable event handler:

| Deprecated hook | Event handler |
|---|---|
| `afterChange` | `on: 'document.created'` and `on: 'document.updated'` (plus `document.published` / `document.unpublished` if only publish state matters) |
| `afterDelete` | `on: 'document.deleted'` |

```ts
// Before
hooks: {
afterChange: async ({ id }) => { await purgeCache(`/post/${id}`) },
}

// After
eventHandlers: [
defineEventHandler({
on: 'document.updated',
collection: 'post',
run: async ({ event }) => { await purgeCache(`/post/${event.documentId}`) },
}),
]
```

> **The 50ms guideline.** Synchronous hooks must be fast and deterministic. Network calls, LLM calls, or any unbounded work in a hook blocks the writer and risks the transaction — move it to an event handler.
The legacy alias names `beforeValidate`, `beforeChange`, `beforeDelete`, and `afterRead` were removed. Rename them to `preValidate`, `postValidate`, `preDelete`, and `postRead`.

## Asynchronous event handlers
## Events: after the game

`defineEventHandler` registers a handler, and `defineCms({ eventHandlers })` installs it. Handlers are delivered **at-least-once** from a durable outbox, so they must be idempotent (check-then-write is the blessed pattern).

Expand Down Expand Up @@ -208,5 +237,5 @@ push updates; a full-read fallback recovers missed events.

## When to use which

- **Hook** — the work is part of the write, must be fast, and should block or veto it: slugify, derive a field, enforce an invariant, transform a response.
- **Event handler** — the work reacts to a committed change and may be slow or fail: send a notification, call an external API, recompute a derived collection, run a nightly job.
- **Hook** (before the game) — the work is part of the write, must be fast, and should block or veto it: slugify, derive a field, enforce an invariant, transform a response.
- **Event handler** (after the game) — the work reacts to a committed change and may be slow or fail: send a notification, call an external API, recompute a derived collection, run a nightly job. This includes anything you would once have put in `afterChange` or `afterDelete`.
2 changes: 1 addition & 1 deletion docs/architecture/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ sequenceDiagram
Op->>Core: commitDocument()
Core->>Core: preValidate hooks, schema validation, field rules, postValidate hooks
Core->>Core: transaction: re-check access and expectedRevision, write document, record revision, enqueue events and webhooks
Core->>Core: afterChange hook, emit change / publish
Core->>Core: emit change / publish
Core-->>Op: committed document
Op-->>DB: staged: false
DB->>Op: refetch listPublishedDocuments
Expand Down
5 changes: 3 additions & 2 deletions docs/migration/from-payload.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ Payload v3 and TanStack CMS are both **code-first TypeScript CMSs** with schema
| `admin.defaultColumns` | `admin.columns` | Scalar fields after the title column |
| `defaultSort: '-field'` | `admin.defaultSort: { field, dir: 'desc' }` | |
| `access.{read,create,update,delete}` | `access.{read,create,update,delete}` (+ `publish`, `write`) | Role arrays or `({ session, doc }) => boolean` |
| `hooks.*` | `hooks.*` | `beforeValidate`, `beforeChange`, `afterChange`, `afterRead`, `beforeDelete`, `afterDelete` |
| `hooks.beforeValidate` / `beforeChange` / `beforeDelete` / `afterRead` | `hooks.preValidate` / `postValidate` / `preDelete` / `postRead` | |
| `hooks.afterChange` / `afterDelete` | `defineEventHandler` on `document.created` / `document.updated` / `document.deleted` | Post-commit work is an event, not a hook |
| `versions.drafts` | Built in | Saving a published doc stores a draft; `_status` → `published` |
| `schedulePublish` | `publishAt` / `unpublishAt` | System fields on every document |
| `upload: true` collection | Media library + `image` fields | Not a content collection |
Expand Down Expand Up @@ -97,7 +98,7 @@ Field options carry over by name: `required`, `unique`, `index`, `defaultValue`,
- `({ req: { user } }) => Boolean(user)` becomes `({ session }) => session.isAuthenticated`; a role check becomes a role array such as `['editor', 'admin']`.
- Published documents are always publicly readable, so Payload's common `read: () => true` needs no rule. `access.read` governs drafts and admin reads.
- Public writes (form submissions) belong in an app server function that calls `commitDocument` from `@tanstack/cms-core/server`.
- Hook arguments change from `{ data, originalDoc, req, operation }` to `{ doc, id, operation, actor }`. Return the transformed doc from `before*` hooks and throw to abort. Replace `req.payload.find()` with `queryDocuments()` or `readDocument()`. Fan-out hooks (cache purges, search sync) often become `defineCms({ webhooks })`.
- Hook arguments change from `{ data, originalDoc, req, operation }` to `{ doc, id, operation, actor }`. Return the transformed doc from `preValidate` / `postValidate` hooks and throw to abort. Replace `req.payload.find()` with `queryDocuments()` or `readDocument()`. Fan-out hooks (cache purges, search sync) often become `defineCms({ webhooks })`.

### Blocks (`pages.layout` → `page.blocks`)

Expand Down
2 changes: 1 addition & 1 deletion docs/schema/building-pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Readers see published documents only. Sessions with `content.read` (viewers and

## Loading content

There are three ways to read content from a route loader. All of them respect drafts, field access rules, and `afterRead` hooks.
There are three ways to read content from a route loader. All of them respect drafts, field access rules, and `postRead` hooks.

### 1. The CMS server functions

Expand Down
38 changes: 22 additions & 16 deletions docs/schema/collections-and-fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -404,43 +404,49 @@ export const invoice = defineCollection({

## Hooks

Every hook may be async; the engine awaits it. Throwing from a `before*` hook aborts the write.
A hook is the engine asking, just before a commit, "anything you want to make us aware of before we go in?" Hooks may rewrite the document or veto the write by throwing. Anything that reacts to the result after the commit is an [event handler](../architecture/events-and-hooks) instead. Every hook may be async; the engine awaits it. Keep each one under about 50ms: outside production the engine warns once per hook that runs longer.

| Hook | Arguments | Runs |
| --- | --- | --- |
| `beforeValidate` | `{ doc, id, operation, actor }` | Before validation, on saves and when a change is staged. May return a transformed doc (merged over the input). |
| `beforeChange` | `{ doc, id, operation, actor }` | After validation, right before a commit (direct save or approval). May return a transformed doc. |
| `afterChange` | `{ doc, id, operation, actor }` | After a commit, with the committed document. |
| `afterRead` | `{ doc, id }` | On every read. May return a transformed doc. |
| `beforeDelete` | `{ id, actor }` | Before a delete commits. |
| `afterDelete` | `{ id, actor }` | After a delete commits. |
| `preValidate` | `{ doc, id, operation, actor }` | Before validation, on saves and when a change is staged. May return a transformed doc (merged over the input). |
| `postValidate` | `{ doc, id, operation, actor }` | After validation, right before a commit (direct save or approval). May return a transformed doc, which is re-validated. |
| `preDelete` | `{ id, actor }` | Before a delete commits. Throw to veto. |
| `postRead` | `{ doc, id }` | On every read. May return a transformed doc (the response only; never stored). |
| `afterChange` | `{ doc, id, operation, actor }` | **Deprecated.** After a commit, with the committed document. Use a `document.created` / `document.updated` event handler. |
| `afterDelete` | `{ id, actor }` | **Deprecated.** After a delete commits. Use a `document.deleted` event handler. |

`operation` is `'create'` or `'update'`. `actor` identifies who made the change (`human`, an agent name such as `content-agent`, `mcp`, or `webmcp`).

```ts validate=type
import { defineCollection } from '@tanstack/cms-core'
import { defineCollection, defineEventHandler } from '@tanstack/cms-core'

export const article = defineCollection({
name: 'article',
label: 'Articles',
titleField: 'title',
hooks: {
beforeValidate: ({ doc }) => ({
preValidate: ({ doc }) => ({
...doc,
title: typeof doc.title === 'string' ? doc.title.trim() : doc.title,
}),
afterChange: async ({ id, operation }) => {
await fetch('https://example.com/revalidate', {
method: 'POST',
body: JSON.stringify({ id, operation }),
})
},
beforeDelete: ({ id }) => {
preDelete: ({ id }) => {
if (id === 'home') throw new Error('The home article cannot be deleted.')
},
},
fields: [{ name: 'title', label: 'Title', type: 'text', required: true }],
})

// Post-commit work goes in an event handler: `defineCms({ eventHandlers: [revalidate] })`.
export const revalidate = defineEventHandler({
on: 'document.updated',
collection: 'article',
run: async ({ event }) => {
await fetch('https://example.com/revalidate', {
method: 'POST',
body: JSON.stringify({ id: event.documentId }),
})
},
})
```

For outgoing notifications on publish, unpublish, and delete, prefer [webhooks](../api/cms-core#cmswebhook-and-cmswebhookevent), which are signed and retried.
Expand Down
Loading
Loading