2 min read

Server-Sent Events (SSE)

Server-Sent Events (SSE) allow a web page to get updates from a server. Unlike WebSockets, which offer full-duplex communication, SSE is a unidirectional channel where the server sends data to the client.

1. The Concept

SSE is built on top of standard HTTP. The client opens a persistent connection to the server, and the server keeps it open, pushing text-based data whenever it has new information.

  • Unidirectional: Server -> Client only.
  • Text-based: Only sends text (usually JSON).
  • Automatic Reconnection: Built-in retry mechanism if the connection drops.
  • Standard HTTP: Works easily over HTTP/2 and doesn't require special protocols like WebSockets.

2. Client-Side Implementation

The EventSource interface is used to receive server-sent events.

const eventSource = new EventSource('/api/stream');

// 1. Listen for generic messages
eventSource.onmessage = (event) => {
  console.log('New message:', event.data);
  const data = JSON.parse(event.data);
  // Update UI
};

// 2. Listen for connection open
eventSource.onopen = () => {
  console.log('Connection to server opened.');
};

// 3. Listen for errors
eventSource.onerror = (err) => {
  console.error('EventSource failed:', err);
  // EventSource automatically tries to reconnect, but you can close it here if needed.
  // eventSource.close();
};

3. Named Events

The server can send specific event types (not just generic messages). You can listen for these using addEventListener.

eventSource.addEventListener('ping', (event) => {
  console.log('Ping received:', event.data);
});

eventSource.addEventListener('update', (event) => {
  console.log('Update received:', event.data);
});

4. SSE vs. WebSockets

Feature Server-Sent Events (SSE) WebSockets
Direction One-way (Server to Client) Two-way (Bidirectional)
Protocol HTTP WebSocket (TCP)
Data Type Text (UTF-8) Binary & Text
Reconnection Automatic Manual implementation required
Complexity Low (Simple HTTP) Medium/High
Use Case News feeds, stock tickers, notifications Chat apps, multiplayer games

programming/javascript/vanilla/javascript programming/javascript/vanilla/websockets programming/javascript/vanilla/ajax-fetch