# `@hamur/notifications`

The first-party notifications module: it tells a recipient that something happened, by mail, by webhook, in a list your app shows and live in the open page. Add it to `modules` and set its options under the `notifications` config key. The mail channel needs [`@hamur/mail`](/api-reference/mail) in `modules` too, and the database channel [`@hamur/db`](/api-reference/db).

```ts
// hamur.config.ts
import mail from "@hamur/mail"
import notifications from "@hamur/notifications"
import { defineConfig, env } from "hamur"

export default defineConfig({
  modules: [mail, notifications],
  site: { url: "https://acme.dev" },
  mail: { from: "hello@acme.dev", transport: { type: "resend", apiKey: env("RESEND_API_KEY") } },
})
```

### `default`

The module, as `defineModule({ meta: { name: "notifications", configKey: "notifications" } })`. Its setup checks the options, reads `server/notifications/`, adds the task `notifications:deliver`, and refuses `@hamur/notifications/server` in client code.

### `NotificationsConfig`

```ts
interface NotificationsConfig {
  queue?: boolean // default true: notify queues one task per delivery
  webhook?: { url: string; secret: EnvRef } // the endpoint of a recipient without one
  table?: string // default "notifications": the table of the database channel
  connection?: string // default "default": the connection of db.connections that has the table
}
```

The secret must be `env("NAME")`: `notifications.webhook.secret must be env("NAME"); a secret in the config file ends up in the repository`.

### `Recipient`

```ts
interface Recipient {
  type: string // an entity type name, "User"
  id: string
  email?: MailAddress
  webhook?: { url: string; secret: EnvRef | string } // a tenant's own endpoint
  prefs?: Record<string, unknown> // read by via()
}
```

### `NotificationRow`

```ts
interface NotificationRow {
  id: string
  notification: NotificationName
  data: unknown // what the notification's `database` function returned
  readAt: Date | null
  createdAt: Date
}
```

### `NotificationName`, `HamurNotifications`

`HamurNotifications` is filled in by typegen from `server/notifications/`: each notification's name and the input `notify` takes. `NotificationName` is one of its names, and `string` in an app that has none.

## `@hamur/notifications/server`

### `defineNotification`

```ts
// server/notifications/invoice-paid.ts
import { defineNotification } from "@hamur/notifications/server"
import * as v from "valibot"

export default defineNotification({
  input: v.object({ invoiceId: v.string(), amount: v.number() }),
  mail: (input) => ({ subject: `Invoice ${input.invoiceId} is paid`, template: "InvoicePaid", props: input }),
  webhook: (input) => ({ type: "invoice.paid", invoiceId: input.invoiceId, amount: input.amount }),
  via: (to) => (to.prefs?.mail === false ? ["webhook"] : ["mail", "webhook"]),
})
```

A notification is a file of `server/notifications/`, named by its path below that folder: `server/notifications/team/invited.ts` is `team:invited`. A file or folder whose name starts with `_` or `.` is not one. Layers add theirs, and the app's file wins by name.

`input` is a Standard Schema. A channel is a function of the validated input and the recipient, which it gets without its `webhook`:

