Real-time Communication

Server-Sent Events

Build real-time applications with Server-Sent Events - receive live updates from servers with automatic reconnection and event streaming.

What are Server-Sent Events (SSE)?

Server-Sent Events let a server push updates to the browser over a normal HTTP connection that stays open. In JavaScript, new EventSource("/stream") receives each message in a message event, and the browser reconnects automatically if the connection drops. The stream is one-way, server to client, and it's simpler than WebSockets for live feeds and notifications.

const source = new EventSource("/api/updates");
source.onmessage = (e) => console.log(JSON.parse(e.data));
source.addEventListener("price", (e) => update(e.data));

// Server response (Content-Type: text/event-stream)
// event: price
// data: {"btc": 64000}
//

Key Features

Real-time

Instant server-to-client communication

Auto-reconnect

Automatic reconnection on disconnect

HTTP/2 Ready

Efficient streaming over HTTP

Interactive SSE Demo

Experience real-time data streaming with stock prices, live chat, and system monitoring - all powered by Server-Sent Events.

Server-Sent Events Architecture

Communication Flow

  • Unidirectional: Server → Client only
  • HTTP-based: Uses standard HTTP protocol
  • Text/Event-Stream: MIME type for events
  • Persistent Connection: Long-lived connection
  • Auto-reconnect: Built-in reconnection logic

Event Stream Format

data: Hello World! event: update data: {"message": "New data"} id: 123 : This is a comment data: Multi-line data: event data

EventSource API Usage

Creating EventSource Connection

Basic Connection
const eventSource = new EventSource('/api/events'); eventSource.onopen = (e) => { console.log('Connection opened'); }; eventSource.onmessage = (e) => { console.log('Data:', e.data); }; eventSource.onerror = (e) => { console.log('Error occurred'); };
With CORS & Headers
const eventSource = new EventSource( 'https://api.example.com/events', { withCredentials: true } ); // Custom event types eventSource.addEventListener('update', (e) => { const data = JSON.parse(e.data); handleUpdate(data); });

Event Properties & Types

Event Properties
  • data - The event data
  • lastEventId - Last received ID
  • origin - Event source origin
  • type - Event type name
  • target - EventSource instance
Ready States
  • CONNECTING (0) - Establishing connection
  • OPEN (1) - Connection is open
  • CLOSED (2) - Connection is closed

Connection Management

Handle connection states and implement proper cleanup:

