# App events

An **app event** is a named, typed fact your app announces, such as `user.registered`; a **listener** reacts to it. Code that registers a user announces the event and knows nothing about the welcome mail, the audit row or the analytics call that follow. Server [hooks](/plugins-and-hooks) stay the framework's extension points; app events are yours.

## Declare the events

`server/events.ts` of the app (and of each [layer](/layers)) default-exports `defineAppEvents`, one [Standard Schema](https://standardschema.dev) per event. The samples on this page use a small hand-written schema, so they need no library; write valibot, zod or arktype in your app.

````ts [data/events-define.ts]
import { defineAppEvents } from "hamur/server"
import { object } from "./events-schema.ts"

export default defineAppEvents({
  "user.registered": object<{ userId: string }>({ userId: "string" }),
  "order.paid": object<{ orderId: string; total: number }>({ orderId: "string", total: "number" }),
})
````

A name is lower case, dot-separated, and written out as a key: `/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*$/`. The build reads the names without running the file, so a spread or a computed key fails it. When the app and a layer declare one name, the app's wins. Typegen writes the payload of each event to `.hamur/types/app-events.d.ts`, so `emitAppEvent` and `defineListener` are typed from the schemas; the payload is the schema's output.

## Write a listener

A listener is a file in `server/listeners/` whose default export is `defineListener`. Its name is the path below `server/listeners/`, with `/` turned into `:`, by the rule of [tasks](/tasks#writing-a-task): `server/listeners/audit/order.ts` is `audit:order`. `on` is the event name as a string literal. `run(payload, ctx)` gets the payload and a `ctx` with `listener` (the name), `log` (the server logger with `{ listener }` added) and `waitUntil`.

A **synchronous** listener, the default, runs while the emitter waits:

````ts [data/events-listener-sync.ts]
import { defineListener, useStorage } from "hamur/server"

export default defineListener({
  on: "order.paid",
  async run({ orderId, total }: { orderId: string; total: number }, ctx) {
    ctx.log.info("order paid", { orderId, total })
    await useStorage("audit").setItem(`order:${orderId}`, { total, at: Date.now() })
  },
})
````

A **queued** listener, `queue: true`, runs later, outside the emitter's call, with a queue's retries where the platform has them:

````ts [data/events-listener-queued.ts]
import { defineListener } from "hamur/server"

declare function sendWelcome(userId: string): Promise<void>

export default defineListener({
  on: "user.registered",
  queue: true,
  async run({ userId }: { userId: string }, ctx) {
    ctx.log.info("sending the welcome mail", { userId })
    await sendWelcome(userId)
  },
})
````

`queue` is a literal `true` or `false`, and the options of `defineListener` are written out, not spread: the build reads the file as text.

## Emit

````ts [data/events-emit.ts]
import { defineHandler, emitAppEvent } from "hamur/server"
import { useDatabase } from "@hamur/db/server"

export const register = defineHandler({
  route: "/api/register",
  method: "POST",
  async handler({ email }: { email: string }) {
    const userId = crypto.randomUUID()
    await useDatabase().transaction(async (tx) => {
      await tx.run`insert into users (id, email) values (${userId}, ${email})`
    })
    await emitAppEvent("user.registered", { userId })
    return { userId }
  },
})
````

`emitAppEvent(name, payload)` validates the payload with the event's schema, runs every synchronous listener of the event together, waits for all of them and then enqueues each queued listener. A payload the schema refuses throws in the emitter, since it is a bug there: `emitAppEvent("user.registered"): the payload is refused by its schema: userId must be a string at userId`. A name that `server/events.ts` does not declare rejects with `emitAppEvent("x"): not an app event; declare it in server/events.ts`.

- **Order.** Listeners have no order. A listener that needs another's effect is one listener.
- **A synchronous listener throws.** The others still run. The call then rejects with that error, or with an `AggregateError` of all of them when more than one threw, and **nothing is enqueued**, so a queued listener never runs for an event whose synchronous side failed.
- **A transaction.** Emit after `transaction()` resolves, as the sample does. Hamur cannot see your transaction from the core, so an event emitted inside it would still reach its listeners when the transaction rolls back.

## Where a queued listener runs

A queued listener is a [task](/tasks) named `listener:<name>`, added to the task table at build. It is enqueued with `enqueue`, so it goes where [`enqueue` goes](/tasks#queues-and-enqueue) on your preset, with the retries and the durability of that queue:

| Preset                                       | The run                                                                                        |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `bun`, `node` with `tasks.queue.driver "db"` | a row of the [`db` queue](/tasks#the-database-queue): survives a restart, retried with backoff |
| `bun`, `node`, `hamur dev` without it        | this process, after the answer: lost on a restart, never retried                               |
| `cloudflare` with `tasks.queue`              | one message to the Cloudflare Queue; Cloudflare retries it                                     |
| `vercel` with `tasks.queue`                  | a Vercel Queues message; redelivered when the run threw                                        |
| `cloudflare`, `vercel` without it, `netlify` | this process, through the platform's `waitUntil`: not durable                                  |

A queued run that fails is logged and reaches the `task:error` hook like any other unawaited run. Delivery is at least once on the durable queues, so write a queued listener that can run twice. `hamur task list` and the Tasks tab of the [devtools](/devtools) show each queued listener with the event it runs on.

A synchronous listener runs on every preset in the emitter's own request or run. Use it for work the caller must see fail (a row that must exist); use a queued one for work that may happen a moment later (a mail).

## Build errors

| Code                               | What failed                                                                               |
| ---------------------------------- | ----------------------------------------------------------------------------------------- |
| [HAMUR_E1248](/errors/HAMUR_E1248) | `server/events.ts` does not default-export `defineAppEvents({ ... })`                     |
| [HAMUR_E1249](/errors/HAMUR_E1249) | an event name is spread or computed                                                       |
| [HAMUR_E1250](/errors/HAMUR_E1250) | `"User.Registered" is not an app event name (lower case, dot-separated)`                  |
| [HAMUR_E1251](/errors/HAMUR_E1251) | `on "user.registerd" is not an app event (did you mean "user.registered"?)`               |
| [HAMUR_E1252](/errors/HAMUR_E1252) | `on must be a string literal`, or `queue must be true or false`                           |
| [HAMUR_E1253](/errors/HAMUR_E1253) | a listener file does not default-export `defineListener({ ... })`, or spreads its options |

A queued listener whose task name is taken, such as `listener:send-welcome` next to `server/tasks/listener/send-welcome.ts`, fails the build with `Task "listener:send-welcome" of server/listeners/send-welcome.ts conflicts with server/tasks/listener/send-welcome.ts`.

The signatures are in the [server API reference](/api-reference/server#defineappevents-appevents-appeventpayloads-hamurappevents-appeventname-appeventpayload).
