Hooks

Lifecycle callbacks for business logic on create, update, and delete.

Hooks let you run code before or after CRUD operations. Define them on the entity:

          import { entity, text, slug } from "@cms/config";

const posts = entity("posts", {
  hooks: {
    beforeCreate: async (data, context) => {
      data.slug = slugify(data.title);
      return data;
    },
    afterCreate: async (document, context) => {
      await notify(document);
    },
    beforeUpdate: async (data, existing, context) => {
      // Derive a denormalised counter / flag — anything you can compute from
      // the incoming patch and the prior row. `publishedAt` itself is engine-
      // managed when `versions: true` (set by the publish path); user code
      // should not write to it.
      if (data.status === "archived" && !existing.archivedAt) {
        data.archivedAt = new Date().toISOString();
      }
      return data;
    },
    afterUpdate: async (document, context) => {},
    beforeDelete: async (id, context) => {},
    afterDelete: async (id, context) => {},
  },
  fields: [
    text("title", { required: true }),
    slug("slug", { required: true }),
  ],
});
        

Hook signatures

Before hooks

Before hooks receive the data being written and can modify it or throw to abort:

          // beforeCreate — receives the incoming data
beforeCreate: (data: Record<string, unknown>, context: BeforeHookContext) =>
  Promise<Record<string, unknown>> | Record<string, unknown>;

// beforeUpdate — receives the incoming data AND the existing document
beforeUpdate: (
  data: Record<string, unknown>,
  existing: Record<string, unknown>,
  context: BeforeHookContext
) => Promise<Record<string, unknown>> | Record<string, unknown>;

// beforeDelete — receives the record ID, throw to abort
beforeDelete: (id: string, context: BeforeHookContext) =>
  Promise<void> | void;
        

Return the (potentially modified) data from beforeCreate and beforeUpdate. The returned value is what gets written, so return the whole document with your changes spread in ({ ...data, title }).

The value a beforeCreate, beforeUpdate, beforePublish, beforeDraftSave or beforeRestore hook returns is validated like a request body: against the field schemas and the field rules (conditional required, validate). A key that isn’t one of the entity’s fields is rejected too; auto fields (id, timestamps, …) and the engine’s pointer columns are allowed and ignored, so spreading existing is fine. An invalid result fails the write with a 400 VALIDATION_ERROR whose message names the hook and whose details name the field, and nothing is written.

Translating a document is a create, so its beforeCreate gets the translation’s values and its result is validated like any other. context.translationOf names the document it translates.

On a global, the first write (no document yet, or none in that locale) fires beforeCreate and afterCreate; later writes fire beforeUpdate and afterUpdate.

After hooks

After hooks run after the operation completes. They’re fire-and-forget — errors are logged but don’t affect the response:

          afterCreate: (document: Record<string, unknown>, context: HookContext) =>
  Promise<void> | void;

afterUpdate: (document: Record<string, unknown>, context: HookContext) =>
  Promise<void> | void;

afterDelete: (id: string, context: HookContext) =>
  Promise<void> | void;
        

Hook context

Every hook receives a context object. Its cms and system read and write content in-process, through the same code path as the REST API: permissions, validation, versions, translations, hooks and relation resolution all apply, so a hook never depends on how documents are stored.

          type HookContext = {
  entityName: string;    // the entity the hook runs for
  user: { id: string; email: string; role: string } | null; // null for an API key or the public role
  role: string;
  cms: Client;           // acts as the caller: their role decides what they can read and write
  system: Client;        // full access; reads skip unpublished documents unless `draft: true`
  config: CmsConfig;     // the resolved config, plugin entities included (read-only)
  logger: { info; warn; error }; // the engine's logger, tagged with the entity
  reportError: (error: unknown) => void; // hands a failure to error-monitoring plugins
  db: unknown;           // raw Drizzle database, unstable (see below)
  email: { send(message) }; // sends through the email provider, see Server context
  translationOf?: string; // a write that creates a translation: the id of the document it translates
};
        

translationOf is set only on the hooks (and plugin observers) of a write that creates a document as another document’s translation: beforeCreate and afterCreate, plus beforePublish and afterPublish when the translation goes live on creation (no draft workflow). A hook can use it to tell a translation from a new document.

