Skip to main content

APIs · Intermediate · 22 min

Stream live updates to the browser with server-sent events

By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS (node:26 image) · checked in Chromium with Playwright 1.65.1

You will build a Node.js 26 server that streams order-status updates as server-sent events, a live status page that reconnects with Last-Event-ID without losing an update, and the Nginx settings that keep the stream flowing, checked with curl and Playwright.

On this page

A customer pays for an order and wants to see it move from paid to packed to out for delivery without pressing refresh. The server knows when the status changes; the browser does not. Server-sent events (SSE) close that gap with one long-lived HTTP response. The browser opens it with the built-in EventSource object, the server writes a small text block each time something happens, and if the connection drops, the browser reconnects by itself and tells the server the last update it saw.

Before you build one, it helps to know where SSE fits among the three common ways to get fresh data into a page:

  • Polling asks the server every few seconds. It works everywhere and suits data that changes rarely, but most requests come back with nothing new, and updates arrive late by up to one interval.
  • Server-sent events push text from server to browser over plain HTTP. Reconnection and resuming are built in, and proxies, cookies and HTTP/2 work as for any other request. The browser cannot send messages back on the same connection; it uses ordinary fetch calls for that.
  • WebSockets give a two-way channel for binary or text messages. They suit chat, games and collaborative editing, where the browser talks as much as it listens, and they need their own upgrade handling, reconnection logic and message format.

Order tracking, build logs, live scores, dashboards and notifications are one-way, so SSE is usually the simplest fit. In this tutorial you write a Node.js server with no framework, stream an order's status to curl and then to a web page, prove that a dropped connection loses nothing, and set up Nginx so it does not hold the stream back. Every step is checked with curl, and the page with a short Playwright script.

Step 1 · Create the project

Make a throwaway folder and install Playwright 1.65 at an exact version. The server itself uses only Node.js; Playwright is there to check the page in a real browser. On Linux, --with-deps also installs the system libraries Chromium needs and may ask for your sudo password:

Bash
mkdir -p ~/sse-demo/public
cd ~/sse-demo
npm init -y > /dev/null
npm pkg set type=module
npm install playwright@1.65.1
npx playwright install --with-deps chromium

The Chromium download is 100 to 200 MB. On a metered or prepaid mobile connection, run it on Wi-Fi.

Check it worked

Bash
cd ~/sse-demo
node --version
npm ls playwright

node --version prints v26.13.1 or a later 26 release, and the tree lists playwright@1.65.1.

Step 2 · Write the stream server

Create server.mjs. It keeps every status change for one order in a list, each with a number that only goes up. That number becomes the event id, which is what makes resuming possible later. The server has five routes:

  • GET / serves the status page from public/index.html, which you write later.
  • GET /events is the stream.
  • GET /stats reports how many streams are open, so you can see the server clean up.
  • POST /advance moves the order to its next status, standing in for your payment or warehouse code.
  • POST /drop ends every open stream, to imitate a network cut. It is for practice only.
Bash
cd ~/sse-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';

const PORT = Number(process.env.PORT ?? 3000);
const HEARTBEAT_MS = 10_000;
const STATUSES = ['Placed', 'Paid', 'Packed', 'Out for delivery', 'Delivered'];

const updates = []; // every status change so far, oldest first
const streams = new Set(); // responses that are still open

function record(status) {
  const update = { id: updates.length + 1, order: 'PD-1024', status, at: new Date().toISOString() };
  updates.push(update);
  return update;
}
record(STATUSES[0]);

// One event in the text/event-stream format. A blank line ends it.
function toEvent({ id, order, status, at }) {
  return `id: ${id}\nevent: status\ndata: ${JSON.stringify({ order, status, at })}\n\n`;
}

function openStream(req, res) {
  const lastId = Number.parseInt(req.headers['last-event-id'] ?? '0', 10) || 0;

  res.writeHead(200, {
    'Content-Type': 'text/event-stream; charset=utf-8',
    'Cache-Control': 'no-cache',
    'X-Accel-Buffering': 'no',
  });
  res.write('retry: 3000\n\n');

  // Replay whatever this client has not seen yet.
  for (const update of updates) {
    if (update.id > lastId) res.write(toEvent(update));
  }

  streams.add(res);
  console.log(`stream opened (Last-Event-ID ${lastId}), ${streams.size} open`);

  const heartbeat = setInterval(() => res.write(': ping\n\n'), HEARTBEAT_MS);

  res.on('close', () => {
    clearInterval(heartbeat);
    streams.delete(res);
    console.log(`stream closed, ${streams.size} open`);
  });
}

