Server-Sent Events
import type {HttpRequest} from '@heronjs/common';
import {Request, Rest, SSE, type SseEvent} from '@heronjs/express';
import {setTimeout} from 'node:timers/promises';
@Rest('/events')
class EventsController {
@SSE({uri: '/status', heartbeatMs: 15000, maxBufferedBytes: 65536})
async *status(@Request() request: HttpRequest): AsyncIterable<SseEvent<{sequence: number}>> {
let sequence = 0;
while (!request.executionSignal.aborted) {
yield {event: 'status', data: {sequence: sequence++}};
await setTimeout(1000, undefined, {signal: request.executionSignal});
}
}
}Handlers may return an Observable, an AsyncIterable, or a promise resolving to either. Every event is emitted, unlike unary handlers. Guards and interceptors run before streaming. Events require data and may include event, id, and nonnegative integer retry. String data is split into SSE data lines; other data is serialized as JSON. Invalid event/id framing fields are rejected.
Responses set text/event-stream, Cache-Control: no-store, no-transform, and X-Accel-Buffering: no. Heartbeats default to 15 seconds; heartbeatMs: 0 disables them. The default output budget is 64 KiB, including heartbeats and individual frames. Async iterators pause at backpressure; push observables exceeding the budget are disconnected. Disconnect and application shutdown abort the request, unsubscribe, request iterator return, and clear heartbeats. Async sources must honor cancellation to interrupt pending external work.
Errors before headers use ordinary sanitized HTTP errors. Errors after headers close the stream and emit a reviewed operational log label. @SSE rejects cache/eviction and manual-response decorators at registration. IDs support client correlation; this implementation does not replay events or interpret Last-Event-ID as a resume request.
Browser EventSource cannot set a bearer authorization header. Use authenticated fetch and an SSE parser that handles partial UTF-8 chunks, multiline data, comments, and blank-line frame boundaries:
const controller = new AbortController();
const response = await fetch('/events/status', {headers: {Authorization: `Bearer ${accessToken}`}, signal: controller.signal});
if (!response.ok || !response.body) throw new Error('Stream unavailable');
// Feed response.body through your SSE parser; abort when leaving the page.