Extending

Hooks — change what the framework does without forking it

Where extensions live

src/hooks.ts, imported once by src/server/index.ts. Every listener is registered before the server handles its first request.

src/hooks.ts
import { hooks, HOOKS } from '@basicbenframework/core/hooks'

hooks.on(HOOKS.POST_CREATING, async (data) => ({
  ...data,
  title: data.title.trim()
}))

hooks.on(HOOKS.MEDIA_UPLOADED, async ({ url }) => {
  await purgeCdn(url)
})

There was once a plugin system wrapping this — an object with a name, a version and an activation switch. It was removed. A plugin could not be installed at runtime on any host that rebuilds from an image, so what remained was a container around exactly these calls, and import already does that job. Shipping an extension as an npm package still works: install it, import it, call hooks.on.

Two kinds of hook

The distinction is the thing to get right. A filter transforms a value and must return it — returning nothing replaces the value with undefined. A notification is told something happened and its return value is ignored.

// Filters — return the value, changed.
'post.creating'   // return { cancel: true, reason } to refuse the write
'content.render'  // the rendered HTML, before sanitizing
'admin.menu'      // the sidebar items

// Notifications — the return value is ignored.
'post.created'
'media.uploaded'
'server.started'

A listener that throws is contained: the others still run. Pass a name so the logged error points at the culprit — without one it says which hook threw but not which listener, which is no help on a hook with several.

hooks.on(HOOKS.POST_CREATED, reindex, { name: 'search-index' })

// Hook "post.created" (search-index) threw: connection refused

priority takes a number too — lower runs first, default 10. Set BASICBEN_DEBUG_HOOKS=1 for stack traces.

Every hook

All 39, by family: server.*, request.*, post.*, page.*, comment.*, content.render/save/delete, media.*, auth.*, email.*, mail.*, admin.*. Every hook the framework declares fires — that is checked by a test that walks the constants and looks for a call site.

Where hooks fire matters

The registry is a singleton per JavaScript realm, and the browser is a different realm from the server. src/hooks.ts is imported by the server entry, so a hook fired in the browser would consult an empty registry. That is why admin.menu and admin.dashboard fire on the server and reach the UI through an API — the admin asks the server what to render, because the server is where the listeners are.