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
fetchcalls 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:
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 chromiumThe Chromium download is 100 to 200 MB. On a metered or prepaid mobile connection, run it on Wi-Fi.
Check it worked
cd ~/sse-demo
node --version
npm ls playwrightnode --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 frompublic/index.html, which you write later.GET /eventsis the stream.GET /statsreports how many streams are open, so you can see the server clean up.POST /advancemoves the order to its next status, standing in for your payment or warehouse code.POST /dropends every open stream, to imitate a network cut. It is for practice only.
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}`));
JSStart it in your second terminal, from the same folder, and leave it running:
cd ~/sse-demo
node server.mjsThe 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:
curl -s http://localhost:3000/stats
echoIt 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:
curl -N http://localhost:3000/eventsThe command does not return. It prints the reconnection delay and the one update so far, then waits:
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:
curl -s -X POST http://localhost:3000/advance
echoEach event is a few field: value lines followed by a blank line. The browser reads four fields:
datais the payload, always text. Here it is JSON. If an event has severaldatalines, the browser joins them with newlines.eventnames the event, so the page can listen forstatusseparately from other kinds. Without it, the event is calledmessage.idis remembered by the browser and sent back as theLast-Event-IDheader when it reconnects.retrytells 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
: pingand 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 fromstreams, 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:
curl -s http://localhost:3000/stats
echoCheck 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:
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>
HTMLA few choices here are worth copying:
addEventListener('status', ...)receives only events namedstatus. Theonmessagehandler would only get events with noeventfield.- The page writes with
textContent, neverinnerHTML, 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/eventswith status204 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:
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();
JSRun it:
node check.mjsCheck 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:
curl -N -H 'Last-Event-ID: 1' http://localhost:3000/eventsThe 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:
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();
JSRun it:
node reconnect.mjsIf 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 /:
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 offsends each event on as soon as Node writes it.proxy_http_version 1.1and an emptyConnectionheader keep the connection to Node open and use chunked responses, instead of HTTP/1.0 withConnection: close.proxy_read_timeout 1hraises 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:
sudo nginx -t
sudo systemctl reload nginxCheck 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:
cd ~
rm -rf ~/sse-demoThe 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
- Handle the first load, slow responses and errors around a stream in fetch JSON and show it with loading and error states.
- Decide which API responses may be cached and which, like a stream, never should, in set caching headers for API responses.
- Put the server behind a proper proxy with TLS in an Nginx reverse proxy for a Node app.
- Practise more curl flags for inspecting APIs in test an API with curl.
Part of these paths
Related tutorials
- Fetch JSON from an API and show it with loading and error statesYou will build a market price search that loads JSON with fetch, shows loading, empty, error and success states, gives up after five seconds and never shows results out of order.
- Cache API responses with Cache-Control and ETagsYou will give each endpoint of a small Node.js 26 API its own Cache-Control policy, add ETag and Last-Modified validators that answer 304 Not Modified, compress large responses with the right Vary header, and finish with a script that checks the policy for every endpoint.
- How to Put Nginx in Front of a Node.js App as a Reverse ProxyYou will install Node.js 26, run a small app on a local port, and configure Nginx 1.30 to pass public traffic to it with the headers your app needs.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials