Streams
Server-sent events and JSON lines, typed and checked event by event like any other response.
A route can stream its response: as server-sent events, which a browser reads
with EventSource, or as JSON lines (NDJSON), one JSON value per line. The
contract declares what each event or line holds, and the handler sends them
with respond.sse or respond.ndjson. The route's auth, validation and
docs work as they do for any other route.
Server-sent events
Declare the response's events: each event's name, and the schema of its
data. The response is a text/event-stream.
changes: contract({
operation: 'changes',
method: 'get',
path: '/changes',
summary: 'Follow changes to todos',
auth: { scopes: ['todos.read'] },
responses: {
200: {
description: 'Changes to todos, as server-sent events.',
events: { created: todoSchema, updated: todoSchema, deleted: todoDeletedSchema },
},
},
}),The handler passes respond.sse a producer, which sends events until it
returns or the client disconnects:
import { defineHandler } from 'hono-bento';
import { ownerScope } from '../../access';
import type { Session } from '../../auth';
import type { contracts } from './spec';
export const followChanges = defineHandler<Session, typeof contracts.changes>(({ deps, identity, respond }) =>
respond.sse(
200,
(stream) =>
new Promise<void>((resolve) => {
const unsubscribe = deps.todoChanges.subscribe(ownerScope(identity), (change) => {
stream.send(change.type, change.todo).catch(() => {});
});
stream.signal.addEventListener('abort', () => {
unsubscribe();
resolve();
});
})
)
);stream.send(event, data, { id?, retry? }) takes only the events the status
declares, each with its own data type, and sends the data as JSON. An event
named message is the one EventSource.onmessage receives; listen for the
others with addEventListener(name, ...). A reconnecting client sends the last
id it got as the Last-Event-ID header, which the handler can read from
context.req.header('last-event-id').
respond.sse also sends a comment every 15 seconds, so proxies don't close
an idle stream. Pass { keepAlive: false }, or another interval in
milliseconds, as its third argument.
JSON lines
Declare the response's items: the schema of each line. The response is
application/x-ndjson, or the JSON lines type given as content, such as
application/jsonl.
responses: { 200: { description: 'Every todo, one per line.', items: todoSchema } },respond.ndjson sends each value of an array, a generator or an async
generator, or what a producer writes with stream.write(line):
return respond.ndjson(200, store.iterate(deps.db, ownerScope(identity)));When the client disconnects
The stream ends, stream.signal aborts, and from then on send, write and
sleep reject. A loop of them therefore ends by itself, and a generator's
finally runs. Clean up (unsubscribe, release a connection) when signal
aborts or in a finally.
A generator that waits for something else, such as the next message from a
queue, only notices when it next yields. Use a producer that listens to
signal instead.
Errors in a stream
An error the handler throws before it calls respond.sse or respond.ndjson
is an ordinary error response. Once the stream has started, the status has been
sent, so an error can only go in the stream. It's sent in the
usual error shape, after mapError and onError
and logged like any other, and then the stream ends:
- an SSE stream sends it as an
errorevent, soerrorcan't be one of the route's own event names; - a JSON lines stream sends it as its last line.
event: error
data: {"status":404,"error":{"type":"not_found","message":"The todo went away."}}Checks
- At startup, the router rejects a response that declares more than one
of
schema,eventsanditems; acontentthat isn't a stream type; atext/event-streamor JSON linescontentwithouteventsoritems; and an event name with a line break, or namederror. - In the handler's types,
respond.sseandrespond.ndjsononly accept statuses documented as streams, andrespond(status, data)doesn't. - With
validateResponses, each event and line is checked against its schema as it's sent. One that doesn't match ends the stream with a500error event and a logged message naming the event. fuzzSpecschecks a stream's status and headers, and doesn't wait for a stream that never ends.
A HEAD request gets the headers without running the producer.
Documentation
The OpenAPI document describes a stream item by item,
with itemSchema: each event as { event, data, id?, retry? }, or each line,
plus the error event or line. itemSchema is part of OpenAPI 3.2, so generate
a 3.2 document for an API with streams:
export const openApiOptions: GenerateOpenApiOptions = {
openapi: '3.2.0',
// ...
};