Real-Time Updates with Server-Sent Events (SSE)
A lightweight one-way channel for live data over plain HTTP
text/event-stream that simply never finishes. For dashboards, notifications, price tickers and progress bars -- anything where data flows server -> client and rarely the other way -- SSE is often simpler and more robust than a full WebSocket. You have already met WebSockets in this course; this lesson gives you the lighter tool for the many one-way cases.
- explain how SSE streams events over one keep-alive HTTP response;
- write the
text/event-streamwire format --id,event,data,retryand comments; - consume a stream in the browser with
EventSourceand named events; - use automatic reconnection and
Last-Event-IDto resume without gaps; - keep connections alive with heartbeats and defeat proxy buffering;
- decide honestly when SSE is the right tool and when WebSockets are.
1. What SSE is, and why it exists
The classic way to get fresh data from a server is polling: the client asks "anything new?" every few seconds. Polling wastes requests when nothing changed and still adds latency when something does. SSE inverts this. The client opens the connection once, and the server keeps that response open and writes new events into it whenever they occur. The browser exposes this through a tiny built-in API called EventSource.
Because the transport is just HTTP, SSE inherits everything HTTP already gives you: it works over the same port as your web app, passes through firewalls and proxies that allow normal web traffic, and is trivial to secure with TLS and cookies. There is no separate protocol to open in your infrastructure.
Analogy. Polling is like phoning the train station every minute to ask if your train is late. SSE is a radio broadcast: you tune in once, and announcements arrive as they happen. You do not talk back on the radio -- and for departures you do not need to. That one-way shape is exactly what SSE is built for.
SSE is a browser standard (part of HTML), so the client side is not something you invent -- the reconnection, the event parsing, and the Last-Event-ID handling are all done for you by EventSource. Your job on the server is only to speak the simple wire format correctly.