cms and system have the same methods and query shape as @cms/client: find, list, get, create, update, delete, drafts, versions and unpublish, with the same fields, resolve, filter and sort options.

          afterPublish: async (document, { system }) => {
  // A global the editors maintain, read as published.
  const { data: settings } = await system.get("site-settings");
  if (settings?.notifyUrl) await notify(String(settings.notifyUrl), document);
},
        

cms or system. Use cms when the change should be limited to what the person or key that made the request may do. Use system for work the project does on its own behalf, like keeping a counter or a related document in sync. Unlike cms, system reads of an entity with drafts leave out unpublished documents unless the call passes draft: true, which returns the editorial view: pending drafts merged in, unpublished documents included.

Errors. A call that fails throws ClientError from @cms/config, with the HTTP status, the error code and, for a validation error, details per field. Check for it with isClientError, not instanceof: cms.config and everything it imports are loaded with their own copy of @cms/config, so its ClientError class isn’t the one the engine throws.

          import { isClientError } from "@cms/config";

try {
  await system.create("subscribers", { email });
} catch (error) {
  if (isClientError(error) && error.code === "CONFLICT") return; // already subscribed
  throw error;
}
        

Typed calls

cms and system are typed loosely by default: any entity name is accepted and documents are Record<string, unknown>. A hook lives inside the config, so its context can’t be typed from that config automatically. Cast to Client<typeof config> for the same typing as a frontend createClient<typeof config>: entity names are checked and fields narrows the result.

          // lib/notify.server.ts
import type { Client, HookContext } from "@cms/config";
import type cmsConfig from "../cms.config";

export async function notify(ctx: HookContext): Promise<void> {
  const system = ctx.system as Client<typeof cmsConfig>;
  const { data } = await system.list("posts", { fields: { title: true } });
  // data: { title: string; … }[]
}
        

In a before* hook, cast to ContentReader<typeof config> instead: it has the same typed find, list and get, and keeps the writes out of the type as they are out of the hook.

The same casts work inline in cms.config, against a const holding the config. Either way, when a hook or helper returns something built from a typed call (a before* hook returning data, say), write its return type out (: Promise<Record<string, unknown>>). The config’s type depends on the hook, so a return type inferred from the config would depend on itself: TypeScript reports that the config implicitly has type any. A function that returns nothing needs no annotation.

Before-hooks can only read

In a before* hook, cms and system have only find, list and get (BeforeHookContext), and calling a write anyway throws. A before-hook runs inside the write: in a bulk publish, every row is locked inside one transaction while the hooks run, and a write from a hook would wait on those locks. The reads run on the write’s own transaction instead, so they see the write in progress and never wait.

Write from an after-hook instead. A change that must be atomic with the write belongs in the data the hook returns.

          beforePublish: async (data, existing, { system }) => {
  if (!data.parent) return data;
  const { data: parent } = await system.find("pages", { filter: { id: data.parent.id } });
  if (!parent) {
    throw new HookError("Publish the parent page first", [
      { field: "parent", message: "The parent page isn't published" },
    ]);
  }
  return data;
},
        

db is unstable

db is the raw Drizzle database. Its tables are the storage layout, which can change in any release, and a query through it skips permissions, validation, versions and hooks. Prefer cms or system; reach for db only for what they can’t express, and expect to revisit it on upgrades.

Server-only code in .server.ts files

cms.config is loaded by the engine in Node and bundled into the admin SPA, which reads its entities and fields. Everything the config imports ships to the browser with it, hook bodies included. Put Node-only code (database drivers, SDKs, anything holding a secret) in a file whose name ends in .server.ts and import it from the hook:

          // lib/search-index.server.ts
import { algoliasearch } from "algoliasearch";

const client = algoliasearch(process.env.ALGOLIA_APP_ID!, process.env.ALGOLIA_ADMIN_KEY!);

export async function indexPost(document: Record<string, unknown>) {
  await client.saveObject({ indexName: "posts", body: { objectID: document.id, ...document } });
}
        
          // cms.config.tsx
import { indexPost } from "./lib/search-index.server";

const posts = entity("posts", {
  hooks: {
    afterCreate: (document) => indexPost(document),
    afterUpdate: (document) => indexPost(document),
  },
  fields: [text("title", { required: true })],
});
        

