Skip to content

Sse Intro

DodaTech 4 min read

title: "Introduction to Server-Sent Events" description: "Learn what Server-Sent Events (SSE) are, how they enable server-to-client streaming, and when to use them over WebSocket for real-time data." weight: 11 date: 2026-06-28 lastmod: 2026-06-28 tags: ["apis", "sse"]


Server-Sent Events (SSE) is a standard that allows servers to push data to web clients over HTTP. Unlike WebSocket, SSE is unidirectional (server to client) and uses standard HTTP, making it simpler for many use cases.

## What You'll Learn

- What SSE is and how it works
- SSE vs WebSocket differences
- Common SSE use cases
- Browser support and EventSource API
- Simple SSE server implementation

## Why It Matters

SSE is the simplest way to add real-time updates to web applications. It works over standard HTTP, requires no special proxies or handshakes, and automatically handles reconnection.

## Real-World Use

A news website uses SSE to push breaking news alerts to readers. When a story breaks, the server sends an event, and all connected browsers display the alert within milliseconds without any polling.

## Flow Chart

```mermaid
flowchart LR
    A[Server] -->|HTTP Connection| B[Client]
    A -->|Event: data| B
    A -->|Event: data| B
    A -->|Event: data| B
    B -->|Auto-reconnect| A
    Note: Unidirectional server-to-client

Code Examples

Example 1: Basic SSE Server in Node.js

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/events') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
    });

    // Send events every 2 seconds
    const intervalId = setInterval(() => {
      const data = JSON.stringify({
        time: new Date().toISOString(),
        message: 'Hello from SSE',
      });
      res.write(`data: ${data}\n\n`);
    }, 2000);

    // Clean up on connection close
    req.on('close', () => {
      clearInterval(intervalId);
    });
  } else {
    res.writeHead(404);
    res.end();
  }
});

server.listen(3000, () => {
  console.log('SSE server on http://localhost:3000/events');
});

Expected output: Server sends a JSON event every 2 seconds to all connected SSE clients.

Example 2: Browser EventSource Client

<!DOCTYPE html>
<html>
<head>
  <title>SSE Demo</title>
</head>
<body>
  <h1>Server-Sent Events</h1>
  <div id="events"></div>

  <script>
    const eventDiv = document.getElementById('events');

    if (typeof EventSource !== 'undefined') {
      const source = new EventSource('/events');

      source.onopen = () => {
        console.log('Connection opened');
      };

      source.onmessage = (event) => {
        const data = JSON.parse(event.data);
        const p = document.createElement('p');
        p.textContent = `[${data.time}] ${data.message}`;
        eventDiv.appendChild(p);
      };

      source.onerror = (error) => {
        console.error('EventSource error:', error);
      };
    } else {
      eventDiv.textContent = 'EventSource not supported';
    }
  </script>
</body>
</html>

Expected output: Browser connects to SSE endpoint and displays each received event as a paragraph.

Example 3: SSE with Named Events

// Server with named events
res.write(`event: user-connected\ndata: {"userId": 123}\n\n`);
res.write(`event: message\ndata: {"text": "Hello"}\n\n`);
res.write(`event: user-disconnected\ndata: {"userId": 123}\n\n`);

// Client listening for named events
const source = new EventSource('/events');

source.addEventListener('user-connected', (event) => {
  const data = JSON.parse(event.data);
  console.log('User connected:', data.userId);
});

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

source.addEventListener('user-disconnected', (event) => {
  const data = JSON.parse(event.data);
  console.log('User disconnected:', data.userId);
});

Expected output: Client dispatches named events to different handlers based on the event type.

Common Mistakes

Mistake Explanation
Forgetting Content-Type header SSE requires Content-Type: text/event-stream or the browser will not parse events
Adding Cache-Control Set Cache-Control: no-cache to prevent browsers from caching the event stream
Not handling connection close Always clean up server resources when the client disconnects
Using SSE for bidirectional communication SSE is server-to-client only; use WebSocket for bidirectional needs
Missing trailing newlines Each SSE event must end with \n\n (double newline)

Practice Questions

  1. What is the difference between SSE and WebSocket?
  2. What HTTP headers are required for SSE?
  3. How does the EventSource API handle reconnection?
  4. What are named events in SSE?
  5. What browsers support EventSource?

Challenge

Build an SSE server that streams system metrics (CPU, memory, uptime) to a browser dashboard. The client should display each metric in real-time with live-updating values.

FAQ

Does SSE work over HTTP/2?

Yes, SSE works over HTTP/2 and benefits from HTTP/2 multiplexing, allowing multiple event streams over a single connection.

How many simultaneous SSE connections can a server handle?

Each SSE connection uses one HTTP connection and a thread/fiber. Node.js can handle 10,000+ connections. Connection limits depend on server resources.

Can SSE send binary data?

No, SSE only supports UTF-8 text. For binary data, encode as Base64 or use WebSocket.

Does SSE support CORS?

Yes, SSE respects CORS. Set 'Access-Control-Allow-Origin' header on the server for cross-origin requests.

What happens when an SSE connection drops?

The browser's EventSource API automatically reconnects after 3 seconds. The Last-Event-ID header allows the server to resume from where the client left off.

Is SSE suitable for high-frequency updates?

Yes, SSE handles high-frequency updates well. Each event is a separate message with minimal overhead.

Mini Project

Build a live sports scoreboard using SSE. The server pushes game scores and events to all connected browsers. Include named events for score changes, game status updates, and player statistics.

What's Next

Compare SSE and WebSocket in detail

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro