HTML Server-Sent Events (SSE)

Server-Sent Events (SSE) allow a web page to receive automatic updates from a server via a single, long-lasting HTTP connection. Unlike WebSockets, SSE is a unidirectional protocol, where data flows from the server to the client.

1. What are Server-Sent Events (SSE)?

SSE is a standard that enables servers to push updates to the client in real-time, using a simple HTTP connection. It is a part of the HTML5 specification and is useful for applications that require continuous updates from the server, such as:

  • Stock price updates
  • News feeds
  • Chat applications
  • Real-time notifications

2. Basic Syntax

To implement SSE:

  1. Server-Side: Send updates from the server in a specific format.
  2. Client-Side: Use JavaScript to listen to updates and handle incoming messages.

3. Setting Up Server-Sent Events

Server-Side Example (Node.js)

Create a simple server that sends updates.

const http = require('http');

http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  setInterval(() => {
    res.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
  }, 1000);

}).listen(3000, () => {
  console.log('SSE server running on port 3000');
});

Try It Now

Client-Side Example (HTML + JavaScript)

Connect to the SSE server and handle incoming messages.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>SSE Example</title>
</head>
<body>

<h1>Server Time Updates</h1>
<div id="time"></div>

<script>
  if (typeof(EventSource) !== "undefined") {
    var source = new EventSource('http://localhost:3000');
    source.onmessage = function(event) {
      document.getElementById('time').innerHTML = event.data;
    };
  } else {
    document.getElementById('time').innerHTML = "Sorry, your browser does not support Server-Sent Events.";
  }
</script>

</body>
</html>

Try It Now

4. Advanced Topics in Server-Sent Events

4.1 Event Types

SSE allows sending different types of events. You can specify an event type on the server and listen for it on the client.

Server-Side:

res.write('event: customEvent\n');
res.write('data: This is a custom event\n\n');

Try It Now

Client-Side:

source.addEventListener('customEvent', function(event) {
  console.log('Custom Event:', event.data);
});

Try It Now

4.2 Reconnection Handling

By default, the browser will automatically attempt to reconnect to the server if the connection is lost. You can control this behavior using the retry field.

Server-Side:

res.write('retry: 5000\n'); // Retry after 5000 milliseconds

Try It Now

4.3 Sending Multiple Data Fields

You can send multiple data fields in a single event.

Server-Side:

res.write('data: Field 1\n');
res.write('data: Field 2\n\n');

Try It Now

4.4 Managing Connections

You can manage multiple clients by keeping track of connections and sending messages to all connected clients.

Example:

let clients = [];

http.createServer((req, res) => {
  clients.push(res);
  res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' });

  req.on('close', () => {
    clients = clients.filter(client => client !== res);
  });

}).listen(3000);

function broadcast(message) {
  clients.forEach(client => client.write(`data: ${message}\n\n`));
}

Try It Now

4.5 Security Considerations

  • Cross-Origin Resource Sharing (CORS): Ensure that your server is set up to handle CORS if the client and server are on different domains.
  • Rate Limiting: Protect against potential abuse by limiting the rate of messages sent to the client.

5. Use Cases for SSE

  • Live Sports Updates: Deliver real-time scores and updates.
  • Monitoring Dashboards: Continuously update metrics and logs.
  • Social Media Feeds: Stream live updates and notifications.
  • Collaborative Applications: Sync data in collaborative environments like document editors.

6. Limitations of SSE

  • Unidirectional Communication: SSE only supports server-to-client communication. For bidirectional communication, consider using WebSockets.
  • Browser Support: While SSE is widely supported, it may not be available in all browsers, especially older versions.
  • Connection Limits: Browsers have a limit on the number of concurrent connections to a server.

Conclusion

HTML Server-Sent Events offer a simple and efficient way to push updates from the server to the client in real time. With its ease of use and broad applicability, SSE is a valuable tool for developers looking to enhance user experience with dynamic content.