function sendJson(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(body));
}

const server = createServer(async (req, res) => {
  const { pathname } = new URL(req.url, 'http://localhost');

  if (req.method === 'GET' && pathname === '/') {
    try {
      const html = await readFile(new URL('./public/index.html', import.meta.url));
      res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
      return res.end(html);
    } catch {
      return sendJson(res, 404, { error: 'write public/index.html first' });
    }
  }

  if (req.method === 'GET' && pathname === '/events') return openStream(req, res);

  if (req.method === 'GET' && pathname === '/stats') {
    return sendJson(res, 200, { clients: streams.size, lastId: updates.length });
  }

  if (req.method === 'POST' && pathname === '/advance') {
    const next = STATUSES[updates.length];
    if (!next) return sendJson(res, 409, { error: 'order already delivered' });
    const update = record(next);
    const text = toEvent(update);
    for (const stream of streams) stream.write(text);
    return sendJson(res, 200, { id: update.id, status: update.status });
  }

  if (req.method === 'POST' && pathname === '/drop') {
    const dropped = streams.size;
    for (const stream of streams) stream.end();
    return sendJson(res, 200, { dropped });
  }

  sendJson(res, 404, { error: 'not found' });
});

server.listen(PORT, () => console.log(`Status page: http://localhost:${PORT}`));
JS

Start it in your second terminal, from the same folder, and leave it running:

Bash
cd ~/sse-demo
node server.mjs

The updates live in memory, so restarting the server starts the order again from Placed. In a real app they come from your database, and the id is a row number or a sequence that never repeats.

Check it worked

The second terminal prints Status page: http://localhost:3000. In your first terminal, ask for the stats:

Bash
curl -s http://localhost:3000/stats
echo

It prints {"clients":0,"lastId":1}: no one is listening yet, and the order has one update, Placed.

Step 3 · Read the stream with curl and push an update

Open a third terminal and connect to the stream. -N turns off curl's output buffering, so each event appears the moment it arrives instead of when a buffer fills:

Bash
curl -N http://localhost:3000/events

The command does not return. It prints the reconnection delay and the one update so far, then waits:

Text
retry: 3000

id: 1
event: status
data: {"order":"PD-1024","status":"Placed","at":"2026-11-18T09:14:02.511Z"}

Now, from your first terminal, mark the order as paid:

Bash
curl -s -X POST http://localhost:3000/advance
echo

Each event is a few field: value lines followed by a blank line. The browser reads four fields:

  • data is the payload, always text. Here it is JSON. If an event has several data lines, the browser joins them with newlines.
  • event names the event, so the page can listen for status separately from other kinds. Without it, the event is called message.
  • id is remembered by the browser and sent back as the Last-Event-ID header when it reconnects.
  • retry tells the browser how many milliseconds to wait before reconnecting. It can be sent alone, as the server does at the start.

A line that starts with a colon is a comment. The browser ignores it, which makes it useful as a keep-alive, as you will see next.

Check it worked

The first terminal prints {"id":2,"status":"Paid"}. At the same moment the third terminal shows a new block with id: 2, event: status and "status":"Paid". Leave curl running for the next step.

Step 4 · Keep idle streams open and close them when clients leave

Two things go wrong with a stream that stays quiet. Proxies, load balancers and some mobile networks close connections that send nothing for a while; Nginx's default is 60 seconds. And a server only notices that a client has gone when the connection closes or a write fails, so streams can pile up. The server deals with both already:

  • Every 10 seconds it writes : ping and a blank line. That is a comment, so the page never sees it, but it counts as traffic for everything in between. Each ping is a few bytes, far less than a poll every few seconds would cost on prepaid data.
  • res.on('close', ...) runs when the client disconnects, for whatever reason. It stops the heartbeat timer and removes the response from streams, so later updates are not written to a dead connection.

The response headers matter too. Content-Type: text/event-stream is required, or EventSource refuses the stream and does not retry. Cache-Control: no-cache stops caches from storing the stream, and X-Accel-Buffering: no tells Nginx not to buffer this response.

Look at the third terminal. Within 10 seconds of connecting, a : ping line appears, then another every 10 seconds.