The engine runs the real module. The admin build (cms dev and cms build) replaces every *.server.* module (.ts, .tsx, .js, .mjs, from your project or from a package’s published files) with a stub that has the same export names, so the SDK and the secret never reach the admin bundle. Each stubbed export is a function that throws "indexPost" from lib/search-index.server.ts is server-only and was called in the browser. if browser code ever calls it.

  • Node-only code left in a regular file fails the admin build. If a project file that isn’t a .server module imports a Node built-in such as node:fs or crypto, the build stops with "node:fs" imported by lib/db.ts would reach the admin bundle and asks you to move that code into a *.server.ts file. Packages in node_modules are not checked, and neither are SDKs that also run in the browser, so keep any code that holds a secret in a .server module.

  • A .server module’s exports are only usable on the server. Constants exported from it are stubs too, so keep values the admin needs (a field option list, a label) in a regular file.

  • Call a .server function only from inside a hook, handler or observer, never while the config is being defined. The admin evaluates the config too, so a call made at definition time runs the stub and the admin fails to load, even though the engine, cms build and the type-checker are all fine. Passing the function itself is safe:

              import { logChange, notify } from "./lib/audit.server";
    
    hooks: {
      afterCreate: notify,                                       // ✓ passed, called on the server
      afterUpdate: (document) => logChange("update", document),  // ✓ called inside the hook
      afterDelete: logChange("delete"),                          // ✗ called while the config loads
    },
            
  • Write .server modules as ES modules (import/export). A CommonJS .server file (module.exports) fails the admin build, because its export names can’t be read.

  • List re-exports by name. export * from "./x" in a .server module fails the admin build, because the stub can’t know which names to export.

  • Packages follow the same rule: a package’s server-only module must keep the .server.js suffix in its build output. With tsdown, build with unbundle: true so every source module keeps its own file. A named entry ("foo.server": "src/foo.server.ts") also works, unless another entry imports it: the bundler can then move its code into a hashed chunk (foo.server-a1b2c3.js) the admin build doesn’t recognise.

Field-level hooks

Hooks can also live on an individual field, declared in the field’s options. They fire for that field wherever it appears in the document — including fields nested inside object, array, and union (block) structures. The block definition itself declares the behaviour, so a block stays self-contained: add it to any entity and it works.

          import { relation } from "@cms/config";

relation("project", {
  to: "project_page",
  hooks: {
    // Always point this block's relation at the document it lives in.
    beforeRead: ({ document }) => ({ id: document.id, _entity: "project_page" }),
  },
});
        

The four field hooks

Hook Phase Return On error
beforeRead After load, before relation resolution New value for the field Request fails
afterRead After relation resolution New value for the field Request fails
beforeWrite After Zod validation, before write New value (re-validated against the field schema) Request fails; a HookError is a 400 with its details
afterWrite After the write commits — (ignored) Logged, never thrown
          text("code", {
  hooks: {
    // Normalise on the way in. The return value is re-validated against the
    // field's schema, so a buggy hook is caught at write time.
    beforeWrite: ({ value, operation, existing }) => value?.toUpperCase(),
    // Fire-and-forget side effect with the written value + post-write document.
    afterWrite: ({ value, document, operation }) => audit(document.id, value),
    // Reshape on the way out (e.g. redact based on the reader's role).
    afterRead: ({ value, user }) => (user?.role === "admin" ? value : "***"),
  },
});
        

Self-referencing blocks

The headline use case: a block inside a page needs page-level data, but the rendering layer should stay a uniform block → component loop. A beforeRead hook on a relation field sets it to the parent document’s id; because it runs before resolution, the standard ?resolve machinery then populates it:

          const page = entity("project_page", {
  fields: [
    text("title", { required: true }),
    object("attributes", { fields: [text("location"), text("awards")] }),
    array("blocks", {
      of: union("block", {
        of: [
          object("project_hero", {
            fields: [
              text("headline"),
              relation("project", {
                to: "project_page",
                hooks: {
                  beforeRead: ({ document }) => ({
                    id: document.id,
                    _entity: "project_page",
                  }),
                },
              }),
            ],
          }),
        ],
      }),
    }),
  ],
});
        
          GET /api/project_page/:id?resolve[blocks.project]=*
        

The project_hero block comes back with project populated by the parent page — no data duplication, no client-side fetch, no special-casing in the renderer. Resolution stays client-controlled: omit ?resolve and you get the bare { id, _entity } reference. Recursion is bounded by the resolver’s depth limit, so the parent’s own blocks are not re-expanded.

