Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 43 ยท Data and Files

Real-Time Features: SSE and WebSockets

Push live data from Express with Server-Sent Events, and learn when ws or socket.io is the better choice, with runnable SSE and broadcast examples.

Normal HTTP is a question and an answer: the browser asks, the server replies, and the conversation is over. But many features need the server to speak first: a new chat message, a progress bar, a live score, a notification. You have three main options. The browser can ask again and again (polling), the server can keep one response open and keep writing to it (Server-Sent Events), or both sides can talk over a persistent two-way connection (WebSockets).

Express works well with all three, but they are not equally easy. This lesson focuses on Server-Sent Events (SSE), which are plain HTTP and need no extra package, and then explains when ws or socket.io is worth adding. The real packages are read-only here because npm is not available on this site, but the SSE examples are real and run as written, on our mini Express over node:http.

Three ways to go live

Polling Ask again every few seconds.
SSE Server pushes over one open response.
WebSocket Two-way messages both ways.

Start with the simplest one that fits.

1 / 2

Server-Sent Events: the idea

An SSE response is an ordinary HTTP response that never finishes. The server sets Content-Type: text/event-stream, keeps the connection open and writes small text messages whenever it likes. The browser's built-in EventSource class reads them and fires events. A message is a few lines ending with a blank line:

TEXT
event: price
id: 7
data: {"symbol":"ABC","value":101.5}

Only data: is required. event: names the event type (default is message), and id: lets the browser tell the server where it stopped when it reconnects, through the Last-Event-ID header. If the connection drops, EventSource reconnects by itself. That automatic behavior is the main reason to prefer SSE over hand-rolled polling.

SSE in Express

Real Express code for a live clock-style endpoint:

JavaScript
import express from 'express';

const app = express();

app.get('/events', (req, res) => {
  res.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });
  res.flushHeaders(); // send the headers now, keep the body open

  let counter = 0;
  const timer = setInterval(() => {
    counter++;
    res.write(`id: ${counter}\ndata: ${JSON.stringify({ tick: counter })}\n\n`);
  }, 1000);

  req.on('close', () => clearInterval(timer)); // client left: stop working
});

And in the browser:

JavaScript
const source = new EventSource('/events');
source.onmessage = (event) => {
  console.log(JSON.parse(event.data));
};
source.addEventListener('error', () => console.log('reconnecting...'));
// source.close() when you no longer need it

Three details matter. Use res.write, not res.send or res.json, because those end the response. Always clean up in the close event, or every disconnected client leaves a timer or listener running forever. And disable response compression and proxy buffering for this route, because they hold messages back until a buffer fills (for nginx, proxy_buffering off or an X-Accel-Buffering: no header).

Try it: a stream and a reader

EventSource exists only in browsers, but SSE is just text, so Node's fetch can read the stream. The server sends three events and then ends the stream. The client reads chunks and prints each message.

Node.js A server that streams three events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the headers arrive first (the content type line prints before any event) and that messages are separated by blank lines. A single network chunk can hold half a message or several, which is why the reader buffers text and splits on \n\n. EventSource does that for you in the browser.

Broadcasting to many clients

Real apps push the same event to everybody who is subscribed. Keep a Set of open responses, add on connect, remove on close, and write to all of them when something happens. Here an ordinary POST route triggers a broadcast:

Node.js Broadcast to every subscriber

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both readers receive hello and then news, and after they abort, the close handler empties the set. In a multi-server deployment a Set in memory only knows its own server's clients, so you connect servers through a shared message bus such as Redis pub/sub. Keep SSE connections healthy with a comment line every 20 to 30 seconds (res.write(': ping\n\n')) so proxies do not close idle connections.

WebSockets: when you need two-way

SSE is one-way (server to client) and text only. If the client must also send frequent messages, or you need binary data, use WebSockets. A WebSocket starts as an HTTP request with an Upgrade: websocket header, and then the same TCP connection switches to a message protocol. Express itself does not handle upgrades, so you attach a library to the http.Server that app.listen returns.

With the lightweight ws package:

JavaScript
import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
const server = app.listen(3000);
const wss = new WebSocketServer({ server });

wss.on('connection', (socket) => {
  socket.on('message', (data) => {
    for (const client of wss.clients) {
      if (client.readyState === 1) client.send(data.toString()); // echo to everyone
    }
  });
});

With socket.io, a higher-level library, you get rooms, acknowledgements, automatic reconnection and a fallback transport:

JavaScript
import { createServer } from 'node:http';
import { Server } from 'socket.io';

const httpServer = createServer(app);
const io = new Server(httpServer, { cors: { origin: 'https://app.example.com' } });

io.on('connection', (socket) => {
  socket.join('lobby');
  socket.on('chat', (text) => io.to('lobby').emit('chat', { from: socket.id, text }));
});

httpServer.listen(3000);

socket.io has its own protocol, so its clients and servers must be used together; a plain browser WebSocket cannot talk to it. See WebSockets in Node.js for the protocol in detail.

Choosing

Need Best fit
Notifications, live feeds, job progress SSE
Chat, multiplayer, collaborative editing WebSocket (ws or socket.io)
Updates every minute or so Plain polling
Rooms, reconnection and fallbacks out of the box socket.io
Smallest dependency and binary data ws

Authenticate real-time connections just like normal requests: SSE sends cookies automatically (and EventSource cannot set an Authorization header), while a WebSocket needs you to check the session or token during the upgrade. Each open connection costs memory, so limit connections per user and watch file descriptor limits when you scale up (Deployment and Production).

Browsers allow only about six HTTP/1.1 connections per host, and every SSE stream uses one. HTTP/2, which a reverse proxy normally provides, removes that limit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Content-Type marks a Server-Sent Events response?

    The browser's EventSource only accepts responses that declare text/event-stream.
  2. 2. Why should an SSE route use res.write instead of res.json?

    res.json sends one body and finishes. A stream needs to stay open and be written to many times.
  3. 3. What must you do when a client disconnects from an SSE route?

    Without cleanup, timers and stored responses for gone clients pile up and leak memory.
  4. 4. Which feature suits WebSockets better than SSE?

    WebSockets are two-way. SSE only carries messages from the server to the client.

Summary

  • SSE is a never-ending HTTP response with Content-Type: text/event-stream; messages end with a blank line.
  • Write with res.write, flush headers, and clean up in req.on('close').
  • EventSource reconnects automatically and can resume with Last-Event-ID.
  • Broadcasting means keeping a set of open responses; use Redis pub/sub across several servers.
  • Use ws or socket.io for two-way messaging, attached to the http.Server from app.listen.
  • Turn off buffering and compression on streaming routes, and authenticate connections.

Next: Testing Express Apps.