SSE Streams
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
SSE routes open a persistent HTTP connection and push a sequence of named events to the client on a configurable interval. No extra dependencies — yRest uses Node.js native streams and Fastify’s raw reply API.
Declaring an SSE route
Section titled “Declaring an SSE route”The _sse block
Section titled “The _sse block”Event structure
Section titled “Event structure”Looping and repeat
Section titled “Looping and repeat”Interval
Section titled “Interval”Template variables per frame
Section titled “Template variables per frame”Keep-alive
Section titled “Keep-alive”Wire format
Section titled “Wire format”Handler-driven streams
Section titled “Handler-driven streams”When a stream depends on state — a chat, a job queue, notifications triggered by other requests — replace _events with _handler and let a function drive the stream:
_routes: - _method: SSE _path: /events/chat _sse: _handler: chatStreamimport { defineSseHandler } from "@yrest/cli";
export const chatStream = defineSseHandler((req, raw, { collection }) => { for (const message of collection("messages").findAll()) { raw.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); } raw.end();});The handler receives (req, raw, ctx): the request, the Node.js ServerResponse and the same ctx.collection() access as handler functions. yRest sends the SSE headers and the keep-alive comments; the handler writes frames and calls raw.end() when it is done. _interval, _loop, _repeat and _events are not used.
A handler missing from the handlers file answers 501 before the stream opens. One that throws sends an event: error frame and the stream is closed. See SSE handler streams for a full chat example.
Examples
Section titled “Examples”Next steps
Section titled “Next steps”- Template Variables —
{{now}}and{{uuid}}are especially useful in SSE data - Handler Functions — handler-based SSE for fully dynamic streams (Phase 12B)
- WebSocket — bidirectional mock channels (coming soon)