Server-Sent Events (SSE)

A standard for pushing real-time updates from server to client over HTTP.

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over a single HTTP connection. Unlike WebSocket, SSE is unidirectional - only the server can send data.

SSE vs WebSocket

FeatureSSEWebSocket
DirectionServer to clientBidirectional
ProtocolHTTPWebSocket
ReconnectionAutomaticManual
Browser SupportNative EventSourceNative WebSocket
ComplexitySimpleMore complex

When to Use SSE

  • Live Feeds: News, social media updates
  • Notifications: Real-time alerts
  • Progress Updates: File upload, processing status
  • Stock Tickers: Price updates
  • Log Streaming: Real-time log viewing

Event Format

SSE uses a simple text-based format with event, data, id, and retry fields.

Advantages

  • Works over standard HTTP
  • Automatic reconnection
  • Event ID for resuming streams
  • Simple to implement

Code Examples

Node.js SSE Server

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

  const sendEvent = (data) => {
    res.write(`data: ${JSON.stringify(data)}\n\n`);
  };

  const interval = setInterval(() => {
    sendEvent({ time: new Date().toISOString() });
  }, 1000);

  req.on("close", () => clearInterval(interval));
});

Browser EventSource

const source = new EventSource("/events");

source.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Update:", data);
};

source.onerror = () => console.log("Connection error");