LogoMasst Docs

Server-Sent Events

Understanding SSE for server-to-client streaming.

What is SSE?

Server-Sent Events (SSE) is a standard for pushing updates from server to client over HTTP. Unlike WebSocket, it's unidirectional (server to client only).


SSE vs WebSocket

AspectSSEWebSocket
DirectionServer → Client onlyBidirectional
ProtocolHTTPWebSocket
ReconnectionAutomaticManual
Browser supportNative EventSourceNative WebSocket
ComplexitySimpleMore complex

How SSE Works

Client                              Server
   │                                   │
   │─── GET /events ──────────────────►│
   │    Accept: text/event-stream      │
   │                                   │
   │◄── HTTP 200 ─────────────────────│
   │    Content-Type: text/event-stream│
   │                                   │
   │◄── data: message 1 ──────────────│
   │◄── data: message 2 ──────────────│
   │◄── data: message 3 ──────────────│
   │    (connection stays open)        │

Event Format

event: update
id: 123
retry: 5000
data: {"price": 150.25}

event: notification
data: New message received
FieldDescription
eventEvent type (optional)
idEvent ID for reconnection
retryReconnection time in ms
dataEvent payload

Client Example (JavaScript)

const source = new EventSource('/api/events');

source.onmessage = (event) => {
  console.log('Message:', event.data);
};

source.addEventListener('update', (event) => {
  const data = JSON.parse(event.data);
  console.log('Update:', data);
});

source.onerror = () => {
  console.log('Connection error, will auto-reconnect');
};

Server Example (Node.js)

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`);
  };

  // Send updates
  const interval = setInterval(() => {
    sendEvent({ time: new Date() });
  }, 1000);

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

Use Cases

Use CaseWhy SSE
Live feedsNews, social media updates
NotificationsPush alerts to users
Progress updatesFile upload, long tasks
Stock tickersPrice updates
Log streamingReal-time logs

When to Use SSE vs WebSocket

RequirementChoose
Server → Client onlySSE
Bidirectional neededWebSocket
Simple implementationSSE
Binary dataWebSocket
Auto-reconnectionSSE
Low latency bidirectionalWebSocket

Interview Tips

  • Explain unidirectional nature
  • Compare with WebSocket and polling
  • Describe auto-reconnection with event IDs
  • Know the event format (event, id, data)
  • Give use cases: notifications, live updates