Working with Content

Hooks

Run code when content is read, written or deleted.

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:

cms/collections/posts.ts
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's value.
  • On a collection or global, in its hooks.
  • On defineCms(), in hooks. These hooks run for every collection and global. collection or global names the target.
tenon.config.ts
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 the cms you receive.
  • user: the signed-in user of the request, or null for server code.
  • apiKey: the API key of the request, if it has one.
  • context: one object that all hooks of an operation share.
  • collection or global: the name of the target.
  • draft: true on 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() and defineGlobal() type data, doc, docs and originalDoc.
  • Field hooks type only value.
  • Hooks on defineCms(), and the hooks of a collection written straight into defineCms(), are untyped.
Coming from Payload? The hook names are the same. 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.

HookRunsMain valueAlso gets
beforeOperationFirst, in every operation of a collectionargsoperation
beforeValidateOn a create or update, before validationdataoperation, id, originalDoc
beforeChangeAfter validation, before the writedataoperation, id, originalDoc
afterChangeAfter the write. Not on a draft savedocoperation, previousDoc
beforeReadOnce per read, before relations loaddocsoperation
afterReadOnce per read, and after each writedocsoperation
beforeDeleteBefore a document is deletedid, doc
afterDeleteAfter the delete and its onDelete effectsid, doc
afterOperationLast, in every operation of a collectionresultoperation, args
afterErrorAfter an unexpected error. A write rolls back firsterror, operation

Not every stage exists everywhere:

  • Collections take every stage.
  • Globals take beforeValidate, beforeChange, afterChange, beforeRead and afterRead.
  • Fields take beforeValidate, beforeChange, afterChange and afterRead.

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:

  1. beforeOperation
  2. The access rules. A read rule can narrow the query to what the user may see.
  3. The query
  4. beforeRead
  5. Loading the relations. Each related document runs the read hooks of its own collection.
  6. afterRead
  7. Removing the fields that the user may not read, then the select of the read
  8. afterOperation

A read opens no transaction.

A write

create, update, setGlobal and publish run these steps in one transaction:

  1. beforeOperation
  2. The access rules, and the updatedAt check for edit conflicts. Fields that the user may not change are dropped.
  3. Default values on create, then slugs
  4. beforeValidate
  5. Validation, then the validate functions of the fields
  6. beforeChange, then validation again, so a hook cannot store invalid data
  7. The checks for unique values and references
  8. The write
  9. afterChange
  10. afterRead
  11. afterOperation
A draft save checks only the value types in steps 5 and 6, and skips step 7 and 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:

  1. beforeOperation
  2. The access rules
  3. beforeDelete
  4. The check for links in rich text and link fields. See Deletes and references.
  5. The delete
  6. The onDelete rule of every relation that points to the document
  7. afterDelete
  8. afterOperation

Several hooks at one stage

At each stage, the hooks run in this order:

  1. The field hooks, in field order. A group's hooks run before the hooks of its fields.
  2. The hooks of the collection or global.
  3. The hooks of plugins, in the order of plugins.
  4. 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, the context and 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.
On a database with one connection, like :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():

tenon.config.ts
export default defineCms({
  // ...
  hooks: {
    afterError: [({ error, operation, collection }) => console.error(operation, collection, error)],
  },
});
  • ValidationError, ConflictError and ForbiddenError are expected, so they run no afterError.
  • Only the outer operation runs afterError. A nested cms call that fails runs none of its own.
  • An error inside afterError is 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():

HookRuns
seedOnce per database, to fill a new database
onInitOn every start
afterImportAfter an import or a restore
afterErrorOn every unexpected error

See Lifecycle hooks.