HTML Server-Sent Events (SSE)
HTML Server-Sent Events (SSE)
Server-Sent Events let a server push a continuous stream of updates to a web page over a single, long-lived HTTP connection — without the browser needing to repeatedly poll or ask for new data. It's a simpler, one-way alternative to WebSockets, ideal whenever data only needs to flow from server to client.
How SSE Differs from WebSockets
- SSE — one-way only (server → client), built on plain HTTP, automatically reconnects, and text-based (UTF-8) only.
- WebSockets — two-way (client <-> server), needs its own protocol upgrade, and supports both text and binary data.
If your app only needs to receive live updates (stock tickers, notifications, live scores, progress bars) rather than send data back over the same channel, SSE is usually the simpler and lighter option.
The EventSource Interface
On the client side, SSE is consumed through the built-in EventSource object. Creating one and pointing it at a server endpoint automatically opens a persistent connection and starts listening for incoming messages.
The Server Side
The server must respond with the Content-Type: text/event-stream header and keep the connection open, sending each update as a block of text starting with data: and ending with two newlines.
Handling Events
The default message event fires for standard updates, but a server can also send named custom events, which the client listens for using addEventListener('eventName', ...) instead of the generic onmessage.
Automatic Reconnection
One of SSE's biggest advantages is that the browser automatically attempts to reconnect if the connection drops, without any extra code needed — the server can also send a numeric id: field with each event so the browser can tell the server where to resume from after reconnecting.
Common Use Cases
Live notifications, stock or crypto price tickers, sports score updates, live dashboards, and progress indicators for long-running server tasks are all classic Server-Sent Events use cases.
Press Run to execute.
Press Run to execute.
Create an EventSource connected to '/notifications', and add a listener for a custom event named 'newMessage' that parses the JSON payload and logs the message text.
Press Run to execute.
Show expected output
source.addEventListener('newMessage', (event) => { const data = JSON.parse(event.data); console.log(data.text); });This is a self-check — compare your result with the expected output above.
Was this page helpful?