SSE vs WebSockets vs long polling
Use SSE for server-to-page text updates, WebSockets for bidirectional streams, and long polling when ordinary request handling is the simplest fit.
Choose Server-Sent Events when a page mostly receives updates and can send commands through ordinary HTTP requests. Choose WebSockets when both ends need frequent messages or binary frames. Long polling fits occasional updates when you already have request-based infrastructure and can tolerate a new request after each response.
| Transport | Server-to-client | Client-to-server | Reconnection |
|---|---|---|---|
| SSE / EventSource | UTF-8 event stream | Separate HTTP requests | Browser reconnects automatically |
| WebSocket | Text or binary messages | Same connection | Application implements it |
| Long polling | Held response, then repeat | Ordinary requests | Client repeats and resumes |
Run an SSE server
Save this as sse.mjs and run node sse.mjs with Node 26. Open http://127.0.0.1:8787/. The server and client share an origin.
import { createServer } from 'node:http';
createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`<!doctype html><title>SSE demo</title><pre id="log"></pre>
<script>
const events = new EventSource('/events');
events.onmessage = e => {
document.querySelector('#log').textContent += e.lastEventId + ': ' + e.data + '\\n';
};
</script>`);
return;
}
if (req.url !== '/events') {
res.writeHead(404).end();
return;
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'X-Accel-Buffering': 'no',
});
res.flushHeaders();
res.write('retry: 2000\n\n');
let id = Number(req.headers['last-event-id'] ?? 0);
if (!Number.isSafeInteger(id) || id < 0) id = 0;
const timer = setInterval(() => {
const ok = res.write(`id: ${++id}\ndata: ${new Date().toISOString()}\n\n`);
if (!ok) res.destroy(); // Bound buffering for a slow reader.
}, 1000);
res.on('close', () => clearInterval(timer));
}).listen(8787, '127.0.0.1');
From another terminal:
curl -N --max-time 3 http://127.0.0.1:8787/events
curl -N --max-time 3 -H 'Last-Event-ID: 7' \
http://127.0.0.1:8787/events
The timeout deliberately ends this infinite response. -N disables curl’s output buffering. Every message ends with a blank line; an id: field updates EventSource’s resume cursor. A retry: field sets its reconnection delay in milliseconds. Call events.close() when your UI no longer needs the stream.
Resume means more than reconnect
This demo continues numbering after the supplied ID but does not replay missed events. For real recovery, keep a bounded event log, associate IDs with persisted events, and replay entries after Last-Event-ID. Define what happens when the cursor is too old, such as sending a snapshot and a new cursor. Authorize each connection independently; a resume ID is not a session token.
Native EventSource cannot set arbitrary authorization headers. Same-origin cookies work; cross-origin credentials need the corresponding CORS policy and withCredentials option. Avoid putting long-lived credentials in query strings.
Check the proxy path
Disable response buffering and ensure idle timeouts exceed your heartbeat interval. An SSE comment such as : keepalive\n\n keeps an otherwise idle stream active. Nginx recognizes X-Accel-Buffering: no unless configured to ignore it; see its buffering documentation.
HTTP/1.1 browser connection pools can make multiple streams across tabs compete with other requests. HTTP/2 multiplexes streams on a connection, but concurrent-stream limits remain negotiated and implementation-dependent. Neither HTTP/2 nor HTTP/3 fixes application backpressure or a proxy that buffers the response.
The EventSource standard defines framing and reconnect behavior; Node’s HTTP API defines streaming writes. Go deeper with WebSocket production concerns and HTTP/3 streams.