Hooks
A hook is a function that Tenon calls at a fixed point of a read, write or delete. Use hooks to change data before it is stored, to check it against other documents, and to react to changes. This collection does all three:
import { defineCollection, ValidationError } from "tenoncms";
export const posts = defineCollection({
fields: {
title: {
type: "text",
required: true,
// Change data: store the title without spaces at the ends
hooks: { beforeChange: [({ value }) => value?.trim()] },
},
featured: { type: "boolean" },
},
hooks: {
beforeChange: {
// Check across documents: only one post can be featured
oneFeatured: async ({ data, id, cms }) => {
if (!data.featured) return;
const other = await cms.findOne("posts", { where: { featured: true } });
if (other && other.id !== id) {
throw new ValidationError({ featured: "Another post is already featured" });
}
},
},
afterChange: [
// React to changes
({ doc, operation }) => console.log(`${operation}: ${doc.title}`),
],
},
});
Hooks run for every call of the local API. The HTTP API and the admin use the local API, so hooks run there too.
For checks of a single value, a field's validate is simpler. See Fields.
Write a hook
A hook gets one object and MAY be async. It MAY return a new value for its main argument, like value, data or docs. Returning nothing keeps the value.
You can set hooks in three places:
- On a field, in the field's
hooks. The hook gets the field'svalue. - On a collection or global, in its
hooks. - On
defineCms(), inhooks. These hooks run for every collection and global.collectionorglobalnames the target.
export default defineCms({
// ...
hooks: {
afterChange: [
({ collection, global, doc }) => console.log("changed", collection ?? global, doc.id),
],
},
});
Lists and records
Each stage takes a list or a record of hooks, and runs them in order. In a record, the keys name the hooks. Code that reuses a collection, like a preset or a plugin, can then leave out one hook and keep the rest:
const { oneFeatured, ...rest } = posts.hooks.beforeChange;
const archive = defineCollection({
...posts,
hooks: { ...posts.hooks, beforeChange: rest },
});
Arguments
Every hook gets:
cms: the local API. See Use thecmsyou receive.user: the signed-in user of the request, ornullfor server code.apiKey: the API key of the request, if it has one.context: one object that all hooks of an operation share.collectionorglobal: the name of the target.draft:trueon a draft save.locale: the language of the operation, with localization.
Field hooks also get data (the whole document), siblingData (the object that holds the field, like a group), originalDoc and path, like seo.title.
The arguments are typed from your fields in these places:
defineCollection()anddefineGlobal()typedata,doc,docsandoriginalDoc.- Field hooks type only
value. - Hooks on
defineCms(), and the hooks of a collection written straight intodefineCms(), are untyped.
req.user is user, req.context is context, and req.payload is cms.Stages (Content)
Each stage runs at one point of an operation. When hooks run shows the order.
| Hook | Runs | Main value | Also gets |
|---|---|---|---|
beforeOperation | First, in every operation of a collection | args | operation |
beforeValidate | On a create or update, before validation | data | operation, id, originalDoc |
beforeChange | After validation, before the write | data | operation, id, originalDoc |
afterChange | After the write. Not on a draft save | doc | operation, previousDoc |
beforeRead | Once per read, before relations load | docs | operation |
afterRead | Once per read, and after each write | docs | operation |
beforeDelete | Before a document is deleted | id, doc | |
afterDelete | After the delete and its onDelete effects | id, doc | |
afterOperation | Last, in every operation of a collection | result | operation, args |
afterError | After an unexpected error. A write rolls back first | error, operation |
Not every stage exists everywhere:
- Collections take every stage.
- Globals take
beforeValidate,beforeChange,afterChange,beforeReadandafterRead. - Fields take
beforeValidate,beforeChange,afterChangeandafterRead.
When hooks run
Every operation runs its steps in a fixed order. Globals have no beforeOperation and afterOperation, so they skip the first and the last step.
A read
find, findOne, findById and getGlobal run these steps:
beforeOperation- The access rules. A read rule can narrow the query to what the user may see.
- The query
beforeRead- Loading the relations. Each related document runs the read hooks of its own collection.
afterRead- Removing the fields that the user may not read, then the
selectof the read afterOperation
A read opens no transaction.
A write
create, update, setGlobal and publish run these steps in one transaction:
beforeOperation- The access rules, and the
updatedAtcheck for edit conflicts. Fields that the user may not change are dropped. - Default values on create, then slugs
beforeValidate- Validation, then the
validatefunctions of the fields beforeChange, then validation again, so a hook cannot store invalid data- The checks for unique values and references
- The write
afterChangeafterReadafterOperation
afterChange. Its hooks get draft: true. The publish later runs every step on the draft, with draft: false.A delete
delete runs these steps in one transaction:
beforeOperation- The access rules
beforeDelete- The check for links in rich text and
linkfields. See Deletes and references. - The delete
- The
onDeleterule of every relation that points to the document afterDeleteafterOperation
Several hooks at one stage
At each stage, the hooks run in this order:
- The field hooks, in field order. A group's hooks run before the hooks of its fields.
- The hooks of the collection or global.
- The hooks of plugins, in the order of
plugins. - The hooks of
defineCms().
Webhooks are queued after the last afterChange and afterDelete hook, so they see the final document.
Inside the transaction
The hooks of a write or delete run inside its transaction. The operation commits after its last hook.
Use the cms you receive
Inside a hook, call other content through the cms argument, not the instance you import:
- It runs in the transaction of the operation. If the operation fails, its changes roll back too.
- It inherits the
locale, thecontextand the drafts or published view of the operation. - It skips the access rules, like the instance you import.
- It is untyped: names and data are plain strings and records.
:memory: libsql, PGlite or a Cloudflare Durable Object, the imported instance waits for the open transaction forever. The request never finishes.Stop loops with context
A hook that writes to its own collection runs the hooks again. context is shared by every hook of the operation and every nested call, so it can stop the loop:
afterChange: [
async ({ doc, cms, context }) => {
if (context.counted) return;
context.counted = true;
await cms.update("posts", doc.id, { views: (doc.views ?? 0) + 1 });
},
],
Keep afterChange fast
A slow afterChange hook delays the commit. Send calls to other services from a job or a webhook. A job that a hook queues with cms.jobs.queue() joins the transaction, so a rollback removes it too.
Errors
A hook that throws stops the operation. A write rolls back every change, including the changes of nested cms calls.
Throw a ValidationError for invalid input. Its keys are field paths, and the admin shows each message next to its field. The key "" holds a message for the whole document:
throw new ValidationError({ "seo.title": "Too long" });
Over HTTP, a ValidationError answers 400 with { message, errors }. Any other error answers 500, without its message.
Unexpected errors
An unexpected error runs the afterError hooks, after the rollback. The hooks of the collection run first, then the ones of defineCms():
export default defineCms({
// ...
hooks: {
afterError: [({ error, operation, collection }) => console.error(operation, collection, error)],
},
});
ValidationError,ConflictErrorandForbiddenErrorare expected, so they run noafterError.- Only the outer operation runs
afterError. A nestedcmscall that fails runs none of its own. - An error inside
afterErroris logged and does not replace the first one.
To report errors to a service like Sentry, use the lifecycle afterError instead. It also sees failed jobs and requests.
cms.import() and restoring a backup skip the content hooks. The lifecycle hook afterImport runs after them.Lifecycle hooks
The hooks on this page run for content. The CMS itself has four more, set directly on defineCms():
| Hook | Runs |
|---|---|
seed | Once per database, to fill a new database |
onInit | On every start |
afterImport | After an import or a restore |
afterError | On every unexpected error |
See Lifecycle hooks.
Related resources
- Lifecycle hooks: code on start, after imports and on errors.
- Writing and drafts: the writes that run these hooks.
- Access control: who may read and write, without a hook.
- Jobs: slow work after a write.
- Webhooks: tell other services about changes.