Streamlined Updates: Mastering Server-Sent Events (SSE)

UtkarshUtkarsh
4 min read

Introduction

Server-Sent Events (SSE) is a web standard that allows servers to push real-time updates to web clients over HTTP. Unlike WebSockets, SSE operates on a unidirectional stream from server to client and is built on standard HTTP, making it easier to implement and suitable for a wide range of use cases such as live notifications, streaming data, or real-time dashboards.

It also offers several advantages including automatic reconnection, event filtering, and a simpler protocol.

How SSE Works

SSE relies on a simple mechanism:

  1. The client establishes a connection to the server using the EventSource API.

  2. The server responds with an HTTP stream that includes event data in plain text format.

  3. The client listens for these events and updates the UI or performs other tasks based on the incoming data.

Key Features

  • One-way communication: Data flows from server to client.

  • Automatic reconnection: The EventSource object handles reconnections.

  • Custom events: Allows defining and handling named events.

  • Lightweight: Minimal overhead compared to WebSockets.

Setting Up SSE in Node.js

Let’s explore how to set up SSE using Node.js. We'll cover a basic implementation, custom events, and practical examples.

Basic Example

Here’s a simple SSE setup:

Backend (NodeJS)

const express = require('express');
const app = express();

app.get('/events', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

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

  req.on('close', () => {
    console.log('Client disconnected');
  });
});

app.listen(3000, () => {
  console.log('SSE server running on http://localhost:3000');
});

Frontend (HTML + Javascript)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SSE Example</title>
</head>
<body>
  <h1>Server Time Updates</h1>
  <div id="time"></div>

  <script>
    const eventSource = new EventSource('/events');

    eventSource.onmessage = (event) => {
      document.getElementById('time').textContent = `Server Time: ${event.data}`;
    };

    eventSource.onerror = () => {
      console.error('Error connecting to SSE server');
    };
  </script>
</body>
</html>

Custom Events

SSE allows for custom event names. Here’s how you can define and listen for them:

Backend

app.get('/custom-events', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');

  setInterval(() => {
    res.write('event: customEvent\n');
    res.write(`data: {"message": "Hello from custom event"}\n\n`);
  }, 2000);
});

Frontend

<script>
  const customSource = new EventSource('/custom-events');

  customSource.addEventListener('customEvent', (event) => {
    console.log('Received custom event:', JSON.parse(event.data));
  });
</script>

Use Cases for SSE

Real-Time Notifications

SSE is ideal for sending live notifications to users, such as:

  • New messages in a chat application.

  • Stock price updates.

  • Order status changes in e-commerce.

Example: Notification System

let clients = [];

app.get('/subscribe', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  clients.push(res);

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

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

setInterval(() => {
  sendNotification('This is a notification');
}, 5000);

Live Dashboards

Display real-time metrics or analytics such as:

  • Website traffic.

  • IoT device data.

  • Server health monitoring.

Collaborative Applications

Keep users in sync by pushing updates to:

  • Document editors.

  • Task management boards.

  • Whiteboard applications.

Advantages of SSE

  • Simplicity: Easy to implement with existing HTTP/HTTPS infrastructure.

  • Lightweight: No extra libraries or protocols required.

  • Automatic Reconnect: Built-in reconnection handling.

  • Browser Support: Widely supported across modern browsers.

Limitations

  • Unidirectional: Data flows only from server to client.

  • No binary data: SSE supports only text-based data.

  • Connection Limits: Limited by browser’s maximum open connections per server.

Best Practices

  • Use Heartbeats: To keep the connection alive, periodically send a comment (:).

  • Optimize Data: Send only the data that has changed to minimize bandwidth.

  • Handle Errors Gracefully: Implement error handling and retries.

  • Security: Secure SSE endpoints with HTTPS to prevent data leaks.

Conclusion

Server-Sent Events provide a robust and efficient way to implement real-time functionality in web applications. With its simplicity and lightweight nature, SSE is an excellent choice for use cases like live notifications, streaming updates, and real-time dashboards. By understanding its features, limitations, and best practices, you can leverage SSE to enhance your applications and deliver a seamless user experience.

0
Subscribe to my newsletter

Read articles from Utkarsh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Utkarsh
Utkarsh

I'm a MERN Stack developer and technical writer that loves to share his thoughts in words on latest trends and technologies. For queries and opportunities, I'm available at r.utkarsh.0010@gmail.com