A loudspeaker runs from the washing room to the front counter. Eko announces every change with a number: "Number 41: twelve, ironing." The people at the front can only listen. They cannot answer through that loudspeaker. If its cable falls out, it is plugged in again a few seconds later. Then Mrs. Rini says "the last one I heard was number 41", so Eko repeats every announcement after number 41.
Server-Sent Events (SSE) works just like that loudspeaker. The loudspeaker is one HTTP response that never finishes: the server (Eko) keeps writing news into it as lines of text. In the browser (the front counter), EventSource reads each piece of news as an event. EventSource is the browser's built-in tool for SSE. SSE also has the numbers and Mrs. Rini's request to repeat: the Last-Event-ID part below covers them.
The text/event-stream format
The server answers with the header Content-Type: text/event-stream (Content-Type names the kind of content in the response). Then the server writes event after event without closing the response:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Access-Control-Allow-Origin: http://localhost:8000
: Mrs. Rini's Laundry board
event: status
data: {"id":12,"status":"Ironing"}
id: 41
| Line | Meaning |
|---|---|
data: ... |
the event's content. Several data: lines in a row are joined with a newline (\n) |
event: status |
the event's name. Without this line it is called message |
id: 41 |
the event's number. The browser remembers it as the Last-Event-ID |
retry: 2000 |
the reconnect delay the server asks for, in milliseconds |
: text |
a comment the browser ignores. Used as a heartbeat (a small regular message) so the connection never looks idle |
| an empty line | the event is complete: the browser passes it to your code now |
One space after the colon is dropped, and unknown fields (the name before the colon) are ignored. The content is always UTF-8 text. The status event above is 57 bytes. Over HTTP/1.1, a response that is not finished is sent in chunks, and each chunk starts with a length marker, so that event is sent as 63 bytes. If the server answers with another Content-Type, application/json for example, EventSource stops right away. Tested in Chromium, Firefox and Safari: only one request, and no reconnect.
The server: Node.js with no library
This server uses only the built-in module node:http. The responses that are still open are kept in screens, and recent events in recent:
import http from 'node:http'
const screens = new Set() // responses still open
const recent = [] // recent events, to send again
let eventId = 40
http.createServer((req, res) => {
if (req.url !== '/board/stream') return res.writeHead(404).end()
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': 'http://localhost:8000',
})
const lastSeen = req.headers['last-event-id']
if (lastSeen) for (const e of recent) if (e.id > Number(lastSeen)) res.write(e.text)
screens.add(res)
req.on('close', () => screens.delete(res))
}).listen(3000)
// Called when Eko changes a status
function sendStatus(id, status) {
eventId++
const text = `event: status\ndata: ${JSON.stringify({ id, status })}\nid: ${eventId}\n\n`
recent.push({ id: eventId, text })
if (recent.length > 100) recent.shift()
for (const res of screens) res.write(text)
}
setInterval(() => {
for (const res of screens) res.write(': ping\n\n') // heartbeat
}, 25000)
res.write(...)with nores.end(): the response is left open.- The
\n\nat the end of each event is the empty line that makes the browser pass the event to your code. recentkeeps the last 100 events. When a request carries aLast-Event-IDheader (kept inlastSeen), the events with a higher number are sent again. The Last-Event-ID part below covers this.- A
: pingcomment every 25 seconds is the heartbeat. Proxies that cut quiet connections (nginx: after 60 seconds) see that the connection is still "talking". - Node sends the headers only with the first
res.write. So in this code, the browser gets the headers only when the first event or ping arrives, which can be 25 seconds later.onopen(the function that runs when the connection opens) also runs only then. The fix: addres.flushHeaders()right afterres.writeHead(...), or writeres.write('retry: 3000\n\n')right away. Tested on Node 24: with neither, no headers had arrived after 3 seconds. Withres.flushHeaders(), they arrived in 12 ms.
EventSource in the browser
In the browser, the board opens the connection with new EventSource(...), then adds a listener for the status event:
const source = new EventSource('http://localhost:3000/board/stream')
source.addEventListener('status', (event) => {
const { id, status } = JSON.parse(event.data)
document.querySelector(`#status-${id}`).textContent = status
console.log('event number', event.lastEventId) // "41"
})
source.onopen = () => console.log('connected')
source.onerror = () => console.log('dropped, readyState', source.readyState)
- An event that has a name (
event: status) only arrives throughaddEventListener('status', ...).onmessageonly receives events without anevent:line. readyState: 0 CONNECTING (also while reconnecting), 1 OPEN, 2 CLOSED.source.close()closes the connection for good, with no reconnect.
For one-way push, SSE is simpler than WebSocket. SSE is plain HTTP, so it needs no special protocol or library. EventSource is built into the browser, and it reconnects automatically.
Dropping and reconnecting: Last-Event-ID
Guess first: the SSE connection of Mrs. Rini's board drops for a few seconds, and while it is down Eko moves #13 to Ready for pickup. Once it reconnects, does the board know about #13?
When the connection drops, EventSource reconnects by itself. The new request carries a Last-Event-ID header with the number of the last event the browser received. This is what happened, step by step, in a test in Chromium 147:
| Time | What happens |
|---|---|
| 0 s | the board receives event 41: #12 Ironing |
| 1 s | a proxy cuts the connection. An error event, readyState 0 |
| 2 s | Eko moves #13 to Ready for pickup. The server keeps event 42 in recent |
| 4 s | the browser reconnects (3 seconds after the drop) with the header Last-Event-ID: 41 |
| 4 s | the server sends event 42 again, and the board shows #13 Ready for pickup |
So the board knows, as long as the server does two things: it writes id: in each event, and it sends again the events after the Last-Event-ID. Without id:, the browser sends no Last-Event-ID. Then the server cannot tell what was missed, and #13 stays wrong until the next update.
The reconnect delay was measured: Chromium 147 and Safari (WebKit 26.4) wait 3 seconds, Firefox 146 waits 5 seconds. A retry: 2000 line from the server makes it about 2 seconds in all three. To stop the reconnecting, the server answers the next request with 204 No Content. EventSource then stops at readyState 2.
What EventSource cannot do
- Your own headers.
new EventSource(url, options)knows only one option,withCredentials. So there is noAuthorization: Bearer ..., the header that usually carries a login token. Use a cookie, or a short-lived token in the query (the part of the address after the question mark). Remember that the URL, token included, is written to the server's logs. If the server only accepts the token in a header, usefetchand readresponse.bodypiece by piece. But then you write the reading of the format (the parsing) and the reconnecting yourself. - POST or a body. EventSource always uses GET. To send a status from Eko's tablet, use an ordinary
fetch. - Two ways, or binary. It only goes from the server to the browser, and it carries only text. Binary data has to be turned into base64 first.
- CORS without permission. The board is on
localhost:8000, the stream onlocalhost:3000. A different port means a different origin (the protocol, the server name and the port). CORS is the browser's rule for requests to another origin: the server has to give permission through a header. WithoutAccess-Control-Allow-Origin, the connection fails and is not retried. Withnew EventSource(url, { withCredentials: true }), cookies are sent. But the server must name the origin exactly (not*, the sign for every origin) and addAccess-Control-Allow-Credentials: true. Tested in all three browsers:*fails when cookies are sent.
⚠️ Why didn't the event arrive?
- Forgetting the empty line. Without
\n\n, the browser keeps waiting and the event never arrives. onmessagefor named events. A stream that writesevent: statusnever triggersonmessage.- Not writing
id:. Changes made while the connection was down are simply lost. - A proxy that buffers or compresses. Events arrive in bunches. Send an
X-Accel-Buffering: noheader for nginx, do not compress the stream with gzip, and send heartbeat comments.
TL;DR: SSE (Server-Sent Events) is one HTTP response that stays open, with the header Content-Type: text/event-stream. In it, the server writes news for the browser. Each event is data: lines (its content; several are joined with \n), and it may also have event: (its name; without it the name is message), id: (its number) and retry: (the reconnect delay). An empty line closes the event. A line starting with : is a comment, used as a heartbeat (a small regular message so the connection never looks idle). EventSource, the browser's built-in tool for SSE, receives named events through addEventListener. EventSource reconnects by itself (3 seconds in Chromium and Safari, 5 seconds in Firefox, or whatever retry: says), and sends Last-Event-ID (the last id: it received) so the server can send again the events that were missed. The server can stop the reconnecting with a 204 answer. EventSource cannot set its own headers, cannot POST, and goes one way with text only. To another origin (a different protocol, server name or port), EventSource needs CORS permission. With withCredentials (cookies sent along), the server must name the origin exactly. For one-way push, SSE is simpler than WebSocket: plain HTTP, a built-in API, automatic reconnecting.
⚡ One event, closed by an empty line
Write:
event: status
data: {"id":12,"status":"Ironing"}
id: 41
Meaning: With SSE (Server-Sent Events), the server answers with the header Content-Type: text/event-stream, then keeps writing events without closing the response. One event is a few lines: event: its name, data: its content, id: its number. The empty line at the end marks the event as complete, and only then does the browser pass it to your code. Without \n\n (that empty line), the browser keeps waiting.
⚡ A named event needs addEventListener
Write:
const source = new EventSource('http://localhost:3000/board/stream')
source.addEventListener('status', (event) => {
const { id, status } = JSON.parse(event.data)
document.querySelector(`#status-${id}`).textContent = status
})
Meaning: EventSource, the browser's built-in tool for SSE, opens an SSE connection to the server. A named event (event: status) only arrives through addEventListener('status', ...). onmessage, another way to receive events, only receives events without an event: line.
⚡ A short drop: Last-Event-ID
Guess first: the SSE connection of Mrs. Rini's order board drops for a few seconds. While it is down, Eko, who works at her laundry, moves order #13 to Ready for pickup. Once it reconnects, does the board know about #13?
It knows, as long as the server writes id: (the event's number). EventSource reconnects by itself with the header Last-Event-ID: 41, the number of the last event it received, and the server sends event 42 (the change to #13) again.
Meaning: Without id:, the browser sends no Last-Event-ID, so changes made while the connection was down are simply lost.
⚡ Simpler than WebSocket
Meaning: For one-way push, from the server to the browser, SSE is plain HTTP: it needs no special protocol or library. EventSource is built into the browser, and reconnecting (connecting again after a drop) is automatic. The price: EventSource cannot set its own headers, cannot POST, and carries only text.