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 like | What it does |
|---|---|
| empty | Dispatches the event collected so far. |
starts with : | A comment. Ignored entirely; servers use these to keep a quiet connection active. |
name: value | Sets a field. One space after the colon is removed if present, and only one. |
name with no colon | Sets 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.
The fields
- data: appended to the event's data buffer followed by a line feed. Several
datalines in one event therefore produce one payload with line breaks between the parts. The final line feed is removed when the event is dispatched. - event: sets the event type. If no
eventline appears, the type ismessage. - id: sets the last event id, which a browser sends back in a
Last-Event-IDheader when it reconnects. A value containing a NUL character is ignored. - retry: a reconnection delay in milliseconds, used by browsers. It is ignored unless the value is made of ASCII digits only.
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.