Server-sent events
Push live updates to browsers with ctx.sse and SseWriter without managing the event-stream wire format yourself.
AI generated, pending review
You want to push live updates to a browser over a long-lived HTTP connection. Call ctx.sse(producer) on FlareHttpContext. Flare returns a FlareResponse with Content-Type: text/event-stream and runs your producer with an SseWriter.
Basic tick loop
Section titled “Basic tick loop”import { FlareHost } from "@flare-ts/core";import { node } from "@flare-ts/core/node";
function delay(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms));}
const host = new FlareHost(node);
host.http.get("/events", (ctx) => { return ctx.sse(async (sse, signal) => { while (!signal.aborted) { await sse.send({ event: "tick", data: { now: Date.now() } }); await delay(1000); } });});
const app = host.build();app.run();The signal argument is the request’s AbortSignal. Stop the loop when the client disconnects.
SseWriter API
Section titled “SseWriter API”| Method | Purpose |
|---|---|
sse.send(event) | Send one event frame (required data; optional event, id, retry) |
sse.comment(text) | Send a comment frame (keep-alive; clients ignore) |
send and comment return promises that resolve when the transport has pulled the frame, so awaiting each call paces the producer (at most one frame buffered).
From a controller
Section titled “From a controller”import { ControllerBase, FlareHost } from "@flare-ts/core";import { Get } from "@flare-ts/core/decorators";import { node } from "@flare-ts/core/node";
class EventsController extends ControllerBase { public static override deps = []; public static override state = [];
@Get("") stream() { return this.ctx.sse(async (sse, signal) => { await sse.send({ data: { hello: "world" } }); await sse.comment("keep-alive"); while (!signal.aborted) { await sse.send({ event: "ping", data: {} }); await new Promise((r) => setTimeout(r, 5000)); } }); }}
const host = new FlareHost(node);host.http.controller("/events", EventsController);
const app = host.build();app.run();- SSE is a response mechanism. You still register a normal GET route.
- The stream ends when the producer settles or the request aborts.
- For generic byte streaming (not the SSE wire format), see Streaming bodies.
Related
Section titled “Related”- Requests:
ctx.sseonFlareHttpContext - API: SseWriter