TExcelTAD
Home › HTML › HTML Server-Sent Events

HTML Server-Sent Events

Most web pages work on a "you ask, I answer" basis: the browser requests something and the server replies. But some information changes on its own — live sports scores, stock prices, a progress bar for a long upload, new notifications. Server-Sent Events (SSE) let the server push updates to the page over a single long-lived HTTP connection, as soon as they happen.

How it works

  1. The page opens a connection with new EventSource('/updates').
  2. The server keeps the response open and writes small text messages whenever it has news.
  3. The browser fires a message event for each one.
  4. If the connection drops, the browser reconnects automatically.

SSE is one-way: server → browser. For two-way chat-style communication, use WebSockets instead.

The browser side

js
const source = new EventSource('/updates');

source.onopen = function () {
  console.log('Connected');
};

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

source.onerror = function () {
  console.log('Connection lost — the browser will retry');
};

// Listen for a custom event type sent with "event: score"
source.addEventListener('score', function (event) {
  const score = JSON.parse(event.data);
  console.log(score.home, '-', score.away);
});

// Stop listening
// source.close();

The server side

The server must answer with the content type text/event-stream and then write messages in a very simple text format. Here is a minimal Node.js server (shown for explanation — it cannot run in the browser):

js
// server.js  (Node.js)
const http = require('http');

http.createServer(function (req, res) {
  if (req.url !== '/updates') { res.end('Hello'); return; }
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });
  let n = 0;
  const timer = setInterval(function () {
    n++;
    res.write('data: Update number ' + n + '\n\n');
  }, 2000);
  req.on('close', function () { clearInterval(timer); });
}).listen(3000);

The message format

Each message is one or more field: value lines followed by a blank line, which marks the end of the message.

data: Simple text message

event: score
data: {"home": 2, "away": 1}

id: 42
retry: 5000
data: First line
data: Second line
Field Meaning
data: The message content. Several data: lines are joined with newlines
event: A custom event name; listen with addEventListener(name, …) instead of onmessage
id: An id the browser remembers; after reconnecting it sends Last-Event-ID so the server can resume
retry: How many milliseconds to wait before reconnecting
: (line starting with colon) A comment, often sent as a "heartbeat" to keep the connection open

The EventSource API

Member Purpose
new EventSource(url) Open a connection
onopen Connection established
onmessage Message without an event: name
onerror Connection problem (the browser retries)
addEventListener(type, fn) Listen for named events
readyState 0 connecting, 1 open, 2 closed
close() Close the connection for good

A simulation

There is no server inside a playground, so this example simulates an SSE stream: it splits a hard-coded text stream into messages using the same rules a browser follows (blank line ends a message, event: sets the type, data: lines are joined) and "delivers" them one per second.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <h3>Live match (simulated stream)</h3>
  <p id="score">Waiting for kick-off…</p>
  <ul id="log"></ul>
  <script>
    const stream =
      'event: score\ndata: {"home":0,"away":0}\n\n' +
      'data: Kick-off!\n\n' +
      'event: score\ndata: {"home":1,"away":0}\n\n' +
      'data: Half-time\n\n' +
      'event: score\ndata: {"home":1,"away":1}\n\n' +
      'data: Full-time\n\n';

    // Parse the text into messages, like EventSource does
    const messages = stream.split('\n\n').filter(Boolean).map(function (block) {
      const msg = { type: 'message', data: [] };
      block.split('\n').forEach(function (line) {
        const i = line.indexOf(':');
        const field = line.slice(0, i), value = line.slice(i + 1).trim();
        if (field === 'event') msg.type = value;
        if (field === 'data') msg.data.push(value);
      });
      msg.data = msg.data.join('\n');
      return msg;
    });

    function handle(msg) {
      if (msg.type === 'score') {
        const s = JSON.parse(msg.data);
        document.getElementById('score').textContent = 'Home ' + s.home + ' – ' + s.away + ' Away';
      } else {
        const li = document.createElement('li');
        li.textContent = msg.data;
        document.getElementById('log').appendChild(li);
      }
    }

    messages.forEach(function (m, i) { setTimeout(function () { handle(m); }, (i + 1) * 1000); });
  </script>
</body>
</html>

With a real server, you would replace the parsing and timers with new EventSource('/match') and the same handle logic inside the listeners.

SSE vs alternatives

Technique Direction Notes
Polling (fetch every few seconds) Browser asks repeatedly Simple but wasteful and laggy
Server-Sent Events Server → browser Plain HTTP, auto-reconnect, text only
WebSockets Both ways Best for chat and games; more complex

Tip: SSE works through most proxies because it is ordinary HTTP. Remember to send a comment line (: ping) every 15–30 seconds so idle connections are not closed by servers in between.

Test yourself

Which object does the browser use to receive Server-Sent Events?

  1. WebSocket
  2. EventSource
  3. XMLHttpRequest
  4. Worker

What ends a single message in the event stream?

  1. A semicolon
  2. A blank line
  3. The word end
  4. A closing tag

When should you choose WebSockets over SSE?

  1. When only the server sends updates
  2. When both the browser and server need to send messages frequently
  3. When you want automatic reconnection
  4. Never