Server-Sent Events Fundamentals
You'll learn: How Server-Sent Events (SSE) enable servers to push updates to browsers automatically over a simple HTTP connection.
What Are Server-Sent Events?
Server-Sent Events provide a one-way communication channel from server to client over standard HTTP. Unlike traditional request-response patterns where the browser must constantly ask "any updates?", SSE lets the server send data whenever it's ready—the browser just listens.
Think of it like subscribing to a news alert service: you sign up once, then updates arrive automatically without you repeatedly checking your inbox.
How SSE Works
When you open an SSE connection, the browser makes a single HTTP GET request to a special endpoint. The server keeps this connection open and sends updates as text messages whenever it has new data. The connection stays alive, streaming data over time.
const eventSource = new EventSource('/api/updates');
eventSource.onmessage = (event) => {
console.log('New data:', event.data);
};
Automatic Reconnection
One of SSE's killer features is built-in resilience. If the connection drops (network hiccup, server restart), the browser automatically reconnects after a few seconds—no extra code needed. The server can even tell the browser how long to wait before reconnecting.
This makes SSE perfect for live dashboards, notifications, stock tickers, or any scenario where the server needs to push updates but clients don't need to send much data back.
One-Way Only
Remember: SSE is server-to-client only. The client can't send messages through the SSE connection (though it can still make separate fetch requests). For two-way communication, you'd need WebSockets instead.
Key Takeaway: Server-Sent Events provide automatic, one-way streaming from server to browser over HTTP with built-in reconnection, making real-time updates simple without constant polling.