# Notifications

A **notification** tells a person that something happened: an invoice was paid, a teammate left a comment, a build failed. You write the notification once and name the **channels** it goes through. `@hamur/notifications` has four: a [mail](/mail), a signed web request (a **webhook**) to another system, a row in a list your app shows (the **inbox**), and a message to the page the person has open.

It is not a way to send mail. If you only need a mail, call `sendMail` ([Mail](/mail)). Use a notification when one event reaches a person in more than one way, or in the way that person chose.

This page starts with one notification that arrives by mail, then adds one channel at a time. The [`@hamur/notifications` reference](/api-reference/notifications) lists every option and error message.

## Send your first notification

The module needs [`@hamur/mail`](/mail) for the mail channel, so list both in `modules`. Setting up a transport is on the Mail page; the config below sends nothing until a build, as there.

````ts [platform/notifications-first.ts]
import mail from "@hamur/mail"
import notifications from "@hamur/notifications"
import { defineConfig, env } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  modules: [mail, notifications],
  site: { url: "https://acme.example" },
  mail: { from },
  $development: { site: { url: "http://localhost:3000" } },
  $production: { mail: { from, transport: { type: "resend", apiKey: env("RESEND_API_KEY") } } },
})
````

A notification is a file of `server/notifications/`. Its name is its path below that folder: `server/notifications/invoice-paid.ts` is `invoice-paid`, and `server/notifications/team/invited.ts` is `team:invited`. A file or folder whose name starts with `_` or `.` is not a notification, so put your helpers there, or next to the folder as the sample does.

````ts [mail/server/notifications/invoice-paid.ts]
import { defineNotification } from "@hamur/notifications/server"
import { schema } from "../schema.ts"

export default defineNotification({
  input: schema<{ invoiceId: string; amount: number }>((value) => {
    const { invoiceId, amount } = (value ?? {}) as { invoiceId?: unknown; amount?: unknown }
    if (typeof invoiceId !== "string" || !/^[\w-]{1,40}$/.test(invoiceId)) return "invoiceId is not an invoice id"
    if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) return "amount must be a number"
    return { invoiceId, amount }
  }),
  mail: ({ invoiceId, amount }) => ({
    subject: `Invoice ${invoiceId} is paid`,
    template: "InvoicePaid",
    props: { invoiceId, amount },
  }),
})
````

