Events
Events
Define a typed VitNode event with defineEvent and a Zod schema, emit it after a write, react to it with a listener and see how listeners run, fail and scale.
Events let one part of an app react to something another part did, without either knowing the other's code. A route emits site-notes.note.created; any plugin can listen and send an email, update a search index or write an audit entry. In this guide site-notes defines that event, emits it when a note is created and logs it from a listener.
Before you begin
- The
site-notescreate route from Permissions, or any route of your own that writes data.
Define the event
Create src/api/events.ts. An event is a name plus a Zod schema for its payload. defineEvent comes from the plugin's src/api/builders.ts, which binds it to your plugin id:
import { z } from "zod";
import { defineEvent } from "@/api/builders";
export const noteCreatedEvent = defineEvent({
name: "site-notes.note.created",
payload: z.object({
noteId: z.number().int().positive(),
title: z.string().min(1),
}),
});- Prefix the name with your plugin id, so it never collides with core's or another plugin's.
- Keep the file free of handlers and database code. Another plugin imports the definition to listen, and should not pull in your routes.
- The payload must be a JSON object, so an adapter can carry it to another process:
z.date()is a compile error. For a date, useeventDate()from@vitnode/api/events/wire, which takes an ISO string and gives listeners aDate. See Event payloads.
Register it
Pass the definition to buildApiPlugin in src/config.api.ts. This is an excerpt; keep the rest of the file:
import { noteCreatedEvent } from "@/api/events";
export const siteNotesApiPlugin = () =>
buildApiPlugin({
manifest,
modules: [helloModule, notesModule, adminModule],
permissionStaff: staffPermissions,
eventDefinitions: [noteCreatedEvent],
});eventDefinitions lists the events your plugin owns. The API refuses to start when two different definitions claim one name, or when a plugin registers another plugin's definition.
Emit it after the write
In src/api/modules/admin/notes/routes/create.route.ts, import the definition with import { noteCreatedEvent } from "@/api/events"; and emit it once the insert has returned, before answering:
handler: async c => {
const values = c.req.valid("json");
const [note] = await c
.get("db")
.insert(site_notes)
.values(values)
.returning({ id: site_notes.id, title: site_notes.title, body: site_notes.body });
await c.get("events").emit(noteCreatedEvent, {
noteId: note.id,
title: note.title,
});
return c.json(note, 201);
},A missing or mistyped field is a compile error. At runtime the payload is validated before any listener runs, and a payload the schema rejects throws EventPayloadValidationError. Emit after the data is saved. Inside a transaction, emit after it commits, or listeners may read data that is then rolled back.
Create a listener
Create src/api/lib/note-created.listener.ts:
import { buildEventListener } from "@vitnode/api/lib/events";
import { noteCreatedEvent } from "@/api/events";
export const noteCreatedListener = buildEventListener({
event: noteCreatedEvent,
name: "log-new-note",
handler: async (c, payload, envelope) => {
await c
.get("log")
.debug(`New note #${payload.noteId}: "${payload.title}" (event ${envelope.eventId})`);
},
});payload is the schema's output. envelope adds the event id, the emitting plugin, the time and the actor (admin, user or system). name identifies the listener in logs and failure reports.
Register it on a top-level module
Add the listener to the events of notesModule, a module passed to buildApiPlugin directly:
import { buildModule } from "@/api/builders";
import { noteCreatedListener } from "@/api/lib/note-created.listener";
export const notesModule = buildModule({
name: "notes",
routes: [listNotesRoute, showNoteRoute],
events: [noteCreatedListener],
});Listeners are collected only from top-level modules. On a nested module, such as admin/notes, a listener never runs: buildApiPlugin throws in development to say so, and vitnode doctor reports it. Production ignores it silently.
Check the result
- Create a note on the AdminCP page, or with the Create a test note button from the Permissions lesson. Then open Debug Panel → Log explorer (
/admin/core/debug/logs). A debug entry fromsite-notesreadsNew note #8: "Lift maintenance" (event …), with your note's id and title. The same line is printed in thepnpm devterminal. - Build the plugin (a running
pnpm devis enough) and runpnpm vitnode inspect eventsinside it. Thesite-notes.note.createdlistener is listed withsite-notesas its event owner, and the definition appears under the plugin's event definitions.
Listen to core and other plugins
Every event has a definition you import. Core's live in @vitnode/api/events/*, one file per area, and a plugin exports its own:
import { userCreatedEvent } from "@vitnode/api/events/users";
import { buildEventListener } from "@vitnode/api/lib/events";
import { welcomeMemberTask } from "@/api/tasks/welcome-member.task";
export const welcomeListener = buildEventListener({
event: userCreatedEvent,
name: "queue-welcome-member",
handler: async (c, payload) => {
await c.get("queue").dispatch(welcomeMemberTask, { userId: payload.userId });
},
});welcomeMemberTask is a queue task of your own plugin, defined in the Built-in events quick start. You never register another plugin's definition: the listener carries it. Built-in events lists every event with its import, and Content Engine events come from contentEvent(contentType, action), as in Content Engine events.
How listeners run
With the default local adapter:
| Question | Answer |
|---|---|
| When do listeners run? | Inside the emitting request, one after another in registration order. emit() resolves after the last one. |
| What if the payload is invalid? | emit() throws EventPayloadValidationError before any listener runs, and nothing is delivered. |
| Does a failing listener break the request? | No. Its error is logged and returned in emit()'s failures, and the remaining listeners still run. A listener or adapter error never makes emit() throw. |
| Is delivery retried or stored? | No. Events are not durable: they live only in that request, and a crash loses them. Work that must survive belongs in the queue. |
| Can a listener run twice? | Yes. Delivery is not exactly-once: code that retries, such as a queue task that emits, can emit the same fact again. Make listeners idempotent. |
| Do other instances hear the event? | No, only the instance that emitted it. A custom adapter can deliver elsewhere and report status: "queued". |
emit() resolves to { eventId, status, delivered, failures }. delivered counts the listeners that succeeded; each failure names the plugin, module and listener. Keep listeners quick, because the person who created the note waits for all of them.
Hand slow work to the queue
When a listener has slow work, such as sending email, queue it instead of doing it in the request, as the welcome listener above does. A listener runs in the emitter's request, so c.get("plugin") is the emitting plugin, but a queue task belongs to the plugin that defines it: dispatch(welcomeMemberTask, ...) stores the row under site-notes either way. Queue shows how to create the task.
Related
- Event payloads: validation, dates, wire format and adapters.
- Built-in events: every event core, the Content Engine and first-party plugins emit, with payloads.
- Custom event adapter: deliver events through your own transport.