# Realtime

This page is the guide through everything that keeps a connection open: WebSockets and their topics, JSON-RPC, streamed responses, streamed uploads, live handlers and synced state. It says which preset runs what and where each limit is. The option tables and the exact messages are in the [server API reference](/api-reference/server).

## Choosing a tool

| You want to                                            | Use                                                                                           |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| send many small messages both ways                     | a [WebSocket](#websockets-per-preset): `defineHandler({ route, websocket })`                  |
| send one message to everyone in a room                 | [topics](#topics-and-publish): `peer.subscribe`, `peer.publish`, `publish`                    |
| call server methods over one connection                | [JSON-RPC](#json-rpc): `jsonRpc` on a handler, with or without `websocket`                    |
| push events from the server to a page                  | [server-sent events](#streamed-responses): an `AsyncIterable` handler, or `createEventStream` |
| write a streamed body that is not events               | `createStream`                                                                                |
| read a large upload as it arrives                      | [`readBodyStream`](#streamed-uploads)                                                         |
| show a value that changes on the server in a component | a [live handler](#live-handlers) and `useAsyncData`                                           |
| tell every page that shows a record that it changed    | [broadcasting](/broadcasting): a live handler that reads a topic with `subscribe`             |
| show who is in a room                                  | [`presence`](/broadcasting#show-who-is-here) in a live handler                                |
| share a small value between the pages of many users    | [synced state](#synced-state)                                                                 |

## WebSockets per preset

A socket is `defineHandler({ route, websocket })`, written the same way on every preset. What changes is where it runs.

| Preset                                                        | Sockets run through                                                     | Hooks run in                      | `publish` reaches                                                 |
| ------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------- | ----------------------------------------------------------------- |
| `bun`                                                         | `Bun.serve`'s `websocket`                                               | the process                       | the process's subscribers; with `server.pubsub`, every instance's |
| `node`                                                        | `node:http`'s `upgrade` event, RFC 6455 written by Hamur, no dependency | the process                       | the process's subscribers                                         |
| `cloudflare`, `cloudflare.websocket: "durable"` (the default) | the Durable Object `HamurWebSocket` Hamur generates, with hibernation   | the object                        | the subscribers in the object named `hamur`                       |
| `cloudflare`, `cloudflare.websocket: "worker"`                | `new WebSocketPair()` in the Worker                                     | the isolate that took the upgrade | nobody: topics throw                                              |
| `static`, `vercel`, `netlify`                                 | none                                                                    |                                   | the build fails                                                   |
| `hamur dev`                                                   | the dev runner, relayed to the server worker                            | the worker                        | the worker's subscribers; a reload closes its sockets with `1012` |

A build for a preset without sockets fails and names the handler's file and export:

```
WebSockets are not supported by the netlify preset (server/chat.ts#chat)
```

`server.syncedState` fails the same way: `server.syncedState needs WebSockets, which the "netlify" preset cannot run (it runs on: bun, node, cloudflare)`. A WebSocket handler has no stub: importing one from `#server` fails with `<file> imports chat from "#server", but it is a websocket: it answers a URL, not a call`. OpenAPI lists none.

On every row the same steps run before the upgrade, in this order: the request steps, `handlerMiddleware`, the handler's `middleware`, the `426` for a request without `Upgrade: websocket`, the origin check and the `upgrade` hook. A refusal at any of them leaves no socket. The hooks of one socket run one after the other (`open`, each `message`, `close`), in the order the platform delivered them, so a `message` never runs before `open` finished. A hook that throws or rejects goes to `error(peer, error)` and the socket stays open; Bun has no socket error callback, so on bun `error` sees only hook errors, while on Cloudflare it also sees the platform's.

### What each preset honours

| Option or field            | `bun`, `node`                                 | `cloudflare`                                                                                     |
| -------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `idleTimeout`, `ping`      | yes                                           | ignored: Cloudflare decides idle sockets                                                         |
| `maxBackpressure`, `drain` | yes                                           | ignored: Cloudflare does not tell how much is buffered, so `peer.send` returns `0`               |
| `compress`                 | yes                                           | ignored                                                                                          |
| `peer.terminate()`         | ends the connection; `close` runs with `1006` | closes with `1011` and reason `"terminated"`: a Worker cannot end a socket without a close frame |
| topics                     | yes                                           | `"durable"` only                                                                                 |

When a route's `websocket` object sets `idleTimeout`, `ping`, `maxBackpressure` or `compress`, the cloudflare build logs one line for the route: `websocket idleTimeout, ping of /ws/chat (server/chat.ts#chat) are ignored on the cloudflare preset: workerd decides them`.

## The `websocket` object

The object holds hooks and options. Any other key throws `websocket key "x" is not a key; use origin, upgrade, open, message, close, error, drain, idleTimeout, ping, maxBackpressure, compress, schema, durableName`.

````ts [realtime/chat.ts]
import { defineHandler } from "hamur/server"
import { schema } from "./schema.ts"

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

const outgoing = schema<{ text: string; at: number }>((value) => ({ value: value as { text: string; at: number } }))

export const chat = defineHandler({
  route: "/api/chat",
  websocket: {
    origin: ["https://app.example"],
    idleTimeout: 120,
    ping: 30,
    maxBackpressure: 16 * 1024 * 1024,
    compress: false,
    schema: { message: incoming, send: outgoing },
    open: (peer) => peer.send({ text: `${peer.peers.size} online`, at: Date.now() }),
    message: (peer, { text }) => peer.send({ text, at: Date.now() }),
    close: (peer, code, reason) => console.log(peer.id, code, reason),
    error: (peer, error) => console.error(peer.id, error),
    drain: (peer) => console.log(peer.id, "buffer flushed"),
  },
})
````

### Options and their defaults

| Key               | Default             | Meaning                                                                                                                                                 |
| ----------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `origin`          | `"same"`            | who may open the socket from a browser page; see [the origin check](#the-origin-check)                                                                  |
| `idleTimeout`     | `120`               | seconds without any frame from the client before the peer is closed with `1001` and reason `"idle timeout"`; `0` is off                                 |
| `ping`            | `30`                | seconds without a frame before the server sends a ping, and again every `ping` seconds; browsers answer with a pong, which resets the timer; `0` is off |
| `maxBackpressure` | `16777216` (16 MiB) | bytes buffered for one peer; above it the peer is closed with `1008` and reason `"backpressure"`                                                        |
| `compress`        | `false`             | `permessage-deflate` when the client offers it                                                                                                          |
| `schema`          | none                | `{ message?, send? }` Standard Schemas: the route speaks JSON both ways                                                                                 |
| `durableName`     | `"hamur"`           | on cloudflare `"durable"`, the name of the object that holds the socket                                                                                 |

`idleTimeout` and `ping` are integers from `0` to `86400`, and `ping` must be below `idleTimeout` when both are on: `websocket ping (30) must be below idleTimeout (20), or 0`. The other checks throw at definition: `websocket maxBackpressure must be a positive integer of bytes (got 0)`, `websocket compress must be true or false (got "yes")`, `websocket durableName must be a function (got "room")`, `websocket schema key "x" is not a key; use message, send`, `websocket schema.message must be a Standard Schema`, and `WebSocket hook "drain" must be a function`.

Frames:

- A text frame reaches `message` as a string and a binary frame as a `Uint8Array`.
- A message above `server.maxBodySize` (1 MiB by default) closes the socket: `1009` on node, counted per fragment and, for a compressed message, after it is inflated. On bun, Bun closes it and the client sees `1006`.
- A peer whose hook queue holds 4096 messages that have not finished is closed with `1008` and reason `"too many queued messages"`.
- `peer.send(data)` returns the bytes still buffered for the peer. `drain(peer)` runs once, each time the buffer a `send` left is written, which is the moment to send more.
- `compress: true` negotiates `permessage-deflate` with no context takeover; each message is compressed alone, and messages under 1024 bytes on node go uncompressed.

### JSON in both directions

With `schema`, a text frame is parsed and validated by `schema.message` before `message` runs, and `message` gets the value. A frame that is binary, not JSON or invalid reaches `error` as a `400` `HamurError` (`WebSocket message must be a JSON text frame`, `WebSocket message is not JSON`, `Invalid WebSocket message` with the issues in `data`); `message` does not run and the socket stays open. Every `peer.send` and `peer.publish` value goes as its JSON text, and `schema.send` only types it: it is never run. Without `schema`, `peer.send` takes a string, an `ArrayBuffer` or a `Uint8Array` and throws `peer.send takes a string, ArrayBuffer or Uint8Array; set websocket.schema to send JSON values` for anything else.

### The origin check

A browser sends the page's cookies with a WebSocket handshake from any site, so a socket refuses another origin by default. With `origin: "same"` an upgrade passes when it has no `Origin` header (a non-browser client), when the `Origin` host is the host of the request (with `server.trustProxy`, the forwarded host), or when the `Origin` is in `server.originCheck.allow`. Anything else gets `403` with `WebSocket origin not allowed` before `open` runs, and the server logs a warning once per origin.

| `origin`                     | Passes                                                                               |
| ---------------------------- | ------------------------------------------------------------------------------------ |
| `"same"`                     | the rule above                                                                       |
| `"any"`                      | every upgrade                                                                        |
| `["https://admin.example"]`  | exactly those origins, and an absent `Origin`                                        |
| `(origin, event) => boolean` | what the function says, called for every upgrade, with `null` for an absent `Origin` |

A list entry that is not an origin, such as `"https://a.example/x"`, throws `WebSocket origin entry "https://a.example/x" must be an origin such as "https://app.example" (scheme, host and port only)` when the handler is defined. `hamur dev` applies the same check.

### The `upgrade` hook and the peer's fields

`upgrade(event)` runs after the origin check and before the platform upgrade, with the request's event. Return nothing to upgrade, a `Response` (or throw one, or a `createError`) to refuse, or `{ protocol, headers, context }`: `protocol` is one of the values the client offered in `Sec-WebSocket-Protocol`, `headers` are added to the `101`, and `context` is assigned into `event.context`, so into `peer.context`. A `protocol` the client did not offer answers `500` and logs `upgrade() chose protocol "x" the client did not offer`. When `upgrade` chooses none, bun answers with the first protocol the client offered, while node and cloudflare send none; choose it in `upgrade` when it matters.

````ts [realtime/upgrade.ts]
import { createError, defineHandler } from "hamur/server"

export const feed = defineHandler({
  route: "/api/feed",
  websocket: {
    upgrade(event) {
      const token = event.url.searchParams.get("token")
      if (!token) throw createError({ status: 401 })
      if (token === "banned") return new Response("Banned", { status: 403 })
      return {
        protocol: "feed-v1",
        headers: { "x-feed": "1" },
        context: { token, userAgent: event.request.headers.get("user-agent") },
      }
    },
    open(peer) {
      console.log(peer.id, peer.remoteAddress, peer.readyState, peer.context.token, peer.request.url)
      peer.send(`${peer.peers.size} online`)
    },
    message(peer, message) {
      if (message === "bye") peer.close(1000, "bye")
      if (message === "drop") peer.terminate()
    },
  },
})
````

| Peer field                                           | Meaning                                                                                                   |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `id`                                                 | a random id, kept across a hibernation wake on cloudflare                                                 |
| `request`, `params`, `context`                       | the upgrade request, its route params and `event.context` as middleware and `upgrade` left it             |
| `remoteAddress`                                      | what `getRequestIP(event)` gave at the upgrade; `undefined` when unknown                                  |
| `peers`                                              | the open peers of the same route in this process (on cloudflare, in its object), the peer itself included |
| `readyState`                                         | `1` from `open`, `2` once `close()` was called or a close frame arrived, `3` inside `close`               |
| `topics`                                             | the topics the peer holds; empty once it closed                                                           |
| `send(data)`, `close(code?, reason?)`, `terminate()` | a reason above 123 bytes throws `RangeError: WebSocket close reason must be 123 bytes or fewer`           |

`peer.close(code, reason)` sends the close frame and, when the client does not answer within 5 seconds, ends the connection; `close` then runs with the code that was sent. A connection lost without a close frame gives `1006`.

## Topics and `publish`

`peer.subscribe(topic)` and `peer.unsubscribe(topic)` join and leave a topic. `peer.publish(topic, data)` sends to every subscriber but the sender. `publish(topic, data)` from `hamur/server` sends to every subscriber, from any handler, plugin, task or hook; a value that is not a string, `ArrayBuffer` or `Uint8Array` goes as its JSON text. It resolves when the local peers have it and, with `server.pubsub`, when the driver took it.

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

export const room = defineHandler({
  route: "/api/room",
  websocket: {
    open: (peer) => peer.subscribe("room"),
    message: (peer, message) => peer.publish("room", message),
    close: (peer) => console.log(peer.id, "held", [...peer.topics]),
  },
})

export const announce = defineHandler({
  route: "/api/announce",
  method: "POST",
  handler: async () => {
    await publish("room", { notice: "maintenance at 22:00" })
  },
})
````

- A topic is a non-empty string of at most 256 characters, else `TypeError: WebSocket topic must be a non-empty string of at most 256 characters`.
- Never subscribe a socket to a topic name its client sent without checking it: `hamur:notifications:…` topics carry users' private data. `publish` and `peer.publish` refuse topics that start with `hamur:`.
- Subscribing twice is one subscription. A closed peer leaves all its topics before `close` runs, so a publish from `close` does not reach it.
- `publish` on a server that cannot run sockets rejects with `publish needs a preset that runs WebSockets (bun, node, cloudflare); this server runs on "netlify"`.
- On cloudflare `"worker"` there are no topics, because a Worker can send only on the sockets of its own request: `subscribe` and `peer.publish` throw, and `publish` rejects with `WebSocket topics need cloudflare.websocket: "durable": a Worker cannot send to a socket that another request accepted`. Sockets that share topics need `"durable"`.

### Several instances: `server.pubsub`

Topics reach the peers of one process. With several instances of an app on the `bun` preset, `server.pubsub` carries `publish` and `peer.publish` between them through Redis (`Bun.redis`).

````ts [realtime/pubsub-config.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "html",
  preset: "bun",
  server: { pubsub: { driver: "redis", url: "redis://cache:6379", channelPrefix: "hamur:" } },
})
````

`url` defaults to `REDIS_URL`, and `channelPrefix` to `"hamur:"`. A start with neither `url` nor `REDIS_URL` fails with `server.pubsub needs url or REDIS_URL`, and a URL that is not `redis://` or `rediss://` with `server.pubsub.url must be a redis:// or rediss:// URL`. A topic message goes on the channel `<channelPrefix>ws:<topic>`; every instance delivers it to its own subscribers and skips its own messages, so nothing arrives twice. A payload over 16 MiB goes to the local peers only. `revalidateTag`, `revalidatePath`, `invalidateRouteCache` and a cache's `expire()` also go on `<channelPrefix>cache:invalidate` when they reached a `memory` mount, so the other instances drop the same entries. When Redis is unreachable, `publish` reaches the local peers only, the server logs `server.pubsub lost redis://cache:6379; retrying` once per outage (without the password) and reconnects after 100 ms, doubling up to 5 s.

On any preset but `bun` the build fails: `server.pubsub needs Bun.redis, which the "node" preset cannot run (it runs on: bun)`. On Cloudflare a Durable Object is one instance for its sockets, and the objects of other names are reached through the object's RPC `publish`, below.

A small chat with rooms, a validated room name and escaped messages is in `examples/websocket-chat/`.

## Durable Objects on Cloudflare

With `cloudflare.websocket: "durable"` the build writes the class `HamurWebSocket extends DurableObject` into the server bundle and exports it beside the default export. The Worker runs the steps before the upgrade, then forwards the request to the object named by `durableName(event)`, and the object accepts the socket with Cloudflare's hibernation API and runs the hooks. Peers of one name share one object, its `peer.peers` and its topics. `durableName` must return a non-empty string, else the upgrade answers `500` and logs `websocket durableName of /ws/chat must return a non-empty string (got <value>)`.

````ts [realtime/durable-name.ts]
import { defineHandler } from "hamur/server"

export const board = defineHandler({
  route: "/api/boards/:id",
  websocket: {
    durableName: (event) => `board-${event.params.id ?? "main"}`,
    open: (peer) => peer.subscribe("cursor"),
    message: (peer, message) => peer.publish("cursor", message),
  },
})
````

`peer.context` in the object is the JSON copy of the upgrade event's `context`: functions and `undefined` drop and a `Date` becomes its string. A context `JSON.stringify` cannot write (a cycle, a `BigInt`) refuses the upgrade with `500`.

The classes of your own come from `defineServer({ exports: { Counter } })`; see [Deploy](/deploy/presets/cloudflare#durable-objects). The build binds `HamurWebSocket` as `HAMUR_WS` in `.output/wrangler.json` and, when your `wrangler.json` has no `migrations`, writes the migration `hamur-ws-v1`; the rules and the build errors for a config with its own migrations are in [Deploy](/deploy/presets/cloudflare#websockets). The object's RPC method `publish(topic, data)` reaches the subscribers of that object: `env.HAMUR_WS.get(env.HAMUR_WS.idFromName("room-1")).publish("room", text)`. `publish` from `hamur/server` reaches only the object named `hamur`.

### Hibernation limits

Cloudflare evicts an idle object and keeps its sockets open. A woken object rebuilds every peer and its topics from the socket's attachment, so these limits apply:

- The attachment holds the peer's `id`, `params`, route, upgrade URL, `remoteAddress`, topics and `context`, and Cloudflare allows at most 2048 bytes. Above it `context` is left out and the route logs once `peer context of /ws/chat is above Cloudflare's 2048-byte socket attachment; it is not kept across hibernation`. When it is still too large, `subscribe` throws `RangeError: WebSocket peer state of /ws/chat is above Cloudflare's 2048-byte socket attachment; subscribe to fewer topics` and keeps the topics the peer had. At the upgrade the same overflow answers `500` before `open`.
- After a wake `open` does not run again. `peer.request` holds the upgrade URL without its query and no headers; copy what you need into `event.context` in middleware or `upgrade`.
- A protocol ping gets its pong from Cloudflare and reaches no hook. An app's own `"ping"` text message reaches `message` as any other.
- A message above `server.maxBodySize` closes with `1009`, and a woken socket whose route no longer exists closes with `1011`.

## JSON-RPC

The `jsonRpc` key makes a route a [JSON-RPC 2.0](https://www.jsonrpc.org/specification) endpoint. Each method is a handler made with `defineHandler`, so a call's `params` is its `input`, checked as any input is, and its `middleware` runs. Without `websocket` the route answers `POST` only, with `application/json` (`415` otherwise) and `maxBatchSize` requests at most (default `50`). With `websocket` beside it the route is a socket whose text frames are requests, one request or batch per frame, answered on the same peer; `upgrade`, `open`, `close`, `error` and the options stay, `message` is refused, and a binary frame answers `-32600`. Over a socket `ctx.signal` aborts when the peer closes.

````ts [realtime/rpc.ts]
import { defineHandler } from "hamur/server"
import { schema } from "./schema.ts"

const operands = schema<{ a: number; b: number }>((value) => {
  const { a, b } = (value ?? {}) as { a?: unknown; b?: unknown }
  return typeof a === "number" && typeof b === "number"
    ? { value: { a, b } }
    : { issues: [{ message: "a and b must be numbers" }] }
})

const add = defineHandler({
  input: operands,
  handler: ({ a, b }) => a + b,
})

export const rpc = defineHandler({ route: "/rpc", jsonRpc: { methods: { add }, maxBatchSize: 50 } })

export const rpcSocket = defineHandler({
  route: "/rpc/ws",
  websocket: { origin: "same" },
  jsonRpc: { methods: { add } },
})
````

The answers are JSON-RPC's: `-32700` for text that is not JSON, `-32600` for a request that is not valid, an empty batch or one above `maxBatchSize`, `-32601` for an unknown method, `-32602` with `data: { issues }` when `input` refuses `params`, `-32000` with `data: { status, data }` for a thrown `createError(...)` or a `fail(status, data)`, and `-32603` for anything else, with the thrown message in dev only. A request without `id` is a notification and gets no answer; a batch of notifications answers `204`. A batch runs its calls together and answers in request order.

## Streamed responses

A handler that returns an `AsyncIterable` or a `ReadableStream` answers as `text/event-stream`, one `data:` event per value, `event: end` when the iterable ends, and `event: error` with the masked error on a throw. It is the shortest way to push events, and the stub of a call reads that answer.

````ts [realtime/iterable.ts]
import { defineHandler } from "hamur/server"

export const countdown = defineHandler({
  route: "/api/countdown",
  method: "GET",
  async *handler(_, { signal }) {
    for (let n = 5; n >= 0 && !signal.aborted; n--) {
      yield { n }
      await new Promise((resolve) => setTimeout(resolve, 1000))
    }
  },
})
````

`createEventStream(event, source)` is the same wire with the control in your hands. Its second argument, a function, is the generator form: each `{ data, id?, event?, retry? }` you yield is one push, the next value is pulled once the client has read the last, and the end writes `event: end`. A client that goes aborts the `signal` and calls the generator's `return()`, so `finally` runs once. Resuming is yours: read `last-event-id` and start after it.

````ts [server/event-generator.ts]
import { createEventStream, defineHandler, getRequestHeader } from "hamur/server"

export const ticks = defineHandler({
  route: "/api/ticks",
  method: "GET",
  raw: true,
  handler(_, { event }) {
    const after = Number(getRequestHeader(event, "last-event-id") ?? 0)
    return createEventStream(event, async function* (signal) {
      for (let n = after + 1; n <= after + 5 && !signal.aborted; n++) {
        yield { data: { n }, id: String(n), retry: 5000 }
        await new Promise((resolve) => setTimeout(resolve, 1000))
      }
    })
  },
})
````

`createEventStream(event, { heartbeat })` without a function returns `push`, `close`, `onClosed` and `send()` for a producer that is not a generator; see [Server](/server#server-sent-events).

`createStream(event, write, { type })` writes a body that is not events: plain text, NDJSON, a file as it is made. `write` receives `s.write(chunk)`, `s.pipe(stream)`, `s.sleep(ms)`, `s.onAbort(callback)` and `s.aborted`, and waits while the client has not read what was sent. A throw in `write` cuts the stream and reaches the `error` hook; the status is already sent. `type` that is not a string throws `TypeError: createStream type must be a content type string`, and a chunk that is not a string or a `Uint8Array` throws `TypeError: createStream write takes a string or a Uint8Array`.

````ts [server/create-stream.ts]
import { createStream, defineHandler } from "hamur/server"

export const lines = defineHandler({
  route: "/api/lines",
  method: "GET",
  raw: true,
  handler(_, { event }) {
    return createStream(
      event,
      async (s) => {
        for (let i = 1; i <= 5 && !s.aborted; i++) {
          await s.write(`line ${i}\n`)
          await s.sleep(1000)
        }
      },
      { type: "text/plain; charset=utf-8" },
    )
  },
})
````

`$fetch.stream(url)`, in the browser or on the server, reads such a stream as `for await (const e of $fetch.stream("/api/ticks"))`, each `e` being `{ data, text, event, id }`. It stops at `event: end`, throws at `event: error`, and after a dropped connection opens again after the server's `retry` (default 3000 ms) with `Last-Event-ID` set. `break` or `options.signal` stops it. An answer that is not `text/event-stream` throws `TypeError: $fetch.stream expected text/event-stream from /api/ticks, got application/json`. With a route's `events` schema, `e.data` has its type.

````ts [api/app-fetch-stream.ts]
import { $fetch } from "hamur/app"

export async function firstTicks(signal: AbortSignal): Promise<number[]> {
  const seen: number[] = []
  for await (const e of $fetch.stream("/api/ticks", { signal })) {
    seen.push((e.data as { n: number }).n)
    if (seen.length === 3) break
  }
  return seen
}
````

### Platform limits on one response

Every streamed answer goes through the body's backpressure, ends at once when the client aborts, and turns the bun idle timeout off. It still ends at the platform's own limit, which Hamur cannot raise:

| Preset        | Limit on one response                                                                                       |
| ------------- | ----------------------------------------------------------------------------------------------------------- |
| `bun`, `node` | none; the event stream's heartbeat (`: ping` every 15 s) keeps proxies in front from cutting a quiet stream |
| `cloudflare`  | none while the client stays connected                                                                       |
| `vercel`      | the function's `maxDuration`: 300 s by default, up to 800 s on Pro and Enterprise                           |
| `netlify`     | 60 s, not configurable; a streamed response is also capped at 20 MB                                         |

A client that must stay subscribed longer reconnects; an `EventSource` does so on its own, and so does `$fetch.stream`. WebSockets on Cloudflare are not streamed responses and have no such limit.

## Streamed uploads

`readBodyStream(event, { maxBodySize })` returns the request body as it arrives, never buffered. `maxBodySize` defaults to `server.maxBodySize`: a `content-length` above it errors the stream before the first read, and a chunked body errors once the bytes read pass it, both with `413` `Request body is too large`, and the request body is cancelled. A client that leaves mid-upload errors it with `400`. `server.maxRequestBodySize` still caps the request before the handler runs. Raise both for a large upload.

````ts [realtime/upload.ts]
import { defineHandler, readBodyStream } from "hamur/server"

export const upload = defineHandler({
  route: "/api/upload",
  method: "PUT",
  raw: true,
  async handler(_, { event }) {
    const reader = readBodyStream(event, { maxBodySize: 512 * 1024 * 1024 }).getReader()
    let bytes = 0
    for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) bytes += chunk.value.byteLength
    return Response.json({ bytes })
  },
})
````

The body can be read once: a second `readBodyStream`, or `readBody` after it, throws `TypeError: the request body was already read`, and so do `readBody`, `readFormData`, `readBodyBytes` and `readMultipart` after it. For `multipart/form-data` use `readMultipart(event, { onFile })`, which already hands each file to `onFile` as a stream without buffering it; see [Uploads](/forms-and-login#uploads).

## Live handlers

A handler with `live: true` and an `async function*` as its `handler` yields values; each one replaces the last for every reader of the same input. Read it with `useAsyncData(visitors, { room: "lobby" })`: the first value is rendered on the server and `data` then follows every value. A call outside a component returns a `LiveQuery`: `await` gives the first value, `current` the last, and `subscribe(callback)` hears the later ones.

````ts [realtime/live.ts]
import { defineHandler } from "hamur/server"
import { schema } from "./schema.ts"

declare function count(room: string): Promise<number>
declare function changes(room: string, signal: AbortSignal): AsyncIterable<void>

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 visitors = defineHandler({
  live: true,
  input: roomInput,
  timeout: 10,
  async *handler({ room }, { signal }) {
    yield await count(room)
    for await (const _ of changes(room, signal)) yield await count(room)
  },
})

export async function watch(): Promise<() => void> {
  const query = visitors({ room: "lobby" })
  const first = await query
  console.log(first, query.connected, query.error)
  return query.subscribe((value) => console.log("now", value, query.current))
}
````

Components that read one handler with one input share one `GET <baseURL>_hamur/fn/<id>` request, answered as an event stream with `cache-control: no-store`; it closes a microtask after the last reader leaves. A dropped connection reconnects after 1 s, doubling to 30 s, and at once on `online`; the generator starts again, so its first value replaces the last. `event: end` stops the query without reconnecting, `current` kept. `timeout` bounds the time to the first value only. A live handler cannot have `route`, `raw`, `websocket`, `jsonRpc`, `batch`, `cache`, `prerender`, `output` or `form`. The details are in [Handlers](/handlers#live-handlers) and [`LiveQuery`](/api-reference/app#livequery). To push what `publish` sends to a topic into a live handler, with `authorize` and `presence`, see [Broadcasting](/broadcasting).

## Synced state

`server.syncedState` adds a socket route, `/_hamur/synced` by default under `app.baseURL`, that keeps one JSON value per room and key and sends each change to every socket subscribed to it. Off, which is the default, the path answers `404`.

````ts [realtime/config.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "html",
  preset: "cloudflare",
  cloudflare: { websocket: "durable" },
  server: {
    pubsub: false,
    syncedState: { path: "/_hamur/synced", maxKeys: 10000, maxSubscriptions: 1000 },
  },
})
````

| Key                | Default            | Meaning                                                                                                                                                 |
| ------------------ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path`             | `"/_hamur/synced"` | the route, starting with `/`                                                                                                                            |
| `maxKeys`          | `10000`            | the most keys stored; a `set` of a new key past it answers `err` 413 `Synced state is full`. Nothing deletes a key, so it counts every key ever written |
| `maxSubscriptions` | `1000`             | the most subscriptions one socket holds; one more `sub` answers `err` 413 `A synced state socket holds at most 1000 subscriptions`                      |

`true` is the defaults. A value whose JSON is above 65536 bytes is not stored (`err` 413, `Synced value is above 65536 bytes`), `room` and `key` are non-empty strings of at most 256 characters (`err` 400 otherwise), and any other frame answers `err` 400 `Invalid synced state message`. A refused key answers `err` and the socket stays open for its other keys. A subscriber gets the current value first, then every change; a `set` goes to every subscriber, the writer included, so concurrent writers end on the value the server stored last.

The server hook `syncedState:access({ event, room, key, mode })` decides who reads (`"read"`, each `sub`) and writes (`"write"`, each `set`); `event` is the upgrade request's, so the context your middleware set is there. A throw refuses that key: the client gets `err` with the thrown `HamurError`'s status and message, any other throw is `403` `Forbidden`, and a refused `sub` also ends a subscription the socket held for that key. Without a listener every client may read and write every room, and the first socket logs `server.syncedState has no syncedState:access hook: every client may read and write every room`.

````ts [realtime/synced-access.ts]
import { createError, definePlugin } from "hamur/server"

export const access = definePlugin((server) => {
  server.hooks.hook("syncedState:access", ({ event, room, mode }) => {
    if (room.startsWith("user:") && room !== `user:${event.context.userId}`)
      throw createError({ status: 403, message: "Not your room" })
    if (room === "announcements" && mode === "write") throw createError({ status: 403 })
  })
})
````

On bun and node the values live in the memory of the process: a restart loses them and two instances keep two sets (`server.pubsub` does not carry them). On Cloudflare the route runs in the `hamur` object and keeps values and subscriptions in its storage, so they survive hibernation. A preset without sockets fails the build, and so does `cloudflare.websocket: "worker"`: `server.syncedState needs cloudflare.websocket: "durable": with "worker" each isolate would keep its own values`.

From a page, `useSyncedState(key, initial, { room? })` reads and writes a key through one socket per page, and the render shows `initial` with the shared value arriving after hydration. The core client is `syncedState` from `hamur/app`, with `get`, `set`, `subscribe`, `connected` and `error`; it reconnects after 1 s, doubling to 30 s.

````tsx [react/synced-counter.tsx]
import { useSyncedState } from "@hamur/adapter-react"

export default function SharedCounter() {
  const [count, setCount] = useSyncedState("count", 0, { room: "lobby" })
  return (
    <button type="button" onClick={() => setCount(count + 1)}>
      Everyone clicked {count} times
    </button>
  )
}
````

## From a page: `connectWebSocket`

`connectWebSocket(path, { protocols, reconnect })` from `hamur/app` opens a socket to `app.baseURL` plus `path` on the page's host, `wss:` on an `https:` page, and runs in the browser only. After a close the page did not ask for it reconnects after 500 ms, doubling to 30 s with a jitter of 20 %, and at once on `online`; a `send` while closed waits for the next `open`. `close()` ends it for good. On a route whose `websocket` object literal sets `schema`, the client sends `JSON.stringify(data)` and hands `message` callbacks the parsed value, and once `hamur typegen` ran, `send` and the callback are typed from the route and a path no socket route matches fails to compile.

````ts [realtime/client.ts]
import { connectWebSocket, syncedState } from "hamur/app"

export function openFeed(): () => void {
  const feed = connectWebSocket("/api/feed?token=abc", { protocols: "feed-v1", reconnect: true })
  feed.on("open", () => feed.send("hello"))
  feed.on("message", (data) => console.log(data))
  feed.on("close", (code, reason) => console.log("closed", code, reason, feed.status))
  return () => feed.close(1000, "done")
}

export function watchCount(): () => void {
  const count = syncedState("count", 0, { room: "lobby" })
  const stop = count.subscribe((value) => console.log("count is", value, count.connected, count.error))
  count.set(count.get() + 1)
  return stop
}
````
