HTTP/2 and Server-Sent Events in Node.js
How HTTP/2 multiplexes many streams over one connection and why Server-Sent Events are often a simpler answer to live data than WebSocket – with a working SSE endpoint in Node and the usual pitfalls.
WebSocket is not a protocol for live data. It is a bidirectional channel that happens to handle live data too – and if you open it, you pay for the return channel whether you use it or not: hand-written reconnect logic, upgrade support at every hop, custom timeouts for long-lived connections, and in a cluster usually sticky sessions and a pub/sub layer on top. For a stock ticker, a build progress bar or a notification bar, exactly one direction of that channel is ever in use.
That makes the choice of transport a design decision with direct consequences for operations and testing, not a matter of taste. It depends on three axes: the direction of the data, the operating environment and testability. If you reach for a transport by reflex, you pay later in more code, more infrastructure and more home-grown error handling – not with the first endpoint, but with every feature that hangs off the channel afterwards. Before we get to Server-Sent Events, it is worth a quick look at the layer underneath, because HTTP has changed more in recent years than most of us notice in daily work.
What HTTP/2 changes at the foundation#
For years our mental model of HTTP was as simple as it gets: one request, one connection, one response. HTTP/1.1 stretched that a bit with keep-alive and pipelining, but at its core a TCP connection could still only serve one request at a time in any useful way. For years the browser worked around this with brute force: it opened up to six parallel connections per origin. Six. If you have ever built a page with a hundred small assets, you know what that bottleneck feels like.
HTTP/2 turns this model around. Instead of many connections there is a single one, and many independent streams run in parallel over that one connection – this is called multiplexing. Each stream carries exactly one request/response, and all of them share the same TCP tunnel. This removes head-of-line blocking at the application level, and the artificial limit of six per origin is no longer an issue. Most implementations allow 100 concurrently open streams (SETTINGS_MAX_CONCURRENT_STREAMS) – the HTTP/2 specification recommends this as a minimum – and the value is configurable.
graph LR
subgraph HTTP1["HTTP/1.1 – six connections"]
C1[Client] -->|Connection 1| S1[Server]
C1 -->|Connection 2| S1
C1 -->|Connection 3| S1
C1 -->|... up to 6| S1
end
subgraph HTTP2["HTTP/2 – one connection, many streams"]
C2[Client] -->|Stream 1<br/>Stream 3<br/>Stream 5| S2[Server]
endTwo more things matter in practice. First, HTTP/2 compresses headers with HPACK. If you have ever captured traffic and seen how often the same cookie and user agent headers travel over the wire, you can guess how much redundancy is in there. HPACK keeps a static and a dynamic table for this and refers to recurring headers only by index instead of spelling them out again.
Second, there is server push – and by now I am explicitly cautious about it. The idea was charming: the server sends along resources it knows the client will need shortly, before the client even asks. In practice it was hard to use correctly, it often wasted bandwidth, and Chrome removed HTTP/2 server push by default with version 106 in 2022. The feature is still there in Node’s http2 module, but today I would not advise anyone to build an architecture on it. If you want preloading, you are better served by preload hints and 103 Early Hints.
An important point for the browser context: browsers speak HTTP/2 practically only over TLS with ALPN negotiation to h2. The Node module does support unencrypted h2c, but for anything a browser is supposed to touch, you need certificates.
The http2 module in Node#
Node ships HTTP/2 as its own core module, node:http2, stable since the early Node 10 days. When this post was published, 18, 20 and 22 were the relevant release lines; in July 2026, 22 and 24 are LTS and 26 is Current. The module is available without a flag. There are two ways to work with it. The first is the native core API built around streams:
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const server = createSecureServer({
key: readFileSync('localhost-key.pem'),
cert: readFileSync('localhost-cert.pem'),
});
server.on('stream', (stream, headers) => {
const path = headers[':path'];
stream.respond({
':status': 200,
'content-type': 'text/plain; charset=utf-8',
});
stream.end(`you requested ${path}`);
});
server.listen(8443);
What stands out are the pseudo headers with a leading colon and in lower case: :status, :method, :path, :scheme, :authority. They are the HTTP/2 replacement for the old status line and the classic request metadata. The stream event is the heart of it – for every incoming stream you get your own duplex object.
The second way is the compatibility API. It mimics req/res the way you know them from the old http module, so existing HTTP/1 code keeps running almost unchanged:
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const server = createSecureServer(
{
key: readFileSync('localhost-key.pem'),
cert: readFileSync('localhost-cert.pem'),
},
(req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('ok');
},
);
server.listen(8443);
On the client side you connect with http2.connect(authority) and send requests via client.request({ ':path': '/' }). If you want to dig deeper into Node internals and how they interact with the event loop, my Node.js training gives you the right foundation.
Server-Sent Events: the one-way stream#
Now to the actual core. In a great many live applications, data flows almost entirely in one direction: the server has something new, and the client should learn about it. A stock ticker, a build progress bar, a notification bar, a live log. For all of these you need no bidirectional channel, no protocol upgrade and no custom reconnect logic. You need Server-Sent Events.
SSE is not a special module and not a new protocol. It is ordinary HTTP with a particular content type: text/event-stream. The server keeps the response open and keeps writing new events into it in a simple line format. The browser has a native client for it in EventSource, and – this is the real charm – that client reconnects on its own when the connection drops.
The wire format is deliberately plain. A message consists of fields, each on its own line, and ends with a blank line:
data: hello world
event: tick
data: {"count":42}
id: 42
: this is a keep-alive comment
The most important fields are data: for the payload, event: for a named event type, id: for a sequential identifier and retry: for the reconnect delay in milliseconds. Lines that start with a colon are comments and work well as a keep-alive ping. What matters is the double line break, the \n\n, at the end of every message – if you forget it, the event is simply never delivered.
sequenceDiagram
participant B as Browser (EventSource)
participant S as Node Server
B->>S: GET /events
S-->>B: 200 text/event-stream
loop every 1s
S-->>B: data: { ... }<br/>(response kept open)
end
Note over B,S: Connection drops
B->>S: GET /events<br/>Last-Event-ID: 42
S-->>B: 200 text/event-stream<br/>(resumes from id 42)An SSE endpoint in Node#
The code is pleasantly short. What matters are the response headers, flushing immediately and – most people miss this the first time – cleaning up when the client closes the connection.
import { createServer } from 'node:http';
const server = createServer((req, res) => {
if (req.url !== '/events') {
res.writeHead(404).end();
return;
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.flushHeaders();
let count = 0;
const timer = setInterval(() => {
count += 1;
const payload = { count, time: Date.now() };
res.write(`id: ${count}\n`);
res.write(`event: tick\n`);
res.write(`data: ${JSON.stringify(payload)}\n\n`);
}, 1000);
req.on('close', () => {
clearInterval(timer);
});
});
server.listen(3000);
The req.on('close', ...) handler is not optional. Without it, the setInterval keeps happily running even when the browser closed the page long ago. The handler then writes into a dead connection, the timer stays around, and with many clients you have a real memory leak. In projects, this is the bug I run into most reliably – the endpoint works fine on the happy path, and only under load does anyone notice that nothing gets cleaned up.
On the browser side, the client is almost unremarkable:
const es = new EventSource('/events');
es.onmessage = (event) => {
// fires for messages without an explicit event: field
console.log('default message', event.data);
};
es.addEventListener('tick', (event) => {
const payload = JSON.parse(event.data);
render(payload);
});
es.onerror = (err) => {
// EventSource reconnects on its own; log and let it recover
console.warn('connection lost, reconnecting…', err);
};
// later, when you no longer need it
// es.close();
The point that matters most to me here: you do not have to build the reconnect yourself. EventSource remembers the last id: it saw and sends it along in the Last-Event-ID header when it reconnects. If your server reads this header, it can pick up seamlessly from the last message. The retry: field controls how long the browser waits before trying again.
The pitfall that is guaranteed to catch you#
There is one classic, and I have seen it live often enough to spell it out here: reverse proxy buffering. In development, everything runs against the bare Node process and works flawlessly. As soon as nginx sits in front of it, the events suddenly no longer arrive one by one every second, but bundled and delayed – or seemingly not at all. The reason: nginx buffers response bodies by default, and to the buffer a text/event-stream is at first just a body that is not finished yet.
The fix is the response header X-Accel-Buffering: no, which nginx recognizes and then turns off buffering for that one response. Alternatively, you set proxy_buffering off; in the nginx configuration. That is why this header is already in the example above – not because every environment needs it, but because it saves you exactly the debugging afternoon that would otherwise inevitably come.
Two more stumbling blocks belong here. First, the format mentioned earlier: you have to either split line breaks inside the payload across several data: lines or avoid them – a raw \n in the middle of the JSON tears the message apart. Second, a limitation of EventSource itself: the native client can only do GET and cannot set custom headers. Authentication therefore typically runs through cookies or a token in the query string, not through an Authorization header.
When SSE and when WebSocket#
The deciding factor is the direction of the data. Here is the comparison that pins it down:
- Direction: SSE is one-way, server to client. WebSocket is fully bidirectional.
- Protocol: SSE is ordinary HTTP with a special content type. WebSocket needs a protocol upgrade of the connection.
- Reconnect: Built into SSE, including
Last-Event-ID. With WebSocket you build it yourself. - Payload: SSE carries UTF-8 text only. WebSocket handles text and binary data.
- Infrastructure: SSE runs through normal proxies, auth and compression. WebSocket needs upgrade support everywhere.
- Typical use: SSE for notifications, live feeds and progress indicators. WebSocket for chat, games and collaborative editors.
If the client mostly just listens, SSE is enough. Only when you need a real low-latency return channel – the user types, clicks, moves a game piece – is WebSocket the right investment. For everything else, SSE means less code, less infrastructure fiddling and less home-grown error handling.
Choosing a transport as a design decision#
The comparison above answers the question of data direction. In practice, though, direction alone rarely decides; what the choice costs in operations and testing does. Three axes carry the decision, and you can walk through them in this order.
First, data direction, because it is the hardest constraint. If traffic flows mainly from server to client, the return channel of WebSocket is dead weight that still needs looking after. If it flows both ways with low latency, SSE is the wrong tool, and any attempt to rebuild the return channel with a second HTTP request quickly gets more unpleasant than a clean WebSocket. This axis is not a matter of taste; it determines which capability you need at all.
Then the operating environment, because it decides the running costs. SSE is ordinary HTTP. It runs through the same reverse proxies, load balancers, auth layers and compression stages as any other request, and your existing monitoring sees it without special treatment. WebSocket requires upgrade support at every hop, custom timeouts for long-lived connections and often sticky sessions so that a client stays with its backend. All of that is manageable, but it is extra operational surface someone has to maintain. If you scale horizontally, you notice the difference first: an SSE connection is a stream that any node can end and the client can reestablish, while a WebSocket cluster usually needs its own pub/sub layer so that an event also reaches the node the recipient is connected to.
Finally, testability, because it sets your development cycles. I test an SSE endpoint with tools that are already there. A curl -N http://localhost:3000/events shows the raw stream in the terminal, and in a browser test the native EventSource is enough to check events and reconnects. A WebSocket channel usually needs its own client library in the test setup and more choreography to cover the handshake, the bidirectional flow and the home-grown reconnect. That does not show up with the first line, but with every feature afterwards that hangs off the channel.
Economically, the math is unspectacular and that is exactly why it matters. The cheaper transport is the one that touches fewer outside systems and can be tested with built-in tools. For a live feed, a progress bar or a notification bar, that almost always means SSE: shorter cycles, because less infrastructure is involved, and less friction in operations, because nothing new has to be monitored. The limit is just as clear. As soon as real interaction with a return channel comes into play, WebSocket earns back its higher operating costs with a capability SSE simply does not have. Making the choice deliberately costs a few minutes of thought once. Making it by reflex costs considerably more over the lifetime of the system.
SSE and HTTP/2 together#
And this brings us full circle. SSE does not need HTTP/2 – it runs perfectly happily over HTTP/1.1. But it benefits from it. Over HTTP/1.1, every open SSE connection counts against the browser’s limit of six per origin. If you work with several tabs or several parallel streams, you hit that quickly. Over HTTP/2, on the other hand, open SSE connections are streams within one connection. How many of them may be open at the same time is negotiated by the peer via SETTINGS_MAX_CONCURRENT_STREAMS; RFC 9113 recommends at least 100 but does not guarantee that value. The rigid HTTP/1.1 limit usually becomes much less relevant as a result.
Because SSE is a long-lived stream that delivers data in small pieces, it is also worth looking at how Node handles streams internally and what happens when a client reads more slowly than the server writes. If you serve many clients, you should understand backpressure – my post on Node.js streams and backpressure fits right in.
HTTP/2 has relaxed the transport layer so much that many old optimization tricks have become unnecessary, and Server-Sent Events bring exactly as much complexity as a one-way stream needs – not a bit more. The boundary stays sharp: as soon as data really flows in both directions, WebSocket is the right investment. It just flows both ways less often than the first reflex suggests. If you walk through the three axes once before you commit, in the best case you save yourself an entire pub/sub layer.
Further reading#
- Node.js training and Node.js streams and backpressure – the matching foundations from my blog.
- Node.js HTTP/2 module – core API, compatibility API,
createSecureServer,pushStream. - MDN: Using server-sent events – SSE in practice.
- MDN: EventSource – the EventSource interface in detail.
- WHATWG: Server-sent events – the specification of the
text/event-streamformat. - RFC 9113 (HTTP/2) and RFC 7541 (HPACK) – the underlying standards.
Revised and translated from German with the help of AI.