- `mail` returns a [`MailMessage`](/api-reference/mail) without `to`. It is sent to the recipient's `email`.
- `database` returns the data of the row, which is kept as JSON for [`listNotifications`](#listnotifications).
- `broadcast` returns the data that the recipient's open pages get, which must be JSON: see [the broadcast channel](#the-broadcast-channel).
- `webhook` returns the body, which is sent as JSON.

`via(to, input)` narrows the channels for a recipient. A channel it names that the notification does not have is skipped with a warning.

The build reads the channels from the keys of the object, so write them out. A file that is wrong fails the build, such as `server/notifications/invoice-paid.ts has no channel: give it mail, database, broadcast or webhook` and `server/notifications/invoice-paid.ts: the mail channel needs @hamur/mail in modules`.

### `notify`

```ts
function notify<N extends NotificationName>(
  to: Recipient | readonly Recipient[],
  name: N,
  input: HamurNotifications[N]["input"],
  options?: { queue?: boolean },
): Promise<void>
```

```ts
import { notify } from "@hamur/notifications/server"

await notify({ type: "User", id: "7", email: "ada@x.dev" }, "invoice-paid", { invoiceId: "2026-14", amount: 90 })
```

The call validates `input`. Each recipient and channel is one delivery, also for a recipient listed twice. By default each delivery is one run of the task `notifications:deliver`, so the retries of your [queue](/tasks) repeat the delivery that failed and no other. A mail that may have arrived is not sent again: the task logs the failure at `error` with `the queue does not send it again`. A mail links to the site, or the tenant of `site.tenants`, whose request called `notify`.

With `queue: false`, or `notifications.queue: false` in the config, the deliveries run in the call. It rejects after all of them ran when one failed: `notify("invoice-paid"): 1 of 6 deliveries failed: webhook to Tenant::"9": 502 Bad Gateway`.

A recipient without what a channel needs is skipped with a warning: `notify("invoice-paid"): User::"7" has no email; the mail channel skipped it`. An unknown name rejects: `Notification "x" not found (notifications: invoice-paid)`.

A queued delivery holds the validated input and the recipient's `type`, `id`, `email` and `prefs`; no other field of the object you pass is kept. The recipient's `webhook` is sealed with `HAMUR_KEY`, which an app needs to queue a delivery to one.

#### Webhooks

The webhook channel sends a `POST` signed as [Standard Webhooks](https://www.standardwebhooks.com) says, with the headers `webhook-id`, `webhook-timestamp` and `webhook-signature`. The secret is `whsec_` followed by the base64 of the key. `webhook-id` is the same on every retry, so a receiver can tell a repeat.

The URL may come from a user: it must be `https:` on the default port with a host name, the name must not resolve to a private, loopback or link-local address, and no redirect is followed. The receiver has 10 seconds to answer. Every answer that is not 2xx fails the delivery with its status.

#### The database channel

The channel keeps its rows in a table your app owns. Add it to a migration:

```sql
create table notifications (
  id text primary key,
  recipient_type text not null,
  recipient_id text not null,
  notification text not null,
  data text not null,
  read_at text,
  created_at text not null
);
create index notifications_recipient on notifications (recipient_type, recipient_id, created_at);
```

On MySQL, use `varchar(255)` for the columns of the key and the index. Keep the two dates as text: they hold ISO 8601.

The build reads the migrations and fails when the table or a column is missing: `@hamur/notifications: table "notifications" has no column "read_at"`. A delivery that the queue repeats leaves one row.

Call `notify` after a `db.transaction`, not in it. A queued delivery is not part of the transaction: it is made even when the transaction rolls back. With `queue: false`, and in a test app, the call rejects and no row is written: `db.run was called inside db.transaction; use the tx argument`.

#### The broadcast channel

The channel publishes `{ notification, data }` to the recipient's own topic, [`notificationTopic`](#notificationtopic), and a [live handler](/broadcasting) brings it to the page. Nothing is stored: a page that is closed gets nothing, so add the `database` channel for a list to come back to.

It needs the `bun`, `node` or `cloudflare` preset. Any other fails the build: `server/notifications/invoice-paid.ts: the broadcast channel needs a preset that publishes (bun, node, cloudflare)`. So does `cloudflare.websocket: "worker"`, which has no topics. With several instances, set [`server.pubsub`](/realtime#several-instances-serverpubsub).

A broadcast that the queue repeats is published again, and no other channel is.

### `notificationTopic`

```ts
function notificationTopic(to: Pick<Recipient, "type" | "id">): string
```

The topic of a recipient's broadcasts. No two recipients share one. Whoever reads the topic gets the notifications, so take the recipient from `getPrincipal`, never from the input of a request:

````ts [notifications/live.ts]
import { notificationTopic } from "@hamur/notifications/server"
import { createError, defineHandler, getPrincipal, subscribe } from "hamur/server"

export const notificationEvents = defineHandler({
  live: true,
  async *handler(_: unknown, { event, signal }) {
    const principal = await getPrincipal(event)
    if (!principal) throw createError({ status: 401, message: "Unauthorized" })
    const messages = subscribe(notificationTopic(principal), { signal })
    yield null
    for await (const message of messages) yield message as { notification: string; data: unknown }
  },
})
````

`getPrincipal` is the `principal` of your `server/policies/entities.ts`. Its `type` and `id` must be those you pass to `notify`.

A recipient without a `type` and an `id`, or with more than about 230 characters in them, throws a `TypeError`. `notify` then rejects before it sends anything.

### `listNotifications`

```ts
function listNotifications(
  to: Pick<Recipient, "type" | "id">,
  options?: { unread?: boolean; limit?: number; cursor?: string },
): Promise<{ items: NotificationRow[]; nextCursor: string | null }>
```

A page of the recipient's notifications, the newest first. `limit` is 1 to 100, 20 by default. Pass `nextCursor` back as `cursor` for the next page. `unread: true` leaves out those that were read.

The function does not check who calls it, so pass the signed-in user, never a recipient from the request:

```ts
// server/notifications.ts
import { listNotifications, markNotificationsRead } from "@hamur/notifications/server"
import { createError, cursorInput, defineHandler, getPrincipal, type HamurEvent } from "hamur/server"
import * as v from "valibot"

async function me(event: HamurEvent) {
  const principal = await getPrincipal(event)
  if (!principal) throw createError({ status: 401, message: "Unauthorized" })
  return principal
}

export const inbox = defineHandler({
  input: cursorInput(),
  handler: async (page, { event }) => listNotifications(await me(event), page),
})

export const markRead = defineHandler({
  method: "POST",
  input: v.object({ ids: v.union([v.literal("all"), v.array(v.string())]) }),
  handler: async ({ ids }, { event }) => markNotificationsRead(await me(event), ids),
})
```

A cursor that `listNotifications` did not return is a `400`. In an app without a notification that has the database channel the call rejects: `listNotifications needs a notification with the database channel`.

### `markNotificationsRead`

```ts
function markNotificationsRead(to: Pick<Recipient, "type" | "id">, ids: readonly string[] | "all"): Promise<number>
```

Marks the recipient's unread notifications with these ids, or all of them, and resolves to how many it marked. An id of another recipient is left as it is.

## `@hamur/notifications/test`

### `sentNotifications`

```ts
function sentNotifications(options?: { name?: NotificationName }): Promise<
  Array<{
    name: string
    channel: "mail" | "database" | "broadcast" | "webhook"
    recipient: { type: string; id: string }
    payload: unknown // what the channel's function returned
  }>
>
```

```ts
import { sentNotifications } from "@hamur/notifications/test"

expect(await sentNotifications({ name: "invoice-paid" })).toHaveLength(2)
```

It returns the deliveries of the test app, oldest first. In an app built by `setup` or the test preload, `notify` runs its deliveries in the call and records each one; no webhook is sent, nothing is broadcast, mail goes to the [outbox](/api-reference/mail), and the database channel writes its row.