class SSEManager { constructor(url, options = {}) { this.url = url; this.options = options; this.eventSource = null; this.reconnectDelay = 1000; this.maxReconnectDelay = 30000; } connect() { if (this.eventSource) { this.disconnect(); } this.eventSource = new EventSource(this.url, this.options); this.eventSource.onopen = (e) => { console.log('Connected to SSE'); this.reconnectDelay = 1000; // Reset delay on successful connection }; this.eventSource.onerror = (e) => { if (this.eventSource.readyState === EventSource.CLOSED) { this.scheduleReconnect(); } }; } disconnect() { if (this.eventSource) { this.eventSource.close(); this.eventSource = null; } } scheduleReconnect() { setTimeout(() => { if (!this.eventSource || this.eventSource.readyState === EventSource.CLOSED) { this.connect(); this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay); } }, this.reconnectDelay); } }

Server-Side Implementation Examples

Node.js/Express Server

Basic SSE endpoint implementation:

app.get('/api/events', (req, res) => { // Set SSE headers res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Cache-Control' }); // Send initial connection event res.write('data: Connected to SSE\n\n'); // Send periodic updates const interval = setInterval(() => { const data = { timestamp: new Date().toISOString(), data: Math.random() }; res.write(`data: ${JSON.stringify(data)}\n\n`); }, 1000); // Handle client disconnect req.on('close', () => { clearInterval(interval); res.end(); }); });

Custom Events & Event IDs

Custom Event Types
// Server res.write('event: update\n'); res.write('data: User data updated\n\n'); res.write('event: notification\n'); res.write('data: New message\n\n'); // Client eventSource.addEventListener('update', handleUpdate); eventSource.addEventListener('notification', handleNotification);
Event IDs & Recovery
// Server res.write('id: 123\n'); res.write('data: Important message\n\n'); // Recovery from last event const lastEventId = req.headers['last-event-id']; if (lastEventId) { // Send events after this ID sendEventsSince(lastEventId); }

Advanced Server Patterns

Broadcasting to multiple clients:

class SSEBroadcaster { constructor() { this.clients = new Set(); } addClient(res) { this.clients.add(res); res.on('close', () => { this.clients.delete(res); }); } broadcast(eventType, data) { const message = `event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`; this.clients.forEach(client => { try { client.write(message); } catch (error) { this.clients.delete(client); } }); } broadcastToChannel(channel, eventType, data) { const message = `event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`; this.clients.forEach(client => { if (client.channel === channel) { try { client.write(message); } catch (error) { this.clients.delete(client); } } }); } }

Use Cases & Best Practices

Ideal Use Cases

  • • Live sports scores and updates
  • • Stock price feeds
  • • Social media feeds
  • • System monitoring dashboards
  • • News feed updates
  • • Progress indicators
  • • Notification systems

Performance Optimization

  • • Use event IDs for recovery
  • • Implement proper cleanup
  • • Buffer events for slow clients
  • • Use compression when possible
  • • Monitor connection health

Error Handling & Fallbacks

  • • Implement exponential backoff
  • • Handle network interruptions
  • • Provide polling fallback
  • • Monitor connection state
  • • Log connection issues

Security Considerations

  • • Validate and sanitize data
  • • Implement authentication
  • • Use HTTPS in production
  • • Rate limit connections
  • • Monitor for abuse

SSE vs WebSockets Comparison

Server-Sent Events Advantages

  • • Simpler to implement
  • • Built-in reconnection
  • • HTTP-based (firewall friendly)
  • • Event replay with IDs
  • • Better for one-way communication
  • • Works well with HTTP/2
  • • Native browser support

SSE Limitations

  • • Unidirectional only (server → client)
  • • Text data only
  • • 6 connection limit per domain
  • • No binary data support
  • • Limited mobile support

WebSockets Advantages

  • • Bidirectional communication
  • • Binary data support
  • • Lower latency
  • • No connection limits
  • • Custom protocols
  • • Better for real-time gaming
  • • Full-duplex communication

When to Choose What

  • SSE: Live feeds, notifications, monitoring
  • WebSockets: Chat, gaming, collaboration
  • SSE: Simple server push needs
  • WebSockets: Complex real-time interactions
  • SSE: Better infrastructure compatibility

Code Editor

<p>Server-Sent Events need a server, so this demo <b>simulates</b> the stream.</p>
<pre>// Real code:
const source = new EventSource("/api/scores");
source.onmessage = (e) => show(JSON.parse(e.data));</pre>
<ul id="feed"></ul>

Preview

Server-Sent Events — step by step

1 / 4
1

Understand SSE vs WebSockets

Server-Sent Events (SSE) are unidirectional — the server pushes data to the client over a persistent HTTP connection. Unlike WebSockets, the client cannot send messages back over the same connection. SSE is simpler and works over standard HTTP.

1 of 4
💡SSE Is Perfect for Live Feeds and Notifications
SSE is ideal for use cases where the server needs to push updates to the client — live activity feeds, real-time dashboards, progress updates, and notifications. Since it uses standard HTTP, it works seamlessly through proxies and load balancers that may block WebSocket upgrades.

🎯 Quick Check

What is the key difference between SSE and WebSockets?

Server-Sent Events: summary

Key points

  • The server sends text/event-stream, with messages separated by a blank line.
  • Reconnection and the Last-Event-ID header are built in.
  • SSE works over HTTP/2 and passes through most proxies and firewalls.

Frequently asked questions

›Can SSE send data from the client to the server?

No. It's one-way. Send client data with a normal fetch request, or use WebSockets for two-way messaging.