Server-Sent Events (SSE) in HTML: A Detailed Guide
Server-Sent Events (SSE) provide a simple and efficient way to send real-time data from a server to a web page over HTTP. Unlike WebSockets, which is bidirectional, SSE is a one-way channel from the server to the client, making it an ideal solution for applications that only require server-to-client communication.
1. Introduction to SSE
What are Server-Sent Events?
Server-Sent Events are a standard browser feature used for receiving automatic updates from a server via an HTTP connection. This can be utilized for live news feeds, notifications, or any other form of real-time data updates.
Benefits of SSE:
- Simplicity: No need for complex protocols or libraries.
- Built-in Reconnection: If the connection drops, the browser will automatically try to reconnect.
- Efficient: Uses a single HTTP connection.
- Native Browser Support: No additional libraries are required.
2. Getting Started with SSE
HTML:
<div id="events"></div>
JavaScript:
const eventSource = new EventSource("path_to_your_server_endpoint");
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
document.getElementById("events").innerHTML += `<p>${data.message}</p>`;
};
eventSource.onerror = function(error) {
console.error('EventSource failed:', error);
eventSource.close();
};
3. Server-side Implementation
To make SSE work, the server must send the data with the content type set to `text/event-stream`. Here's an example using Node.js and Express:
const express = require('express');
const app = express();
app.get('/path_to_your_server_endpoint', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
// Send an event every 2 seconds
setInterval(() => {
res.write(`data: ${JSON.stringify({message: "Hello, client!"})}\n\n`);
}, 2000);
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
4. Handling Custom Events
Besides the general `message` event, you can also send named events from the server.
Server:
res.write("event: userNotification\n");
res.write(`data: ${JSON.stringify({message: "New user joined!"})}\n\n`);
Client:
eventSource.addEventListener('userNotification', function(event) {
const data = JSON.parse(event.data);
console.log(data.message);
});
5. Closing the Connection
If you want to close the SSE connection from the client side, use:
eventSource.close();
6. Browser Compatibility
Most modern browsers support SSE. However, Internet Explorer does not, so if you need to support IE, you might consider other solutions or polyfills.
Conclusion
Server-Sent Events offer a simple way to push real-time updates from the server to the web browser. With built-in reconnection, native browser support, and straightforward implementation, it's a valuable tool for many web applications.