Video in progress
What is Server-Sent Events (SSE) and how does it work?
SSE is a standard where the server sends a stream of events to the client inside a normal HTTP response, without closing the connection. It is one-way only: server to client. The browser has the EventSource API for it.
📖 Answer
The server responds with Content-Type: text/event-stream and doesn't close the response. Each event is a few lines of text ending with a blank line:
id: 17
event: order-status
data: {"orderId":42,"status":"SHIPPED"}
On the client side:
const es = new EventSource('/api/orders/stream');
es.addEventListener('order-status', e => {
const msg = JSON.parse(e.data);
console.log(msg.status);
});
The nice thing about SSE is that it's plain HTTP. There's no separate protocol, and proxies, HTTP/2 and cookies work as usual. If the connection drops, EventSource reconnects on its own.
Limits: text only (no binary), and the client can't write to the server over this channel; it sends a regular POST request for that. For notifications, progress bars and live logs, this is all you need.
Sign up to mark studied questions and save your progress.