# Broadcasting

Broadcasting sends what happens on the server to every page that shows it: a document renamed by one user appears renamed for the others, and a room shows who is in it. It is not a new channel API. It is a [live handler](/realtime#live-handlers) that reads a **topic**, so one handler holds the three things a broadcast needs: who may listen (`authorize`), what the message looks like (the handler's types) and how it reaches the page (the live stream, read with `useAsyncData`).

## Listen to a topic

`subscribe(topic, { signal })` is an async iterable of the messages that [`publish`](/realtime#topics-and-publish) sends to the topic after the call. A string arrives as a string, a `Uint8Array` as a `Uint8Array`, and anything else as the value parsed back from the JSON text `publish` wrote.

````ts [realtime/broadcast-document.ts]
import { defineHandler, subscribe } from "hamur/server"
import { schema } from "./schema.ts"

export interface DocumentEvent {
  kind: "renamed"
  title: string
}

const documentInput = schema<{ id: string }>((value) => {
  const { id } = (value ?? {}) as { id?: unknown }
  return typeof id === "string" && id ? { value: { id } } : { issues: [{ message: "id is required", path: ["id"] }] }
})

export const documentEvents = defineHandler({
  live: true,
  input: documentInput,
  authorize: { action: "view", resource: (input) => ({ type: "Document", id: input.id }) },
  async *handler({ id }, { signal }) {
    const messages = subscribe(`doc:${id}`, { signal })
    yield null
    for await (const message of messages) yield message as DocumentEvent
  },
})
````

The handler does three things in order:

1. **`authorize`** runs before the handler, when a connection opens, again on every reconnect and when the page renders on the server. A denial answers 401, 403 or 404 and `subscribe` is never called. It does not close a stream that is already open: a user whose access ends is refused at the next connection. The policies behind `authorize` are described in the [`authorize` reference](/api-reference/server#authorize-can-caneach-explain-authzexplanation-handlerauthorize).
2. **`subscribe` before the first `yield`.** A message published after the `subscribe` call is kept, so none is lost between the call and the loop (on Cloudflare the Durable Object starts reading once the call reaches it).
3. **A first `yield` at once.** The page renders on the server with the first value, so a handler that waits for a message before yielding keeps the page waiting. Yield the current state, or `null` as here.

Anything can publish: a handler, a task, a plugin or a hook.

````ts [realtime/broadcast-publish.ts]
import { defineHandler, publish } from "hamur/server"

declare function saveTitle(id: string, title: string): Promise<void>

export const renameDocument = defineHandler({
  async handler({ id, title }: { id: string; title: string }) {
    await saveTitle(id, title)
    await publish(`doc:${id}`, { kind: "renamed", title })
  },
})
````

A page reads the stream like any live handler. The first value is rendered on the server and `data` follows every later one:

````tsx [react/broadcast-title.tsx]
import { useAsyncData } from "@hamur/adapter-react"
import { documentEvents } from "../realtime/broadcast-document.ts"

export default function Title({ id }: { id: string }) {
  const { data } = useAsyncData(documentEvents, { id })
  return <h1>{data?.title ?? "Untitled"}</h1>
}
````

Every reader of one handler with one input shares one request, so a hundred components showing document 42 hold one connection. Messages are not stored: a browser that was offline when one was published does not get it, and its reconnect starts the handler again, so make the first `yield` the state it must catch up with. A reader more than 256 messages behind ends with `subscribe("doc:42") fell 256 messages behind; the stream ends`, and the live client reconnects.

Topic names are non-empty strings of at most 256 characters. Topics that start with `hamur:` are Hamur's own: `subscribe` and `presence` take them, and `publish` and `peer.publish` from app code refuse them with `topics starting "hamur:" are Hamur's own`. One of them carries a user's [notifications](/api-reference/notifications#the-broadcast-channel).

## Show who is here

`presence(topic, member, { signal })` joins `member` (`{ id, data? }`) to the topic's member list and yields the whole list at once and on every change. The list is sorted by `id` with one entry per `id`, so a user with two tabs counts once. The member leaves when `signal` aborts, which is when the browser goes.

````ts [realtime/broadcast-presence.ts]
import { defineHandler, presence, type HamurEvent } from "hamur/server"
import { schema } from "./schema.ts"

declare function currentUser(event: HamurEvent): Promise<{ id: string; name: string }>

const roomInput = schema<{ room: string }>((value) => {
  const { room } = (value ?? {}) as { room?: unknown }
  return typeof room === "string" && room
    ? { value: { room } }
    : { issues: [{ message: "room is required", path: ["room"] }] }
})

export const whoIsHere = defineHandler({
  live: true,
  input: roomInput,
  authorize: { action: "view", resource: (input) => ({ type: "Room", id: input.room }) },
  async *handler({ room }, { event, signal }) {
    const user = await currentUser(event)
    const member = { id: user.id, data: { name: user.name } }
    for await (const members of presence(`room:${room}`, member, { signal })) yield members
  },
})
````

Take the member from the session, never from the input: a client that chooses its own `id` could join as someone else. `data` must be JSON.

- A topic holds at most 1000 members. One more `id` is refused with a 503, `presence("room:1") has 1000 members, its limit; the join is refused`. A member that is not JSON, or one that would take the members of the process to more than 16 MiB of JSON text, throws a `TypeError` at the call.
- A slow reader gets the latest list, never a backlog.
- With several instances (`server.pubsub`, below) each instance sends its members every 15 seconds, and drops those of an instance 45 seconds after its last message, so a crashed instance's members leave within that time.

## Per preset

| Preset                                                | `subscribe` and `presence` read                                                                                                              |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `bun`                                                 | this process; with [`server.pubsub`](/realtime#several-instances-serverpubsub), every instance                                               |
| `node`                                                | this process only: `server.pubsub` needs `Bun.redis`, so several `node` instances do not see each other                                      |
| `hamur dev`                                           | the dev server's process                                                                                                                     |
| `cloudflare`, `websocket: "durable"`                  | the Durable Object named `hamur`, through its RPC; the build binds `HAMUR_WS` when a server file imports them                                |
| `cloudflare`, `websocket: "worker"`                   | refused at the call: `WebSocket topics need cloudflare.websocket: "durable": a Worker cannot send to a socket that another request accepted` |
| `vercel`, `netlify` and other presets without sockets | refused at the call: `publish needs a preset that runs WebSockets (bun, node, cloudflare); this server runs on "netlify"`                    |

A live handler is an event stream, so the page works on every preset; only the topic needs a preset that runs sockets. On a preset that refuses, keep the live handler and read something else in it (a database poll), or move the app to `bun`, `node` or `cloudflare`.

On Cloudflare a `"durable"` app that imports `subscribe` or `presence` also gets the compatibility flag `enable_request_signal` in `.output/wrangler.json`, so a closed tab leaves a presence list at once instead of when the stream's heartbeat write fails. If your own flags hold `disable_request_signal`, the build leaves it.

With `server.pubsub`, an instance subscribes to a topic's Redis channel only while one of its readers or sockets holds the topic.

The signatures are in the [server API reference](/api-reference/server#subscribe).
