Event Streams for API Clients
Sections Lines Four kinds of line The fields Dispatch, and when it does not happen Why API clients write their own parser

The event stream format

Server-sent events are specified in the HTML Living Standard, maintained by WHATWG. The format is deliberately small: a UTF-8 text body, served as text/event-stream, made of lines. Knowing the exact rules matters, because most streaming bugs come from a parser that handles the common case and nothing else.

Lines

A line ends at a carriage return followed by a line feed, at a lone line feed, or at a lone carriage return. All three are valid, and a stream may in theory mix them. A parser that only splits on \n leaves stray \r characters at the end of every value when a server uses CRLF, and never sees a line break at all from a server that uses CR alone.

The body is always decoded as UTF-8, whatever the Content-Type parameters say. A byte order mark at the very start of the stream is skipped.

Four kinds of line

Line looks likeWhat it does
emptyDispatches the event collected so far.
starts with :A comment. Ignored entirely; servers use these to keep a quiet connection active.
name: valueSets a field. One space after the colon is removed if present, and only one.
name with no colonSets the field name with an empty value.

Only four field names mean anything: event, data, id and retry. Any other field is ignored, which is what lets a format add fields later without breaking old clients.

: keep-alive event: update data: first line data: second line id: 17 (empty line) starts with a colon: a comment, ignored sets the event type two data lines are joined with a line feed between them remembered as the last event id dispatch the event The space after each colon is dropped, but only one space.
Anatomy of one event. Nothing is delivered until the empty line arrives.

The fields

Dispatch, and when it does not happen

An empty line ends an event. If the data buffer is empty at that point, nothing is dispatched: an event: line on its own, followed by a blank line, produces no event. And if the stream ends without a final empty line, the specification says the incomplete event is discarded. That second rule is the one that decides what a client sees when a connection breaks, and it is the subject of the chapter on early endings.

Why API clients write their own parser

Browsers parse event streams through the EventSource interface, which only issues GET requests and cannot send custom headers such as an API key. Model APIs take a POST with a JSON body and an authorization header, so clients read the response body with an ordinary HTTP library and parse the lines themselves. The next chapter builds such a parser.