Interactive Learning Platform Nuxt layer

Isolated learning atmosphere · v4.x

← Back to writing
Step 7 of 9SSE + defineWebSocketHandler

Live: SSE for the Board, WebSocket for the Radio

Stream the depot snapshot with createEventStream, add a WebSocket ops radio with peer.subscribe/publish, and learn why the read path and the write path use different realtime tools.

A depot board that needs a refresh is a dashboard. A depot board that updates itself is a control room. Stage 7 adds two realtime transports: SSE for the board, WebSocket for the people running it.

ampyard / preview / 7
Live stage Open app ↗
Ampyard · live stageStage 7 / 9

What it is#

Two different problems:

  1. The board is a one-way feed. The server knows something changed; every reader should see it. That is Server-Sent Events.
  2. The radio is a conversation. Operators join, talk to everyone, and leave. That is WebSocket with pub/sub.

Nitro supports both. SSE is a plain HTTP response with content-type: text/event-stream. WebSocket is a route with defineWebSocketHandler and features.websocket: true.

Why you'd care#

It is tempting to use WebSockets for everything. Do not. Each transport has a cost:

  • SSE auto-reconnects, works through proxies, needs no extra binding, and is easy to reason about on serverless. It is one-way, which is exactly what a board needs.
  • WebSocket is bidirectional and supports topics, presence, and fan-out. It needs a persistent connection and, on Cloudflare, a Durable Object for pub/sub across connections.

Ampyard uses both because the app has both shapes. The board is read-only. The radio is not.

What we're building#

  • GET /api/stream: an SSE stream that pushes a snapshot when it changes and a ping when it does not.
  • /ws/ops: a WebSocket route with an ops topic.
  • useLiveDepot: an EventSource composable that replaces the snapshot in place.
  • OpsRadio: a small chat UI for the ops page.

Before#

Stage 6's board refreshes when the reader clicks Refresh, or when the page reloads. The simulator moves the depot, but the browser does not know.

After#

The SSE route creates a stream, pushes a snapshot, and keeps pushing on a timer:

server/api/stream.get.ts
import { defineHandler } from "nitro";
import { createEventStream } from "nitro/h3";
import { readSnapshot } from "../utils/depot";

export default defineHandler(async (event) => {
  const stream = createEventStream(event);
  let last = "";
  let closed = false;

  async function push() {
    if (closed) return;
    const snapshot = await readSnapshot(10_000);
    const data = JSON.stringify(snapshot);

    if (data === last) {
      await stream.push({ event: "ping", data: String(Date.now()) });
      return;
    }

    last = data;
    await stream.push({ event: "snapshot", data, id: String(Date.now()) });
  }

  const timer = setInterval(push, 30_000);
  const first = setTimeout(push, 50);

  stream.onClosed(() => {
    closed = true;
    clearInterval(timer);
    clearTimeout(first);
  });

  return stream.send();
});

Two details matter:

  • Do not await push() before stream.send(). The stream is not open until send() returns. Schedule the first push just after it.
  • Thirty seconds, not four. Every SSE connection calls readSnapshot, which reads the state store (D1 by default). Four seconds per reader is 900 snapshots an hour; thirty is 120. The helper keeps a ten-second in-memory snapshot so several connections in one isolate share a build. The board still feels live because charging progress is derived from startedAt.
  • Clear the interval in onClosed. A stream that outlives its reader is a leak.

The client subscribes with the browser's EventSource:

app/composables/useLiveDepot.ts
source = new EventSource("/api/stream");
source.addEventListener("open", () => {
  connected.value = true;
  transport.value = "sse";
});
source.addEventListener("snapshot", (event) => {
  snapshot.value = JSON.parse((event as MessageEvent<string>).data);
  connected.value = true;
});
source.addEventListener("error", () => {
  connected.value = false;
  transport.value = "error";
});

EventSource reconnects on its own. The composable only tracks the state; it does not need a retry loop.

The WebSocket route is smaller:

server/routes/ws/ops.ts
import { defineWebSocketHandler } from "nitro";

export default defineWebSocketHandler({
  open(peer) {
    peer.subscribe("ops");
    peer.send({ type: "system", text: `Radio open. You are operator ${peer.id.slice(0, 4)}.` });
    peer.publish("ops", { type: "system", text: `Operator ${peer.id.slice(0, 4)} joined.` });
  },
  message(peer, message) {
    const text = message.text().trim().slice(0, 240);
    if (!text) return;

    const payload = { type: "note", from: peer.id.slice(0, 4), text };
    peer.publish("ops", payload);
    peer.send({ ...payload, from: "you" });
  },
  close(peer) {
    peer.publish("ops", { type: "system", text: `Operator ${peer.id.slice(0, 4)} left.` });
  },
});

peer.publish excludes the publishing peer. That is why the handler also sends the note back to the sender, with from: "you".

Enable the transport in config:

nitro.config.ts
features: {
  websocket: true,
},

On Cloudflare, declare the Durable Object binding so pub/sub is shared across connections:

json
{
  "durable_objects": {
    "bindings": [{ "name": "$DurableObject", "class_name": "$DurableObject" }]
  },
  "exports": {
    "$DurableObject": { "type": "durable-object", "storage": "sqlite" }
  }
}

Nitro generates this from cloudflare.wrangler in nitro.config.ts. Without the binding, each Worker connection is isolated; peer.publish has no one to talk to.

Do it yourself#

Start the app and open /preview/7 in two tabs:

bash
pnpm --filter ampyard dev
  1. Watch the SSE live badge in the board header.
  2. Click Advance depot clock in one tab. The other tab should update without a refresh.
  3. Open /ops in two tabs.
  4. Send a message from one radio. It appears in the other.
  5. Close one tab. The other receives a system message.

You can also inspect the stream directly:

bash
curl -N http://localhost:4321/api/stream

The first frame is a snapshot; later frames are ping or snapshot when the depot changes.

The live stage#

The preview above is /preview/7. The board now shows an SSE live badge and updates in place. The ops page at /ops includes the WebSocket radio. Stage 6 still shows the static board; the old stage does not receive the stream.

Gotchas#

  • SSE is not a database. The stream polls the snapshot builder. Every connection is a set of D1 reads, so the cadence is a budget: thirty seconds per reader, not four. Cache the snapshot for normal readers and keep the stream slower than the HTTP route.
  • Cloudflare Workers are not long-lived servers. A streaming response can run for a while, but it has CPU and duration limits. Keep the work per tick small.
  • WebSocket pub/sub needs the Durable Object on Cloudflare. Without it, peers are isolated. This is the most common "why does it work locally but not in production?" bug in this stage.
  • peer.publish is not a server-wide broadcast. It publishes to the topic within the namespace, and it excludes the sender. Use peer.send for the echo.
  • You cannot publish from an HTTP route with peer. If a cron or a webhook needs to broadcast, you need a different bridge: a Durable Object RPC, a queue, or a poll. Keep the write path inside the WebSocket handler if you can.
  • SSE reconnects. The browser will reconnect after a dropped connection, but your first frame should be a full snapshot, not a diff. The client has no state to patch.
  • Backpressure is real. On Node's ws, check peer.bufferedAmount before a fast send loop. On Cloudflare, the runtime buffers for you, but the CPU still costs.

Recap#

Ampyard is live: SSE streams the board, WebSocket carries the ops radio, and both rides on the same Nitro app. Stage 8 turns the charger routes into a contract and adds tests.

Next: The Charger Contract.