Server-Sent Events (SSE)
developer-ready SSE system for Express enabling real-time, one-way data streaming with event broadcasting, auto-reconnect, and heartbeat management.
Overview
A robust Server-Sent Events (SSE) system that enables real-time communication from your backend to connected clients. Unlike WebSockets, SSE offers one-way streaming — ideal for dashboards, live updates, or analytics feeds with minimal overhead. Built with simplicity and scalability in mind, it includes built-in auto-reconnect, heartbeat, and event broadcasting mechanisms.
Installation
What This Does
Adds real-time server-to-client streaming using Server-Sent Events (SSE).
Files & Folders Created
| File / Path | Description |
|---|---|
| /src/services/sseService.js | Core SSE logic with client management and broadcasting. |
| /src/routes/sse.js | Routes for connecting and sending events. |
| /src/example-client.js | Example of consuming SSE stream in Node/Browser. |
Files to be modified
| File / Path | Description |
|---|---|
| server.js | Mounts SSE routes at /api/events and /api/send. |
| .env | Optional: add PORT and SSE_RETRY_TIMEOUT configuration. |
Configuration
# SSE Configuration PORT=3001 SSE_RETRY_TIMEOUT=5000 # client reconnect interval in ms
Frontend Integration
Use this component to stream real-time data from the server directly into your frontend apps (React, Next.js, or vanilla JS). The connection automatically re-establishes if interrupted.
Opens a persistent event stream connection to receive real-time updates.
Broadcasts a new event with data to all connected clients.
Example
1// Example: Next.js / React frontend usage
2import { useEffect, useState } from 'react';
3
4export default function LiveEvents() {
5 const [messages, setMessages] = useState([]);
6
7 useEffect(() => {
8 const source = new EventSource('http://localhost:3001/api/events');
9
10 source.addEventListener('update', (e) => {
11 const data = JSON.parse(e.data);
12 setMessages((prev) => [...prev, data]);
13 });
14
15 source.onerror = (err) => console.error('SSE error:', err);
16 return () => source.close();
17 }, []);
18
19 return (
20 <div className="max-w-md mx-auto p-4">
21 <h2 className="text-lg font-semibold text-foreground mb-3">
22 Live Server Events
23 </h2>
24 <ul className="space-y-2">
25 {messages.map((msg, i) => (
26 <li
27 key={i}
28 className="border border-border/30 rounded-lg p-2 bg-secondary/30 text-sm text-foreground/90"
29 >
30 {msg.message || JSON.stringify(msg)}
31 </li>
32 ))}
33 </ul>
34 </div>
35 );
36}Usage
1// Send custom broadcast from server
2await fetch('http://localhost:3001/api/send', {
3 method: 'POST',
4 headers: { 'Content-Type': 'application/json' },
5 body: JSON.stringify({
6 event: 'update',
7 data: { message: 'Server metrics refreshed' }
8 })
9});