Now press Ctrl+C in the third terminal to stop curl, and ask for the stats again:

Bash
curl -s http://localhost:3000/stats
echo

Check it worked

The stats show {"clients":0,"lastId":2}, and the server's terminal has a line stream closed, 0 open for the curl you stopped. If the count stays above zero after clients leave, the close handler is not running and every visitor leaks a timer and a connection.

Step 5 · Build the live status page

Create public/index.html. The page opens an EventSource on /events, listens for status events, and shows the connection state so a customer can tell a live page from a stale one:

Bash
cd ~/sse-demo
cat > public/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Order PD-1024</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 32rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
    #connection { font-weight: 600; }
  </style>
</head>
<body>
  <h1>Order PD-1024</h1>
  <p>Connection: <span id="connection">Connecting</span></p>
  <p>Status: <strong id="current" aria-live="polite">Waiting for the first update</strong></p>
  <ol id="updates"></ol>

  <script>
    const connection = document.querySelector('#connection');
    const current = document.querySelector('#current');
    const list = document.querySelector('#updates');
    const source = new EventSource('/events');

    source.addEventListener('open', () => {
      connection.textContent = 'Live';
    });

    source.addEventListener('error', () => {
      // CONNECTING means the browser will try again by itself.
      connection.textContent =
        source.readyState === EventSource.CONNECTING ? 'Reconnecting' : 'Disconnected';
    });

    source.addEventListener('status', (event) => {
      // Ignore an update the page already shows.
      if (list.querySelector(`[data-id="${event.lastEventId}"]`)) return;

      const update = JSON.parse(event.data);
      current.textContent = update.status;

      const item = document.createElement('li');
      item.dataset.id = event.lastEventId;
      item.textContent = `${update.status} at ${new Date(update.at).toLocaleTimeString()}`;
      list.append(item);

      if (update.status === 'Delivered') {
        source.close();
        connection.textContent = 'Order complete';
      }
    });
  </script>
</body>
</html>
HTML

A few choices here are worth copying:

  • addEventListener('status', ...) receives only events named status. The onmessage handler would only get events with no event field.
  • The page writes with textContent, never innerHTML, so a status string can never inject markup.
  • aria-live="polite" makes screen readers announce each new status without the user moving focus.
  • When the order is delivered, the page calls source.close(). Nothing more will happen, so there is no reason to hold a connection open. A server can also stop a browser from reconnecting by answering /events with status 204 No Content.

Open http://localhost:3000 in your browser. To check it without clicking, write a Playwright script that loads the page, advances the order from Node and waits for the page to show the change:

Bash
cd ~/sse-demo
cat > check.mjs <<'JS'
import { chromium } from 'playwright';

const base = 'http://localhost:3000';
const browser = await chromium.launch();
const page = await browser.newPage();

await page.goto(base);
await page.locator('#connection', { hasText: 'Live' }).waitFor();

await fetch(`${base}/advance`, { method: 'POST' });
await page.locator('#current', { hasText: 'Packed' }).waitFor();

const ids = await page.locator('#updates li').evaluateAll((items) => items.map((li) => li.dataset.id));
console.log(`connection: ${await page.textContent('#connection')}`);
console.log(`status: ${await page.textContent('#current')}`);
console.log(`ids: ${ids.join(',')}`);

await browser.close();
JS

Run it:

Bash
node check.mjs

Check it worked

The script prints connection: Live, status: Packed and ids: 1,2,3. The tab in your own browser shows the same three updates, with Packed arriving without a reload. If the page says Disconnected instead, open the developer tools Network tab and check that /events answers 200 with Content-Type: text/event-stream.

Step 6 · Resume after a dropped connection with Last-Event-ID

Connections drop: a phone switches from Wi-Fi to mobile data, a train goes into a tunnel, a prepaid bundle runs out and is topped up, or you deploy a new version of the server. When that happens, EventSource waits for the retry delay and reconnects. Because the server sent an id with each event, the browser adds a Last-Event-ID header to the new request, and the server replays everything after it.

You can play the browser's part with curl. Ask for the stream as a client that has already seen update 1. Press Ctrl+C after a second:

Bash
curl -N -H 'Last-Event-ID: 1' http://localhost:3000/events

The output has retry: 3000 and then only events 2 and 3. Update 1 is not sent again.

Now test it in the browser. This script loads the page, cuts every stream with /drop, and advances the order while the page is offline. The update is stored but reaches no one. The page should still show it once it reconnects:

