# Hooks: content-type hooks and the event bus

URL: https://kywi-docs-production.up.railway.app/developing/hooks-content-type-hooks-and-the-event-bus
Type: docPage

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.

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' }, ]) } }, }, })

## kywi.config.ts

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.

// 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

## A handler on the bus cannot reject anything

`emit` awaits each handler for an event in registration order, and wraps every one in its own `try/catch` that logs to `console.error` and moves on. A throw from a bus handler stops neither its siblings nor the request — the write has already been decided by the time the event fires, and there is no return channel. This is the whole reason `hooks.validate` is awaited OUTSIDE the bus: a plugin subscribed to `content:validate` can observe a write and can log about it, but only the content type's own `validate` can stop it.

## 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](/developing/plugins-what-one-can-contribute-and-when/) and [Webhooks](/integrating/webhooks/).

## The config validator knows seven of the nine

The zod schema that `parseKywiConfig` uses lists `beforeCreate`, `afterCreate`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete` and `afterPublish` — and zod strips unknown keys, so `validate` and `afterUnpublish` vanish from the parsed result. Nothing at runtime goes through that path, so your hooks still run; what it means is that the CLI's and the MCP developer server's view of a config is not the app's view of it. Don't read a parsed config to decide whether a hook is present.
