← Back to Node.js, page 7

nodejs-0140 · Easy fresher

What are Server-Sent Events, how do you implement them in Node.js, and how does Last-Event-ID help clients resume?

SSE is a one-way stream from server to browser over a normal HTTP response with Content-Type text/event-stream. Each event is lines such as id:, event: and data:, ended by a blank line. The browser's EventSource reconnects by itself and sends the Last-Event-ID header, so the server can resume. Send comment lines as heartbeats and watch for the client closing the connection.

Full answer

Format

  • Response headers: Content-Type: text/event-stream, Cache-Control: no-cache, and Connection: keep-alive for HTTP/1.1.
  • An event is text lines followed by an empty line: id: 7 event: progress data: {"percent":70}
  • Several data lines are joined with newlines. Lines that start with a colon are comments, often used as heartbeats (: ping).
  • retry: 3000 tells the client how many milliseconds to wait before reconnecting.

Client

  • Browser: new EventSource('/events'). It reconnects automatically after errors and sends Last-Event-ID with the last id it received. Authentication is limited to cookies, because custom headers cannot be set (a fetch-based client or a polyfill can send them). Node also has fetch, which can read the stream; a parser is a few lines.

Server in Node

  • Write with res.write(...). Do not call res.end() until the client leaves or the job finishes.
  • Send a heartbeat comment every 15 to 30 seconds so proxies do not close an idle connection.
  • Listen for req.on('close') to stop timers and remove the client from your list. Otherwise you leak memory.
  • Disable response buffering and compression for this route (proxies such as nginx need buffering off).
  • For resume, keep recent events with ids, read the Last-Event-ID header, and replay the missed ones.

SSE versus WebSocket

  • SSE: one direction, plain HTTP, automatic reconnect, works with HTTP/2 multiplexing. Good for notifications, progress, feeds, and streaming responses.
  • WebSocket: two directions, binary, custom protocol. More moving parts.

Limit: browsers allow about six connections per host over HTTP/1.1, so use HTTP/2 in production.

javascript
const http = require('node:http');

const history = [];                          // recent events kept for replay
for (let id = 1; id <= 5; id++) history.push({ id, data: { step: id } });

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
  const lastId = Number(req.headers['last-event-id'] || 0);
  res.write('retry: 1000\n\n');
  for (const event of history.filter((e) => e.id > lastId)) {       // replay what the client missed
    res.write(`id: ${event.id}\nevent: step\ndata: ${JSON.stringify(event.data)}\n\n`);
  }
  res.write(': heartbeat\n\n');
  res.end();                                                          // this demo ends the stream, a real one keeps it open
});

// A tiny SSE parser built on fetch.
async function readEvents(url, headers = {}) {
  const res = await fetch(url, { headers });
  const events = [];
  let current = {};
  let buffer = '';
  const decoder = new TextDecoder();
  for await (const chunk of res.body) {
    buffer += decoder.decode(chunk, { stream: true });
    let index;
    while ((index = buffer.indexOf('\n\n')) !== -1) {
      const block = buffer.slice(0, index);
      buffer = buffer.slice(index + 2);
      current = {};
      for (const line of block.split('\n')) {
        if (line.startsWith(':')) { current.comment = line.slice(1).trim(); continue; }
        const [field, ...rest] = line.split(':');
        current[field] = rest.join(':').trim();
      }
      events.push(current);
    }
  }
  return { type: res.headers.get('content-type'), events };
}

server.listen(0, '127.0.0.1', async () => {
  const url = 'http://127.0.0.1:' + server.address().port;
  const first = await readEvents(url);
  console.log('content type:', first.type);
  console.log('first connection ids:', first.events.filter((e) => e.id).map((e) => e.id).join(','));
  console.log('comment event:', first.events.at(-1).comment);

  // The connection dropped after id 3. The client reconnects with Last-Event-ID.
  const second = await readEvents(url, { 'Last-Event-ID': '3' });
  console.log('after reconnect with Last-Event-ID 3:', second.events.filter((e) => e.id).map((e) => `${e.id}:${e.data}`).join(' '));
  server.close();
});

The server replays stored events. The second request sends Last-Event-ID 3 and receives only the events after it. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): content type: text/event-stream first connection ids: 1,2,3,4,5 comment event: heartbeat after reconnect with Last-Event-ID 3: 4:{"step":4} 5:{"step":5}

Key points

  • SSE is a one-way text stream over HTTP.
  • Events use id, event and data lines and a blank line.
  • EventSource reconnects and sends Last-Event-ID.
  • Use heartbeats and clean up on 'close'.
  • WebSocket is for two-way messaging.

Common mistakes

  • Calling res.end() right after writing and breaking the stream.
  • Forgetting the blank line after each event.
  • Not cleaning up on the 'close' event.
  • Leaving proxy buffering or compression on for the stream.
  • Using SSE where the client must send data often.

Follow-ups

  • How does EventSource authenticate when it cannot set headers?
  • How would you stream a long job's progress to many clients?
  • How does HTTP/2 change the connection limit problem?

Tips

  • Show the wire format with id, event, data.
  • Say that reconnect is automatic.
  • Compare with WebSocket in one sentence.