Bash
cd ~/sse-demo
cat > reconnect.mjs <<'JS'
import { chromium } from 'playwright';

const base = 'http://localhost:3000';
const browser = await chromium.launch();
const page = await browser.newPage();

await page.goto(base);
await page.locator('#connection', { hasText: 'Live' }).waitFor();

await fetch(`${base}/drop`, { method: 'POST' });
await page.locator('#connection', { hasText: 'Reconnecting' }).waitFor();
console.log('page went offline');

await fetch(`${base}/advance`, { method: 'POST' }); // nobody is connected now
await page.locator('#current', { hasText: 'Out for delivery' }).waitFor({ timeout: 10_000 });
console.log('missed update arrived after reconnecting');

await fetch(`${base}/advance`, { method: 'POST' });
await page.locator('#connection', { hasText: 'Order complete' }).waitFor();

const ids = await page.locator('#updates li').evaluateAll((items) => items.map((li) => li.dataset.id));
console.log(`ids: ${ids.join(',')}`);

let stats;
for (let i = 0; i < 20; i++) {
  stats = await (await fetch(`${base}/stats`)).json();
  if (stats.clients === 0) break;
  await new Promise((resolve) => setTimeout(resolve, 100));
}
console.log(`open streams: ${stats.clients}`);

await browser.close();
JS

Run it:

Bash
node reconnect.mjs

If you still have the page open in your own browser, it goes through the same drop and reconnect and also ends on Delivered.

Check it worked

The script prints page went offline, missed update arrived after reconnecting, ids: 1,2,3,4,5 and open streams: 0. There is no gap and no repeat in the list. In the server's terminal, look for stream opened (Last-Event-ID 3): that is the browser reconnecting about three seconds after the drop and saying where it left off.

This only works if your server can answer "what happened after id N". Keep the ids in a table or a log with an index, and keep enough history to cover a realistic outage. For a client too far behind, send the current state as one event instead of replaying everything.

Step 7 · Put the stream behind Nginx without buffering

Behind a reverse proxy, the most common SSE fault is a page that stays on Connecting for a long time and then receives a burst of events at once. Nginx buffers proxied responses by default, collecting the response before passing it on, which is right for pages and wrong for a stream. The X-Accel-Buffering: no header your server already sends turns buffering off for that response. Set it in Nginx as well, so the stream works even if a framework drops the header.

If your Node app is not behind Nginx yet, set that up first with an Nginx reverse proxy for a Node app. Then add a location for the stream inside the same server block, above the general location /:

Nginx
location /events {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection '';
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 1h;
}
  • proxy_buffering off sends each event on as soon as Node writes it.
  • proxy_http_version 1.1 and an empty Connection header keep the connection to Node open and use chunked responses, instead of HTTP/1.0 with Connection: close.
  • proxy_read_timeout 1h raises the 60-second idle limit. The 10-second heartbeat already stays under 60 seconds; the higher limit is a margin for a slow heartbeat, not a replacement for one.

Two more settings break streams elsewhere. Compression in a proxy or middleware may hold bytes back until it has a block worth compressing, so leave text/event-stream out of gzip_types and out of any compression middleware. And over HTTP/1.1, browsers allow only six connections per domain, shared by every tab; a user with seven tabs open finds the seventh stuck. Serve the site over HTTP/2, which Nginx does with http2 on; in a TLS server block, and the limit no longer bites.

Test the configuration and reload Nginx:

Bash
sudo nginx -t
sudo systemctl reload nginx

Check it worked

sudo nginx -t reports that the syntax is ok and the test is successful. From your laptop, run curl -N https://your-domain.example/events, replacing the domain with yours. The retry: 3000 line and the stored events appear at once, not after a pause, and a new update shows up the moment you advance the order.

Step 8 · Stop the server and clean up

Press Ctrl+C in the second terminal to stop the server, then remove the demo folder, which also removes the local Playwright package:

Bash
cd ~
rm -rf ~/sse-demo

The Chromium that Playwright downloaded stays in its shared cache. If you no longer need it, run npx playwright uninstall --all from any Node project. If you added the /events location to a real Nginx site for this tutorial, remove it and reload Nginx.

Check it worked

curl -s http://localhost:3000/stats prints nothing and exits with an error, because nothing is listening, and ls ~/sse-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.