How to Implement Server-Sent Events in Node.js
Build a production Server-Sent Events endpoint in Node.js with heartbeats, reconnection, Last-Event-ID replay, and correct proxy and buffering headers.
On this page
Introduction
Server-Sent Events (SSE) is a one-way streaming protocol that lets a server push text messages to a browser over a long-lived HTTP connection. Unlike polling, the server sends data only when it changes; unlike WebSockets, the client needs no special protocol and the browser reconnects automatically. The transport is plain HTTP with the text/event-stream content type, which means it passes through proxies, CDNs, and corporate firewalls that block upgrade handshakes.
This tutorial builds a production SSE endpoint in Node.js with TypeScript. It covers the wire format, the streaming response, heartbeat and lifecycle handling, reconnection with event replay, backpressure, the proxy and buffering settings that break naive implementations, and the tests that prove the boundary behavior. The same ideas apply in Fastify, Express, or a plain http server; the examples use a framework-agnostic handler that writes to the raw response.
The SSE wire format
SSE is a line-based text protocol. Each message is a group of fields terminated by a blank line. The fields are data:, event:, id:, and retry:. A message with a data field carries the payload; a message with an event field names a custom event type the client can listen for; an id field sets the last event identifier; and a retry field tells the client how many milliseconds to wait before reconnecting after a drop.
A single data payload may span multiple data: lines, which the browser joins with newline characters. A line that starts with a colon is a comment and is ignored, which is the mechanism used for heartbeats. The blank line is not optional: without it, the client buffers the fields and never dispatches the event. Payloads must not contain a bare carriage return, because that character can be interpreted as a frame boundary and corrupt the stream.
// Serialize a value into one SSE frame. Keep payloads free of raw \r\n boundaries.
function sseFrame(event: string, data: unknown, id?: string): string {
const payload = JSON.stringify(data);
const lines = [`event: ${event}`];
if (id !== undefined) lines.push(`id: ${id}`);
// A payload with newlines is split into multiple data: lines.
for (const line of payload.split('\n')) lines.push(`data: ${line}`);
return lines.join('\n') + '\n\n';
}
Stream from the server
The response must declare Content-Type: text/event-stream, disable caching, and avoid compression that delays flushing. Writing a chunk that is smaller than the compression buffer means the client sees nothing until the buffer fills or the connection closes, which defeats the point of streaming. The clean approach is to skip compression for the SSE route and to write frames directly to the socket.
import type { Request, Response } from 'express';
const clients = new Set<Response>();
function sseHandler(req: Request, res: Response) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no', // nginx: do not buffer this response
});
// Hint the browser to retry after 3 seconds if the stream drops.
res.write('retry: 3000\n\n');
clients.add(res);
const cleanup = () => clients.delete(res);
req.on('close', cleanup);
res.on('error', cleanup);
}
function broadcast(event: string, data: unknown) {
const frame = sseFrame(event, data);
for (const res of clients) {
if (!res.write(frame)) {
// Backpressure: this client is slow; drop it rather than buffer forever.
clients.delete(res);
res.end();
}
}
}
Startup and shutdown matter too. On SIGTERM, stop accepting new clients, write a final event: shutdown frame so reconnecting clients know why, and close each response after a short grace period. A server that is killed without draining leaves clients reconnecting against a process that is already gone.
Heartbeats and connection lifecycle
Idle connections are closed by intermediaries: load balancers, reverse proxies, and NAT devices all drop sockets that send nothing for a period. A comment heartbeat every 15 to 30 seconds keeps the socket warm and lets the client detect a dead peer. The heartbeat should be a single colon line, not a data event, so application code never sees it.
const heartbeat = setInterval(() => {
for (const res of clients) res.write(': heartbeat\n\n');
}, 20_000);
// Always clear the timer when the process stops.
process.on('SIGTERM', () => {
clearInterval(heartbeat);
for (const res of clients) {
res.write(sseFrame('shutdown', { reason: 'server_restart' }));
res.end();
}
});
Track each client so you can clean up on disconnect, and never leak a subscription. A common bug is registering a database listener or message-broker subscription per connection and forgetting to remove it on close; after a few reconnects the process is holding hundreds of dead listeners and memory grows without bound. Tie every subscription to the response lifecycle.
Reconnection and Last-Event-ID
When the connection drops, the browser reconnects automatically after the retry interval and sends a Last-Event-ID request header containing the last id it received. The server can use that header to replay events the client missed. This turns SSE from “best effort” into “at-least-once within a bounded window,” which is what a notifications or audit feed needs.
function replaySince(lastId: string | undefined, buffer: { id: string; frame: string }[]) {
if (!lastId) return [];
const index = buffer.findIndex((e) => e.id === lastId);
// lastId not in the buffer means the gap is older than our retention: client must resync.
if (index === -1) return null;
return buffer.slice(index + 1);
}
Keep the replay buffer bounded by both count and time, and make event ids monotonic and opaque. If the requested Last-Event-ID is no longer available, the honest response is to send a resync event that tells the client to refetch full state, rather than silently skipping messages. Browsers do not send Last-Event-ID on the first connection, so never require it.
Backpressure and slow clients
res.write returns false when the socket buffer is full, which is the signal that the client cannot keep up. For a broadcast feed, the correct response is to drop the slow client, not to buffer frames in memory: a single stalled reader must not be allowed to grow the server’s heap. Distinguish between a slow consumer and a disconnected one by checking res.writableEnded. Set a maximum frame size and consider a per-client queue with a hard cap; when the cap is exceeded, close the connection and let the client reconnect and replay from its Last-Event-ID. This keeps memory bounded and makes the failure visible in the client’s reconnect logic instead of invisible in the server’s heap.
Proxies, buffering, and HTTP version
The single most common reason an SSE endpoint “does not work in production but works locally” is buffering. nginx buffers proxied responses by default; the X-Accel-Buffering: no header disables it. A CDN or WAF may buffer as well, so test through the real edge. Compression middleware that wraps res.write must be bypassed for the stream. HTTP/2 multiplexes all requests over one TCP connection, which removes the HTTP/1.1 six-connection-per-domain limit but introduces a per-stream flow-control window: a slow client can still block one stream, and connection-level flow control can affect siblings. Many servers also impose an idle timeout; the heartbeat is what keeps the stream alive under that timeout.
Testing and failure paths
Test the wire format first: unit-test sseFrame for multi-line payloads, missing ids, and escaped content. Then test the transport with a real server: open a connection, read the first frame, assert the blank-line terminator, and verify the heartbeat arrives on schedule.
test('delivers a framed event and a heartbeat', async () => {
const server = await startTestServer();
const res = await fetch(server.url, { headers: { Accept: 'text/event-stream' } });
const reader = res.body!.getReader();
const decoder = new TextDecoder();
const chunks: string[] = [];
const readUntil = async (predicate: (s: string) => boolean) => {
while (true) {
const { value, done } = await reader.read();
if (done) return null;
chunks.push(decoder.decode(value, { stream: true }));
const joined = chunks.join('');
if (predicate(joined)) return joined;
}
};
const first = await readUntil((s) => s.includes('\n\n'));
expect(first).toContain('event: message');
await server.emit('message', { ok: true });
const delivered = await readUntil((s) => s.includes('"ok":true'));
expect(delivered).toContain('data: {"ok":true}');
await server.close();
});
Cover the failure paths: client disconnect mid-stream (server cleans up the subscription), Last-Event-ID replay, an id older than the buffer (client told to resync), and a slow reader that is dropped. Assert that the number of tracked clients returns to zero after each disconnect; a leak here is the bug that takes down the process hours later.
Common pitfalls
- Forgetting the blank-line terminator. The client buffers fields and never dispatches an event.
- Compression middleware. It buffers small frames, so the stream appears frozen.
- No heartbeat. Idle connections are reaped by proxies and the client thrashes on reconnect.
- Unbounded replay buffers. Memory grows without limit; bound by count and age.
- Not cleaning up. Dead subscriptions and listeners leak on every reconnect.
- Buffering for slow clients. One slow reader grows server memory; drop it instead.
- Raw carriage returns in payloads. They corrupt framing; strip or escape them.
Conclusion
A robust SSE endpoint is a small protocol implementation plus disciplined lifecycle management. Emit well-formed frames with a blank-line terminator, disable buffering and compression on the stream, send heartbeats to survive idle timeouts, track and clean up every client, and use Last-Event-ID with a bounded buffer to make reconnects lossless within a window. Test the wire format, the disconnect path, and the slow-client path, because those are where naive implementations fail in production. Follow these rules and SSE gives you reliable server push over ordinary HTTP, with the browser’s own reconnect logic doing the hard part.
Sources: MDN: Using server-sent events, WHATWG HTML Standard: Server-sent events, Node.js HTTP documentation.
FAQ
- Are Server-Sent Events better than WebSockets?
- SSE is one-directional, runs over plain HTTP, reconnects automatically, and traverses proxies and CDNs with less friction. WebSockets are bidirectional with lower per-message overhead. Choose SSE for server-to-client updates such as notifications, feeds, or progress; choose WebSockets when the client must also push frequent messages over the same channel.
- Why does my EventSource reconnect every few seconds?
- A proxy, load balancer, or server is closing the connection because it looks idle or because the response is buffered. Send a comment heartbeat every 15 to 30 seconds, set the retry field, and disable gzip and buffering for the stream so bytes flush immediately.
- How many SSE connections can one Node.js process hold?
- Each connection holds a socket and a small amount of memory. A single Node.js process can often hold tens of thousands of idle connections, but file descriptor limits, reverse-proxy limits, and the browser's per-domain connection cap throttle the practical number for one user.
Report a problem with this articleOpens a pre-filled issue on GitHub.