Context shapes

          // beforeRead / afterRead — `document` is normalised but pre-resolution (its
// relations are { id, _entity } stubs). No `db` — keep field hooks pure.
type FieldReadContext<TValue> = {
  value: TValue;
  document: Record<string, unknown>;
  field: AnyFieldBase;
  user: { id: string; email: string; role: string } | null;
  entityName: string;
};

// beforeWrite — `data` is the full submitted document; `existing` is the prior
// canonical row (undefined on create). `system` reads only, on the write's own
// transaction, like an entity before-hook's.
type FieldWriteContext<TValue> = {
  value: TValue;
  data: Record<string, unknown>;
  operation: "create" | "update";
  existing: Record<string, unknown> | undefined;
  user: { id: string; email: string; role: string } | null;
  entityName: string;
  path: string; // where the value sits, dotted: "blocks.2.source"
  parent: Record<string, unknown>; // the object it's a field of, as earlier hooks left it
  system: ContentReader; // find, list, get
  config: CmsConfig;
};

// afterWrite — `document` is the post-write canonical row.
type FieldAfterWriteContext<TValue> = {
  value: TValue;
  document: Record<string, unknown>;
  operation: "create" | "update";
  user: { id: string; email: string; role: string } | null;
  entityName: string;
};
        

Container vs. element granularity

A hook on a container field receives the whole container; a hook on a field inside a container fires once per element. A beforeRead on an array field sees the full array (sort/filter it); a beforeRead on a field nested inside the array fires once per item.

A beforeWrite that refuses a value throws HookError with a detail on its own path, so the admin shows the message on that field, inside the block it belongs to:

          relation("author", {
  to: "authors",
  hooks: {
    beforeWrite: async ({ value, path, system }) => {
      if (!value) return value; // runs on an omitted or cleared value too
      const { data } = await system.list("authors", { filter: { id: value.id, retired: true } });
      if (data.length > 0) throw new HookError("Retired.", [{ field: path, message: "Retired." }]);
      return value;
    },
  },
});
        

Built-in hooks

The _user entity has one built-in hook: afterDelete signs the deleted user out everywhere, after your own. The CMS sends no email when a user is created; there are no passwords, and sign-in is by emailed code.

To run your own code on users (send a welcome email, sync them to a CRM), give _user hooks by extending it: entity.extend("_user", { hooks: { afterCreate } }). Its create, update and delete hooks work as on any entity, and run on signup too. A user cms user create writes skips them: it goes straight to the database.

A welcome email for editors, who otherwise learn of their account from whoever created it:

          // emails.server.ts
import { type HookContext, html } from "@cms/config";

const EN = {
  subject: "Your account is ready",
  body: "An account was created for you. To sign in, open the admin and request a login code for",
};
const COPY: Record<string, typeof EN> = {
  en: EN,
  pt: {
    subject: "A sua conta está pronta",
    body: "Foi criada uma conta para si. Para entrar, abra o admin e peça um código de acesso para",
  },
};

export const sendWelcome = async (doc: Record<string, unknown>, ctx: HookContext) => {
  const role = ctx.config.roles.find((r) => r.name === doc.role);
  if (!role?.adminPanel) return;
  // `preferredLocale` exists with more than one locale; a value no longer configured is unset.
  const { locales, defaultLocale } = ctx.config.i18n;
  const locale = locales.some((l) => l.value === doc.preferredLocale)
    ? (doc.preferredLocale as string)
    : defaultLocale;
  const { subject, body } = COPY[locale] ?? EN;
  // After-hooks run after the commit and nothing waits on them: awaiting holds nothing back, and
  // a rejection is logged and reported by the hook runner.
  await ctx.email.send({
    to: doc.email as string,
    subject,
    html: html`<p>${body} ${doc.email as string}.</p>`,
  });
};

// cms.config.ts
entity.extend("_user", { hooks: { afterCreate: sendWelcome } });
        

Plugin observers

A plugin can register after-hooks once and have them run for many entities. These are observers: a search index that re-indexes every changed document, or a cache that’s revalidated on every publish, without adding a hook to each entity by hand.

          import { definePlugin } from "@cms/config";
import { revalidate } from "./revalidate.server";

export const revalidator = definePlugin("revalidator", (options: { url: string }) => ({
  observers: {
    // A match replaces the default, so leave the built-ins (`_user`, assets) out explicitly.
    match: (entity) => !entity.global && !entity.name.startsWith("_"),
    afterPublish: (document, { entityName }) => revalidate(options.url, entityName, document),
    afterUnpublish: (document, { entityName }) => revalidate(options.url, entityName, document),
    afterDelete: (id, { entityName }) => revalidate(options.url, entityName, { id }),
  },
}));
        

Hooks. afterCreate, afterUpdate, afterPublish, afterUnpublish and afterDelete, with the same signatures as an entity’s. One function serves many entities, so read context.entityName to tell them apart.

Context. An observer gets the hook context without cms (ObserverContext): it runs on its own once the write has committed, so it acts through system. user and role still say who made the write, and its logs and error reports carry the plugin’s name.

Loops. A write an observer makes through system runs the observers of other plugins, but not those of any plugin already in that chain. A plugin that copies changes into an entity it also observes doesn’t re-trigger itself, and two plugins that observe each other’s entities can’t loop forever. The entity’s own hooks always run.

match. Decides which entities the plugin observes, once at boot, so entities you add later are covered too. Without it, a plugin observes every entity except the built-in ones (_user, _image, _video, _file). A match decides on its own, so it can include built-ins.

Timing. Exactly that of the entity’s own after-hooks, so the same quirks apply:

  • They run after the write commits, and nothing waits for them.
  • On publish, and on a draft save or restore of a document that was never published, afterUpdate fires alongside the specific hook.
  • A global’s first write fires afterCreate; its later writes fire afterUpdate.
  • Bulk writes fire once per document.

Errors. A throw or rejection is logged and reported to error-monitoring plugins (with the failing plugin’s name), and never fails the editor’s save. Each observer is isolated: one plugin’s failure doesn’t stop another’s.

Order. The entity’s own hook is called first, then each plugin’s observer in the order the plugins are listed. Nothing is awaited, so this orders the calls, not their completion: an async entity hook and the observers run at the same time.

No plugin before-hooks. An observer can react to any change, but only the entity decides what is written to it. A plugin can’t validate, transform or reject another entity’s writes: one plugin bug would block publishing across the whole project, and an entity’s behaviour would depend on code you can’t see in its definition. To change what an entity stores, put a before-hook on the entity, or a field from the plugin in its fields.

Keep observer code in a *.server.ts file (above).

Throwing to abort

Any before* hook can throw to abort the operation — no row is written. What the client sees depends on which error you throw.

HookError — the reason belongs to the editor

Throw HookError when the hook is enforcing a rule a person can act on. It becomes a 400 VALIDATION_ERROR carrying your message, which the admin shows instead of a generic failure:

          import { HookError } from "@cms/config";

beforeDelete: async (id, { system }) => {
  const { data: child } = await system.find("pages", { filter: { parent: id }, draft: true });
  if (child) {
    throw new HookError("Cannot delete: entity has children");
  }
},
        

Pass details to scope messages to specific fields. The admin renders each one inline on that field rather than as a toast, so the editor sees the problem where they can fix it:

          beforePublish: async (data) => {
  if (hasGap(data.days)) {
    throw new HookError("Days can't have gaps", [
      { field: "days", message: "Day 3 is empty but later days are filled" },
    ]);
  }
  return data;
},
        

Each field must be a field name on the entity being written; unknown names still surface, just not attached to an input.

A plain Error — something broke

Anything else a hook throws is treated as an unhandled failure: the write aborts, the error is logged in full, and the client gets a generic 500. This is deliberate — a hook that dies on a bad query or an unreachable service must not put its raw message into an API response. If you want the message seen, that’s what HookError is for.

Throwing an error with your own status (e.g. a conflict) is not supported from a hook; use HookError and let the engine pick the status.

Rules that don’t need a hook

Reach for a hook only when the rule needs other documents or another service. Two common rules have a better home:

  • “No two published documents share this value.” Use a unique rule on the entity, or unique: true on the field. A database index enforces it, so two concurrent publishes can’t both get through the way they can past a hook’s find, and the error lands on the field.
  • A rule about one field’s value, even one that compares it with another field of the same document. Use the field’s validate. The admin runs the same function when the editor saves, and the error shows on that field before the request is sent; the server runs it again.

Previous

Permissions

Next

Drafts and publishing