What you'll learn: By the end of this lesson you will be able to read a
text/event-streamresponse line by line, explain which rule turns lines into events, say what anEventSourcedoes when the connection breaks and which answers make it stop for good, useidandLast-Event-IDto resume without losing events, and name the limits (one direction, GET only, connection counts) that make you reach for something else.
Think of a numbered newsletter that arrives by one long delivery that never quite finishes. Each issue is a few lines, ended by a blank line, and has a number on top. If the delivery is interrupted, you phone and say "the last one I have is number 41". The publisher can answer only if it kept the recent issues. That is the whole mechanism: a response that does not end, a text format with a blank line between events, and a number you hand back to resume.
The running example is a merchant dashboard that shows live order counts for a shop. The numbers, timings and names in it are made up for the lesson. The server is only a model here; for the server side see WebSockets, SSE and Long Polling.
The core idea
- SSE is an ordinary HTTP response that stays open. The server answers
200with the media typetext/event-streamand keeps writing. The browser reads the body as it arrives. - The parsing rules, not the server, decide what an event is. Lines are fields, a blank line dispatches, and where the network cut the text does not matter.
- Recovery is a pair:
idout,Last-Event-IDback. It resumes exactly as far as the server kept events, no further.
Three illustrations run through the lesson: a minimal example (a three-event stream), a realistic example (the dashboard reconnecting after a drop) and a failure example (a client that was away longer than the server's replay window).
The wire format
The format is UTF-8 text in lines. A line ends with CRLF, LF or a lone CR. A line starting with a colon is a comment. Otherwise a line is field: value, where exactly one space after the colon is dropped.
| Field | What it does |
|---|---|
data |
Appends the value and a newline to the data buffer. Several data lines make a multi-line payload. |
event |
Sets the event type for the next event. Without it the type is message. |
id |
Sets the last event ID buffer. Ignored if the value contains a NUL character. |
retry |
Sets the reconnection time in milliseconds, but only if the value is digits only. |
| anything else | Ignored. Names are compared literally, so DATA is not data. |
A line with no colon is treated as a field name with an empty value. A blank line ends the event and dispatches it.
A minimal stream (illustrative):
retry: 2000
id: 41
event: price
data: 19.99
id: 42
data: first line
data: second line
The first block only sets the reconnection time. The second dispatches a price event with data 19.99. The third dispatches a message event with the two lines joined by a newline.
Figure 1. From server writes to page code
How to read this: the flow is one way, left to right. The only thing the client sends is the request that opens the stream, and a later one that reopens it.
How the parser decides
Figure 2. What happens to each line
field and value"] S --> F{"Field"} F -->|"data"| A["Append value and newline"] F -->|"event"| T["Set event type"] F -->|"id"| N["Set last event ID buffer"] F -->|"retry"| R["Set reconnection time if digits"] F -->|"other"| X["Ignore"]
How to read this: a line never does two things. State lives in a few buffers, and only the blank line turns the buffers into an event.
Three details trip up hand-written parsers, and the lab's tests pin each one:
- An empty data buffer does not dispatch. A block with only
event: pingor onlyid: 5produces no event. The standard still sets the last event ID string at that point, so an id-only block moves the resume point without waking any handler. - The id persists. An event with no
idfield still reports the previous last event ID. Anidfield with no value resets it to the empty string. - An unfinished event is lost. When the stream ends, anything not closed by a blank line is discarded. A server that dies mid-event costs the client that event, not a corrupt half.
Chunks do not matter. Network reads can end anywhere: inside a word, between the CR and the LF of a CRLF, after data:. The parser keeps its buffers between reads, and the lab's test cuts a stream at every position, and one character at a time, and gets identical events each time. If you decode bytes yourself, TextDecoder.decode takes a stream option, a flag saying "additional data will follow in subsequent calls", for processing data in chunks. A decoder that is not told this treats each chunk as complete.
EventSource: what the browser adds
new EventSource(url) opens the connection and runs the parser for you.
readyStateisCONNECTING(0),OPEN(1) orCLOSED(2).- Events without an
eventfield arrive asmessageevents. With one, you listen for that name withaddEventListener. openfires when the connection opens,errorwhen a connection failed to open or is lost.close()stops it. After that the object does nothing, and events still in flight are dropped.- The options in the sources read for this lesson hold one entry,
withCredentials, which controls whether cross-origin requests carry credentials. The request is a plain GET and the page cannot send data back on it. MDN says plainly: "This is a one-way connection, so you can't send events from a client to a server." A message from the page goes in a separate request.
Reconnection and Last-Event-ID
When an open stream ends, or a connection attempt fails, the browser goes back to CONNECTING, fires error, waits the reconnection time, and tries again. The standard calls the default "implementation-defined", probably a few seconds, and lets the client wait longer. A retry field from the server replaces it. If the last event ID string is not empty, the new request carries Last-Event-ID with that value.
Figure 3. The dashboard loses its connection and resumes
How to read this: the client never asks for "event 3". It says what it has, and the server decides what follows. That is why the server must number events and keep a window of them.
Failing for good. A reconnect is not unconditional. In the standard's processing model a status other than 200, or a media type other than text/event-stream, fails the connection, and a failed EventSource does not try again. The standard's introduction says a server can tell the client to stop with a 204 No Content. A network error, by contrast, triggers a reconnect. A server that wants clients to stop retrying (the endpoint is retired, the user's session ended) must answer one of those; an error that you want retried must be a dropped connection, not a 500. See HTTP Semantics for the Front End for what the statuses mean.
Figure 4. The states of an EventSource
How to read this: CLOSED has no way out. If the page wants a live feed again after a failure, it must create a new EventSource.
The limits
- One direction, GET only. Sending from the page uses a separate request. If you need a body, a header such as
Authorization, or a different method,EventSourcedoes not offer it in the sources read here, so you read the response yourself:fetchgivesresponse.bodyas aReadableStream, andread()returns{ value, done }chunks. You then own the parser, the decoding and the reconnection, which is what the lab's model shows. - Connection counts. MDN warns that without HTTP/2, SSE is limited by the number of open connections, a limit that is per browser and "a very low number (6)", which hurts with many tabs. Over HTTP/2 the number of simultaneous streams is negotiated and defaults to 100. The standard suggests a shared worker for pages that open many connections. See HTTP Protocols.
- Idle connections. Proxies may drop a silent connection. The standard suggests a comment line "every 15 seconds or so".
- Text only. The standard requires UTF-8, so binary data needs an encoding such as Base64, which costs size (a design consequence, not a rule of the standard).
Choosing
Figure 5. When SSE is the right transport
frequent messages?"} W -->|"yes"| WS["WebSocket"] W -->|"no"| H{"Need headers, a body
or a method other than GET?"} H -->|"no"| ES["EventSource"] H -->|"yes"| FS["fetch stream + your own parser"]
How to read this: SSE fits "server talks, page listens". The moment the page must talk a lot, or customise the request, pick another branch.
| Choice | Gain | Cost |
|---|---|---|
EventSource |
Parser, reconnect and resume built in | GET only, no custom headers, one direction |
| Fetch stream plus own parser | Any method, headers and body | You write parsing, decoding, reconnect and backoff |
Short window plus a resync signal |
Little server memory | The client must reload its state when told |
Build it: parse, reconnect, resume, and fall behind
Goal. Run a model of the event-stream parser, an EventSource, and a server with a bounded replay window through five situations.
Setup. The lab sse-event-stream is in the course's example workspace (Node 26.13.1). It is pure logic: no browser and no network, and a virtual clock replaces time.
cd examples/frontend
pnpm install
cd labs/sse-event-stream
pnpm test # 30 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In section 1, find the block
colour: bluefollowed by a linedata. The unknown field is ignored, and the baredataline makes an event with empty data. Theid: 42block produces no event but moves the last event ID. - In section 3, check the timing: no request at 1999 ms after the drop, one at 2000 ms, carrying
Last-Event-ID: 2. - In section 4, the server keeps only ids 6 to 8, so the client with last ID 4 gets a
resyncevent instead of a replay.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01):
=== 1. Parsing: what the standard's rules make of a few lines
the last block, data: never finished, is cut off before its blank line
event: price "19.99" lastEventId="41"
event: message "line one\nline two" lastEventId="41"
event: message "" lastEventId="41"
retry values accepted: [1500]
last event ID string at the end: "42" (set by an id-only block, no event for it)
=== 2. The same stream cut into chunks everywhere
CRLF version, 159 two-chunk splits: 159 give identical events
one character per chunk gives identical events: true
events found: 3
Expected output, captured from a real run (the rest of section 3 and all of section 4 of the same demo):
t= 0 request 1: GET /orders/42/events {"Accept":"text/event-stream","Cache-Control":"no-cache"}
t= 0 open
t= 0 reconnection time learned from the retry field: 2000 ms
t= 0 event message "packed" (last event ID 1)
t= 0 event message "out for delivery" (last event ID 2)
t= 500 the connection drops
t= 500 error: stream ended; will reconnect: true
t= 2499 1999 ms after the drop: 1 request so far
t= 2500 request 2: GET /orders/42/events {"Accept":"text/event-stream","Cache-Control":"no-cache","Last-Event-ID":"2"}
t= 2500 open
t= 2500 event message "arriving soon" (last event ID 3)
t= 2500 event message "delivered" (last event ID 4)
received in order, once each: ["packed","out for delivery","arriving soon","delivered"]
=== 4. Away too long: the replay window has moved on
t= 2500 the connection drops
t= 2500 error: stream ended; will reconnect: true
t= 2500 server keeps only ids 6, 7, 8; the client's last ID is "4"
t= 4500 request 3: GET /orders/42/events {"Accept":"text/event-stream","Cache-Control":"no-cache","Last-Event-ID":"4"}
t= 4500 open
t= 4500 event resync "replay window starts at 6" (last event ID 8)
t= 4500 closed: readyState 2
What the lab does not show. No real HTTP, proxies or buffering, and no byte decoding: the parser takes text. The 3000 ms default wait, the numbering from 1 and the resync event are this lab's design, not the standard's. The standard's processing model is followed in the order the lab implements it, but the lab was not compared with any browser.
Break it. In src/client.ts, change the condition before headers["Last-Event-ID"] so the header is never sent. Five client tests fail. Revert it.
In practice: a merchant dashboard that quietly fell behind
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A merchant dashboard shows today's order count and the newest five orders. A product manager wants it live. Updates are small, arrive a few times a minute, and only go from server to page. Merchants keep the dashboard open on an office screen for days, and laptops sleep overnight.
Starting architecture
Figure 6. Starting point: polling every 30 seconds
How to read this: every poll repeats the whole read. Updates reach the page up to one interval late.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Poll every few seconds | Nothing to build | Load grows with open dashboards | Still not live |
| WebSocket | Two-way, low latency | Own protocol for order, acks, reconnect | More than a one-way feed needs |
SSE with EventSource |
One-way push, built-in reconnect | GET only, replay window to run | Silent gaps after a long absence |
The decision
| Field | Decision record |
|---|---|
| Context | One-way updates a few times a minute to dashboards that stay open for days. |
| Decision | Use EventSource on one endpoint. Number every event, send id, keep the last N events, and send a named resync event when a client's last ID is older than the window. On resync, the dashboard reloads its state with one normal request. |
| Consequences, good | Live updates, no custom client protocol, resume after short drops. |
| Consequences, bad | The server keeps a replay log, and the client has two paths: apply events and reload state. |
| Revisit when | The page must send frequent messages (consider a WebSocket) or the stream needs custom headers (read a fetch stream). |
Rollout and verification
- Start with tests for chunk splits, id persistence,
204and500. - Ship behind a flag and compare the live count with the polled count for a week.
- Test the long absence on purpose: pause the dashboard longer than the replay window and confirm it reloads.
The 2 a.m. failure
Monday morning a merchant reports the dashboard shows Friday's order count. The laptop slept all weekend. On wake the browser reconnected with Last-Event-ID set to a Friday id that was long gone from the server's window. The server, written for the happy path, replayed nothing and sent only new events, so the page showed new orders added to an old total (illustrative).
First three checks: (1) compare the Last-Event-ID in the request with the oldest id the server holds; (2) check whether the server tells a client that its id is too old; (3) check whether the client has a code path for "reload everything". Mitigation: send a resync event when the id is older than the window, and have the page reload state on it. Follow-up: reload on visibilitychange after a long hidden period, count resync events in monitoring, and test the long absence in CI.
Architect's notes
- Number every event from the start. Without ids there is nothing to resume from.
- Decide the window and say it out loud. "Resume works for N events" is a product statement.
- Always give the client a way to start over. A signal plus a reload path beats silent drift.
- Pick the failure status on purpose. A
204or an error status stops the client; a dropped connection makes it retry.
Common mistakes
- Writing a parser that splits on
\n\n. It breaks on CRLF and lone CR, and on a chunk that ends mid-line. - Treating
idas optional. The reconnect then replays nothing. - Returning
500to make clients back off. A failedEventSourcenever retries. - Putting long-lived secrets in the query string to work around the missing headers. URLs are often logged.
Key takeaways
- SSE is an open HTTP response in
text/event-stream, UTF-8, read line by line. - A blank line dispatches; empty data does not;
idpersists; unfinished events are discarded. - Where the network splits the text must never change the events.
EventSourcereconnects after the reconnection time, sendsLast-Event-IDwhen it has one, and stops for good on a non-200 answer, a wrong media type orclose().- It is one-way and GET only; for headers or a body, read a fetch stream and write your own parser.
- Resume is only as good as the server's replay window; design the "too old" answer.
Practice exercises
Exercise 1, Starter (45 min): Write five streams by hand (CRLF line ends, a comment, a two-line data, a bad retry, an id with no data) and predict the events.
Exercise 2, Intermediate (2 hours): Add backoff to the lab's client: double the wait after each failed attempt up to a cap, and reset it after a stream delivers an event. Write tests with the virtual clock.
Exercise 3, Advanced (half day): Write a fetch-based reader that feeds a TextDecoder (with stream: true) into the parser, and make it send a custom header. List what you now own that EventSource owned before.
Related reading
In this course:
- WebSockets, SSE and Long Polling, the server side of the same feeds and the three transports compared.
- HTTP Semantics for the Front End, the status codes and media types that decide whether a stream opens.
- HTTP Protocols, HTTP/1.1 and HTTP/2 connection limits.
- Error, Loading and Empty States, what the dashboard shows while it is
CONNECTING.
Planned lessons in this module, named here as plain text: Polling, SSE and WebSockets compares the transports; Reconnection and Message Ordering goes further on resuming and ordering.
Official documentation
- WHATWG HTML: Server-sent events, the grammar, parsing and dispatch steps, and the
EventSourcemodel. - MDN: Using server-sent events and EventSource.
- MDN: Using readable streams, reading a
fetchbody as a stream. - MDN: TextDecoder.decode(), the
streamoption for chunked input.