Skip to content

Hooks: content-type hooks and the event bus

Content types carry nine lifecycle hooks; the registry behind them also dispatches comment, category, group, site, trash, version and admin events.

A content type's hooks block is nine async functions core awaits on the write path. Underneath them sits a plain string-keyed event bus that every other lifecycle in Kywi — comments, categories, groups, sites, trash, versions, API requests and responses, admin actions, admin rendering — dispatches onto, and that plugins subscribe to by event name. The two layers look alike and behave differently, and the difference decides whether your code can stop a write.

The nine, and the one that is not like the others

interface ContentTypeHooks {
  validate?:        (ctx: { data; kywi }) => Promise<void>
  beforeCreate?:    (ctx: { data; kywi }) => Promise<Record<string, unknown>>
  afterCreate?:     (ctx: { content; kywi }) => Promise<void>
  beforeUpdate?:    (ctx: { data; content; kywi }) => Promise<Record<string, unknown>>
  afterUpdate?:     (ctx: { content; kywi }) => Promise<void>
  beforeDelete?:    (ctx: { content; kywi }) => Promise<void>
  afterDelete?:     (ctx: { content; kywi }) => Promise<void>
  afterPublish?:    (ctx: { content; kywi }) => Promise<void>
  afterUnpublish?:  (ctx: { content; kywi }) => Promise<void>
}

beforeCreate and beforeUpdate RETURN the record that gets written — return an object and it replaces the payload, return nothing and the payload passes through. validate is the inverse: its return value is ignored entirely. It runs on create and on update, after schema parsing and before the row is written, and the only way it changes the outcome is by throwing.

Rejecting a write

Throw KywiValidationError. All three write doors — create, PUT and PATCH — run the before-hook and validate inside one try, and map that one error class to a 400 carrying its fields array as the response's per-field messages. Any other throw is a 500.

kywi.config.tsts
import { defineContentType, KywiValidationError } from '@kywi-software/core/config'

defineContentType({
  name: 'event',
  // …
  hooks: {
    async validate({ data }) {
      if (data.endsAt && data.startsAt && data.endsAt < data.startsAt) {
        throw new KywiValidationError('Event dates are inconsistent', [
          { field: 'endsAt', message: 'must be on or after startsAt' },
        ])
      }
    },
  },
})

Import it from @kywi-software/core/config, not from the package root. The re-export on that subpath exists for exactly this: the root barrel pulls in server-only modules such as nodemailer, and importing it from kywi.config.ts drags them into the Next bundle.

The bus underneath

The dispatcher does two things per event. It awaits the content type's own hook directly, and then it emits onto the registry — twice, once type-scoped (content:event:afterPublish) and once flat (content:afterPublish, with contentType in the payload). Ten more dispatchers ride the same registry with the same shape, and core subscribes to it like any other consumer rather than special-casing itself: comment counts, AX cache invalidation, and outbound webhooks are all just handlers.

ts
// The names core itself registers on, verbatim
'comment:afterCreate'          // → increments kywi_content_stats.commentCount
'content:afterPublish'         // → invalidates ax:{siteId}:*, and fires webhooks
'content:event:afterUpdate'    // → the type-scoped twin of content:afterUpdate

What a plugin gets

A plugin's hooks is a Record<eventName, handler> that joins the same registry, so it can subscribe to anything above — including a type-scoped name for a content type it did not define. Each handler is wrapped before registration and skipped at emit time when the plugin declares siteIds that exclude the payload's site, or when the plugin is deactivated for that site. The wrapper passes the plugin's static config as a second argument, so a handler reads its settings from there rather than closing over module scope.

Which site a handler is told about comes off the payload, not from process state — the same rule webhook dispatch follows, where the endpoints queried are the ones belonging to the site the event happened on, and the default site is a fallback only for an event that names none. See Plugins: what one can contribute, and when and Webhooks.