In this lesson, you will learn how to use Server-Sent Events (SSE) to create a lightweight, HTTP-based conduit for streaming real-time updates from your server to the client.
While WebSockets are powerful, they can be overkill for read-heavy feeds like stock tickers, live news updates, or server monitoring logs. SSE provides a simpler, uni-directional alternative that operates entirely over standard HTTP. Because it is just a long-lived HTTP request, it plays nicely with existing load balancers and firewalls without requiring complex handshake protocols.
Implementing an SSE Stream in Node.js
To set up an SSE endpoint, you simply need to set the Content-Type header to text/event-stream and keep the response object open. Here is a minimal implementation:
app.get('/live-updates', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Send a periodic update to the client
const interval = setInterval(() => {
const data = JSON.stringify({ timestamp: new Date().toISOString() });
res.write(`data: ${data}\n\n`);
}, 3000);
// Clean up when the client disconnects
req.on('close', () => clearInterval(interval));
});
Why Use SSE for Uni-directional Feeds?
When you only need to push data from the server to the client—and the client doesn't need to send messages back over the same channel—SSE is your best friend.
- Automatic Reconnection: The
EventSourceAPI in the browser automatically attempts to reconnect if the connection drops, saving you from writing custom reconnection logic. - Text-based Protocol: Since it uses simple text streams, debugging is as easy as inspecting the network tab in your browser or using
curl. - Efficiency: It avoids the header overhead associated with complex binary protocols, making it perfect for low-latency, read-heavy data updates where you don't need the bidirectional overhead of a WebSocket.
By leveraging SSE, you reduce the architectural complexity of your application by avoiding the state management required for full-duplex socket connections, keeping your server-side logic cleaner and more maintainable.
Key Takeaway: Server-Sent Events offer a lightweight, standardized, and HTTP-compliant way to push data updates to clients when bidirectional communication is not required.