Server-Sent Events (SSE) is a technology in HTML5 that allows a web server to send real-time updates to the browser, without the client needing to request them explicitly. Unlike WebSockets, SSE is one-way communication: from the server to the client. This is useful for applications where the server needs to push information to the browser, such as live feeds, real-time notifications, or data streams.
In this chapter, we’ll explore Server-Sent Events from basic to advanced, explaining its architecture, use cases, and how to implement it in detail, providing examples to make the concepts clear and accessible.
Server-Sent Events allow the server to push updates to the browser through a simple HTTP connection. Once the browser establishes a connection to the server, it listens for events or updates that the server sends. This can be useful for live updates, notifications, and real-time event-driven systems.
Unlike HTTP polling (where the client constantly requests updates from the server), SSEs keep an open connection where the server sends updates as they happen.
SSE is particularly useful for applications where the client needs to receive updates or changes automatically from the server. Here are some examples:
SSE works by maintaining an open HTTP connection between the client and the server. When a browser subscribes to events from the server, the server sends updates as text messages over the same connection.
The data sent is usually formatted in a simple text format, where each event consists of multiple lines that specify:
SSE and WebSockets are both methods to enable real-time communication between a client and server, but they differ in their communication models and use cases.
Feature | SSE (Server-Sent Events) | WebSockets |
---|---|---|
Communication Model | Unidirectional (Server to Client) | Bidirectional (Full Duplex Communication) |
Connection | Persistent connection, server pushes updates to the client | Persistent connection, both client and server can send messages |
Use Case | Best for real-time updates like news feeds, stock prices, or live notifications | Ideal for applications requiring two-way communication like chat applications, online gaming, or collaborative tools |
Browser Support | Wide browser support but limited to HTTP | Broad support across modern browsers, using a specific WebSocket protocol |
Complexity | Simple to implement, leverages HTTP | More complex to implement, requires additional infrastructure |
Security | Works over HTTPS, limited security concerns | Works over WebSocket Secure (WSS), but requires careful handling of security aspects |
In summary, SSE is simpler and well-suited for one-way communication, whereas WebSockets are designed for more complex, two-way communication.
SSE is implemented using standard HTTP. The server sends events as text data in a continuous stream. To set up SSE, you need to configure both the server and the client.
Here’s the general flow:
EventSource
APIIn HTML, SSE is powered by the EventSource
API, which listens for updates from the server.
To send Server-Sent Events from the server, the server must respond with an appropriate Content-Type
and maintain an open connection to send data continuously.
Here’s how you can set up a basic SSE server using Node.js:
const express = require('express');
const app = express();
app.get('/events', (req, res) => {
// Set headers to enable SSE
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Send an event every 3 seconds
setInterval(() => {
res.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
}, 3000);
});
app.listen(3000, () => {
console.log('SSE server running on port 3000');
});
text/event-stream
: The MIME type for Server-Sent Events.res.write()
: Sends data to the client, formatted as SSE.setInterval()
: Sends the current time to the client every 3 seconds.The client listens for events from the server using the EventSource
API.
SSE Example
Server Time Updates:
When you open this page, the <div>
will be continuously updated with the current time from the server every 3 seconds.
The EventSource
API has built-in error handling. You can listen to the onerror
event to handle issues like disconnections:
eventSource.onerror = function(event) {
console.log("Error occurred while receiving updates:", event);
};
If the server goes down or the connection is lost, the browser will automatically try to reconnect after a few seconds, making it resilient to temporary network issues.
Server-Sent Events (SSE) provide a simple, efficient way for servers to send real-time updates to clients. It’s perfect for use cases like live feeds, notifications, and real-time streaming of text data. SSE is easier to implement than WebSockets for one-way communication, and its ability to automatically reconnect in case of failure makes it a robust choice for many real-time applications. Happy coding !❤️