- **`input`** is a schema of the values the notification needs (any [Standard Schema](https://standardschema.dev), such as Valibot or Zod; the sample writes one by hand). `notify` checks the input before anything is sent, and a wrong input rejects with `notify("invoice-paid"): the input is refused by its schema: amount must be a number`. Check strictly: the values go into a mail and a web request. The sample allows an invoice id of letters, digits, `_` and `-` only, so it cannot hold a line break.
- **`mail`** is a function of the validated input. It returns a message like the one `sendMail` takes, without `to`: the notification is sent to the recipient's `email`. It uses a [template](/mail#a-template-in-your-ui-library) of `app/mail/`.

Then call `notify` where the thing happens:

````ts [mail/server/invoices.ts]
import { notify } from "@hamur/notifications/server"

interface Customer {
  id: string
  email: string
  mailOptOut: boolean
}

const customers = new Map<string, Customer>([
  ["c1", { id: "c1", email: "ada@example.com", mailOptOut: false }],
  ["c2", { id: "c2", email: "bob@example.com", mailOptOut: true }],
])

const invoices = new Map([
  ["2026-14", { amount: 90, customer: "c1" }],
  ["2026-15", { amount: 40, customer: "c2" }],
])

function ownerOf(invoiceId: string) {
  const invoice = invoices.get(invoiceId)
  const customer = invoice && customers.get(invoice.customer)
  if (!invoice || !customer) throw new Error(`Invoice ${invoiceId} not found`)
  return { invoice, customer }
}

export async function announcePaid(invoiceId: string): Promise<void> {
  const { invoice, customer } = ownerOf(invoiceId)
  await notify({ type: "Customer", id: customer.id, email: customer.email }, "invoice-paid", {
    invoiceId,
    amount: invoice.amount,
  })
}

export async function announceOverdue(invoiceId: string, days: number): Promise<void> {
  const { customer } = ownerOf(invoiceId)
  await notify(
    { type: "Customer", id: customer.id, email: customer.email, prefs: { mail: !customer.mailOptOut } },
    "invoice-overdue",
    { invoiceId, days },
  )
}
````

`notify(recipient, name, input)` takes who gets it, which notification, and the input. Typegen reads `server/notifications/`, so a misspelled name or a wrong input fails `tsc`.

Four details of the call keep it safe:

- **The recipient comes from your data, not from the request.** `announcePaid` is called by code that found the invoice and its customer in your own records, such as a payment provider's webhook handler. A handler that read the `email` from its input would mail anyone a notification of your app. A recipient is `{ type, id, email?, webhook?, prefs? }`. `type` is a name such as `Customer` and `id` is the id in your data; no two recipients may share both.
- **Only the fields above are used.** A row of your own may be passed, a password hash included; `notify` copies `type`, `id`, `email` and `prefs` and nothing else.
- **A recipient without what a channel needs is skipped, and the call says so.** A customer with no `email` gets no mail, and the log says `notify("invoice-paid"): Customer::"c1" has no email; the mail channel skipped it`. The other channels still run.
- **A notification that does not exist rejects** with `Notification "x" not found (notifications: invoice-paid)`.

A list of recipients works too: `notify([ada, bob], "invoice-paid", input)`. Each recipient and channel is one **delivery**.

## What happens after the call

By default `notify` does not wait for the deliveries. It validates the input, then hands **one task for each delivery** to your [queue](/tasks#queues-and-enqueue) and returns. The task `notifications:deliver` makes the delivery. A delivery that fails is tried again alone, so one broken webhook does not send the mail twice.

That has three consequences, so read them before you rely on a notification:

- **A delivery can fail after `notify` returned.** The page has already said "done". The failure is in the log, and with the `db` queue `hamur task failed` lists it.
- **A delivery can arrive twice.** A queue delivers at least once. A mail that was sent and whose answer was lost may be sent again; so may a webhook, and a broadcast is published again when its run is repeated. A mail whose delivery may have succeeded is not sent again by the task: it logs `…; the queue does not send it again` at `error` and leaves the decision to you. The webhook channel gives every delivery one `webhook-id` that is the same on each try, so a receiver can ignore a repeat.
- **Without a queue it is not durable.** On `bun` and `node` the default queue is the running process. A restart loses the deliveries that wait. Use `tasks.queue` as [Mail](/mail#queue-a-mail) shows when a lost notification matters.

To wait for the deliveries, pass `{ queue: false }` to the call or set `notifications.queue: false`. `notify` then runs every delivery in the call, and rejects after all of them ran when some failed: `notify("invoice-paid"): 1 of 6 deliveries failed: webhook to Tenant::"9": 502 Bad Gateway`. A delivery that ran has still happened. Do not call it again to repeat the ones that failed, or the others arrive twice.

## The webhook channel

A **webhook** is a web request your server sends to another system, such as a customer's server or a chat tool, to say that something happened. The receiver must be able to tell that the request came from you and was not changed, so every delivery is signed.

Add a `webhook` function to the notification. It returns the body, which is sent as JSON. `via` chooses channels for a recipient, and the next section explains it.

````ts [mail/server/notifications/invoice-overdue.ts]
import { defineNotification } from "@hamur/notifications/server"
import { schema } from "../schema.ts"

export default defineNotification({
  input: schema<{ invoiceId: string; days: number }>((value) => {
    const { invoiceId, days } = (value ?? {}) as { invoiceId?: unknown; days?: unknown }
    if (typeof invoiceId !== "string" || !/^[\w-]{1,40}$/.test(invoiceId)) return "invoiceId is not an invoice id"
    if (typeof days !== "number" || !Number.isInteger(days) || days < 1) return "days must be a whole number"
    return { invoiceId, days }
  }),
  mail: ({ invoiceId, days }) => ({
    subject: `Invoice ${invoiceId} is ${days} days overdue`,
    template: "InvoiceOverdue",
    props: { invoiceId, days },
  }),
  webhook: ({ invoiceId, days }) => ({ type: "invoice.overdue", invoiceId, days }),
  via: (to) => (to.prefs?.mail === false ? ["webhook"] : ["mail", "webhook"]),
})
````

A recipient with no `webhook` of its own gets the endpoint of the config, and a recipient without both is skipped with a warning. Set the endpoint and the secret in the config. The secret is a `whsec_` followed by the base64 of a random key, and it is `env("NAME")` like every secret:

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

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  modules: [mail, notifications],
  site: { url: "https://acme.example" },
  mail: { from },
  notifications: {
    webhook: { url: "https://hooks.acme.dev/hamur", secret: env("WEBHOOK_SECRET") },
  },
  $development: { site: { url: "http://localhost:3000" } },
  $production: { mail: { from, transport: { type: "resend", apiKey: env("RESEND_API_KEY") } } },
})
````

````sh [platform/webhook-secret.sh]
echo "whsec_$(openssl rand -base64 32)"
````

`WEBHOOK_SECRET` needs an entry in `app/env.ts`, written like the one on the [Mail](/mail#send-your-first-mail) page and given here with the sample app's:

````ts [mail/app/env.ts]
import { defineEnv } from "hamur"

const optional = (raw: string | undefined) => raw

export default defineEnv({
  RESEND_API_KEY: { schema: optional, description: "The Resend API key; only a build that sends mail needs it" },
  WEBHOOK_SECRET: { schema: optional, description: "The secret that signs webhooks: whsec_ and the base64 of a key" },
})
````

Tests record a webhook and never send it, so they need no secret. Under `hamur dev` the webhook channel fails with a message that the variable is not set until you put a value in `.env`.

Give the receiver the same secret through a safe channel. The request is a `POST` as [Standard Webhooks](https://www.standardwebhooks.com) describes, with the headers `webhook-id`, `webhook-timestamp` and `webhook-signature`.

A **tenant** or a customer may have an endpoint of its own. Put it on the recipient: `webhook: { url, secret }`, read from your database. It is sealed with `HAMUR_KEY` while a delivery waits in the queue, so a queue's records show neither the secret nor a token in the URL. An app without `HAMUR_KEY` cannot queue a delivery to one.

The URL may come from a user, so the module checks it, and checks it again at every send:

- it must be `https:` on the default port and name a host;
- the name must not resolve to a private, loopback or link-local address, so a customer cannot aim your server at your own network;
- no redirect is followed, and the receiver has 10 seconds to answer;
- every answer that is not 2xx fails the delivery with its status.

On the receiving side, check the signature **before** you read the body as data, check that the timestamp is recent, and ignore a `webhook-id` you have seen. This function checks the first two:

````ts [mail/server/receive-webhook.ts]
const TOLERANCE_SECONDS = 300

const bytesOf = (base64: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))

export async function verifyWebhook(
  secret: string,
  headers: Headers,
  body: string,
  now = Date.now(),
): Promise<boolean> {
  if (!secret.startsWith("whsec_")) throw new TypeError("The secret is whsec_ followed by the base64 of the key")
  const id = headers.get("webhook-id")
  const signatures = headers.get("webhook-signature")
  const timestamp = Number(headers.get("webhook-timestamp"))
  if (!id || !signatures || !Number.isInteger(timestamp)) return false
  if (Math.abs(now / 1000 - timestamp) > TOLERANCE_SECONDS) return false
  const key = await crypto.subtle.importKey(
    "raw",
    bytesOf(secret.slice("whsec_".length)),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["verify"],
  )
  const signed = new TextEncoder().encode(`${id}.${timestamp}.${body}`)
  for (const entry of signatures.split(" ")) {
    if (!entry.startsWith("v1,")) continue
    try {
      if (await crypto.subtle.verify("HMAC", key, bytesOf(entry.slice(3)), signed)) return true
    } catch {}
  }
  return false
}
````

Call it with the raw text of the body, not with parsed JSON. It compares in constant time, rejects a timestamp more than five minutes away, and accepts any `v1` signature in the header, since the standard lets a sender list several. Keep the secret in the receiver's environment, never in its code.

## Choose channels for each person

A notification with several channels sends all of them by default. A person may want fewer. `via(recipient, input)` returns the channels for one recipient. In the sample above it returns only `["webhook"]` when the recipient's `prefs.mail` is `false`, and both channels otherwise.

`prefs` is whatever your app stores, such as a column of settings. It is data for `via` and for nothing else. A channel that `via` names and the notification does not have is skipped with a warning. The build reads the channels from the keys of the object you pass to `defineNotification`, so write them out and do not spread another object in.

The `announceOverdue` function above passes `prefs: { mail: false }` for a customer who turned mail off, and that customer gets the webhook only.

## The inbox: the database channel

The inbox is a list inside your app, the bell with a number that a person opens. The database channel writes one row for each delivery into a table that **your app owns**, and `listNotifications` reads it.

Create the table in a [migration](/database#migrations):

````sql [inbox/server/db/migrations/0001_notifications.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);
````

The build reads the migrations and stops when the table or a column is missing: `@hamur/notifications: table "notifications" has no column "read_at"`. Keep the two dates as text; they hold ISO 8601. On MySQL use `varchar(255)` for the columns of the key and the index. Name the table and the connection with `notifications.table` and `notifications.connection` if they differ from `notifications` and `default`.

Add a `database` function. It returns what the inbox shows, and it is stored as JSON. Store what you need to draw the list (a title, an amount, a link), not a whole record of yours:

````ts [inbox/server/notifications/invoice-paid.ts]
import { defineNotification } from "@hamur/notifications/server"
import { schema } from "../schema.ts"

export default defineNotification({
  input: schema<{ invoiceId: string; amount: number }>((value) => {
    const { invoiceId, amount } = (value ?? {}) as { invoiceId?: unknown; amount?: unknown }
    if (typeof invoiceId !== "string" || !/^[\w-]{1,40}$/.test(invoiceId)) return "invoiceId is not an invoice id"
    if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) return "amount must be a number"
    return { invoiceId, amount }
  }),
  mail: ({ invoiceId, amount }) => ({
    subject: `Invoice ${invoiceId} is paid`,
    template: "InvoicePaid",
    props: { invoiceId, amount },
  }),
  database: ({ invoiceId, amount }) => ({ title: `Invoice ${invoiceId} was paid`, amount }),
  broadcast: ({ invoiceId }) => ({ invoiceId }),
})
````

A delivery that the queue repeats leaves one row. No row is ever removed for you, not even a read one, so add a scheduled [task](/tasks#schedules) that deletes old rows before the table grows large.

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

Two handlers serve the list. `listNotifications` returns a page of one recipient's rows, newest first, with a `nextCursor`; `markNotificationsRead` marks rows as read and returns how many it marked.

````ts [inbox/server/inbox.ts]
import { requireUserSession } from "@hamur/auth/server"
import { listNotifications, markNotificationsRead } from "@hamur/notifications/server"
import { cursorInput, defineHandler, type HamurEvent } from "hamur/server"
import { schema } from "./schema.ts"

async function recipient(event: HamurEvent) {
  const { user } = await requireUserSession(event)
  return { type: "User", id: user.id }
}

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

export const markRead = defineHandler({
  method: "POST",
  input: schema<{ ids: "all" | string[] }>((value) => {
    const { ids } = (value ?? {}) as { ids?: unknown }
    if (ids === "all") return { ids }
    if (Array.isArray(ids) && ids.length <= 100 && ids.every((id) => typeof id === "string"))
      return { ids: ids as string[] }
    return 'ids must be "all" or a list of at most 100 ids'
  }),
  handler: async ({ ids }, { event }) => markNotificationsRead(await recipient(event), ids),
})
````

**The recipient is the signed-in user, never a value of the request.** Both functions trust their argument, and `{ type: "User", id }` read from the input would let anyone read anybody's inbox. The sample reads the user from the session. A cursor that `listNotifications` did not return is a `400`, and an id of another recipient is left as it is.

Show the list in a page. It draws the rows, marks them read and refreshes:

````tsx [inbox/app/pages/index.tsx]
import { useAsyncData } from "@hamur/adapter-react"
import { useEffect } from "react"
import { inbox, markRead, notificationEvents } from "#server"

export default function Notifications() {
  const list = useAsyncData(inbox)
  const live = useAsyncData(notificationEvents)

  useEffect(() => {
    if (live.data) void list.refresh()
  }, [live.data])

  async function readAll() {
    await markRead({ ids: "all" })
    await list.refresh()
  }

  return (
    <main>
      <h1>Notifications</h1>
      <button type="button" onClick={() => void readAll()}>
        Mark all as read
      </button>
      <ul>
        {list.data?.items.map((item) => (
          <li key={item.id} style={{ fontWeight: item.readAt === null ? "bold" : "normal" }}>
            {(item.data as { title: string }).title}
          </li>
        ))}
      </ul>
    </main>
  )
}
````

## Tell the open page: the broadcast channel

The broadcast channel publishes a message to the browser the person has open, so the bell changes without a reload. Nothing is stored: a page that is closed gets nothing. Add it **beside** the database channel, which keeps the list a person returns to. The sample notification above has both.

A message goes to a **topic** of the recipient, `notificationTopic({ type, id })`, and a [live handler](/broadcasting) reads that topic and sends it to the page:

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

export const notificationEvents = defineHandler({
  live: true,
  async *handler(_: unknown, { event, signal }) {
    const { user } = await requireUserSession(event)
    const messages = subscribe(notificationTopic({ type: "User", id: user.id }), { signal })
    yield null
    for await (const message of messages) yield message as { notification: string; data: unknown }
  },
})
````

Whoever reads the topic gets the person's notifications, so the live handler takes the recipient from the session and never from its input. The `type` and the `id` must be those you pass to `notify`. The page above reads the handler with `useAsyncData` and loads the list again when a message arrives. The first value is `null`, which draws the page at once.

The channel needs a preset that publishes, `bun`, `node` or `cloudflare` with `cloudflare.websocket: "durable"`. Another preset fails the build: `server/notifications/invoice-paid.ts: the broadcast channel needs a preset that publishes (bun, node, cloudflare)`. With several instances, set [`server.pubsub`](/realtime#several-instances-serverpubsub), or a message reaches only the browsers of the instance that published it. See [Broadcasting](/broadcasting#per-preset) for each preset.

## Test notifications

Under `hamur/test` a notification does not leave the app. `notify` runs every delivery in the call, records it, and returns after all of them ran. No webhook is sent and nothing is broadcast. Mail goes to the [outbox](/mail#test-the-mail), and the database channel writes its row. `sentNotifications` returns the deliveries, oldest first, and `{ name }` keeps one notification's.

````ts [mail/test/invoice-paid.test.ts]
import { sentNotifications } from "@hamur/notifications/test"
import { expect, test } from "bun:test"
import { announceOverdue, announcePaid } from "../server/invoices.ts"

const channelsTo = async (name: "invoice-paid" | "invoice-overdue", id: string) =>
  (await sentNotifications({ name }))
    .filter(({ recipient }) => recipient.id === id)
    .map(({ channel }) => channel)
    .sort()

test("a paid invoice is told by mail", async () => {
  await announcePaid("2026-14")
  expect(await channelsTo("invoice-paid", "c1")).toEqual(["mail"])
})

test("an overdue invoice is told by mail and by webhook", async () => {
  await announceOverdue("2026-14", 3)
  expect(await channelsTo("invoice-overdue", "c1")).toEqual(["mail", "webhook"])
})

test("a customer who turned mail off gets the webhook only", async () => {
  await announceOverdue("2026-15", 3)
  expect(await channelsTo("invoice-overdue", "c2")).toEqual(["webhook"])
})
````

Each record has the `name`, the `channel`, the `recipient` and the `payload` the channel's function returned. The list is not emptied between tests, so filter by recipient as the sample does.

A receiver of webhooks is tested like any function. This one signs a body itself, so no secret is written in the test:

````ts [mail/test/receive-webhook.test.ts]
import { createHmac, randomBytes } from "node:crypto"
import { expect, test } from "bun:test"
import { verifyWebhook } from "../server/receive-webhook.ts"

const key = randomBytes(32)
const secret = `whsec_${key.toString("base64")}`
const now = Date.now()
const body = JSON.stringify({ type: "invoice.overdue", invoiceId: "2026-14", days: 3 })

function signed(at: number, text = body) {
  const timestamp = Math.floor(at / 1000)
  const signature = createHmac("sha256", key).update(`msg_1.${timestamp}.${text}`).digest("base64")
  return new Headers({
    "webhook-id": "msg_1",
    "webhook-timestamp": String(timestamp),
    "webhook-signature": `v1,${signature}`,
  })
}

test("a delivery that was signed with the secret and is recent passes", async () => {
  expect(await verifyWebhook(secret, signed(now), body, now)).toBe(true)
})

test("a changed body, a wrong key and a stale timestamp fail", async () => {
  expect(await verifyWebhook(secret, signed(now), `${body} `, now)).toBe(false)
  const other = `whsec_${randomBytes(32).toString("base64")}`
  expect(await verifyWebhook(other, signed(now), body, now)).toBe(false)
  expect(await verifyWebhook(secret, signed(now - 10 * 60_000), body, now)).toBe(false)
})
````

## What to read next

[Mail](/mail) has the transports, the templates and the queue that the mail channel uses. [Broadcasting](/broadcasting) explains topics and presence. The [`authorize` reference](/api-reference/server#authorize-can-caneach-explain-authzexplanation-handlerauthorize) shows how to decide who may read a topic. The [`@hamur/notifications` reference](/api-reference/notifications) lists every export.
