Skip to content

WebSockets and server-sent events

Working knowledgeUnder the hood

HTTP lets the server answer, never speak first, yet chat messages and live comments appear the instant they are sent. Here is how: a connection kept open, either as a response that never ends or as a socket upgraded from HTTP, drawn message by message.

01 HTTP only ever answers

A chat or a live comment feed needs the server to say "something happened" the moment it happens. Plain HTTP cannot do that: the client sends a request, the server sends one response, and the exchange is over. The server has no way to start a conversation.

The first workaround is polling: ask again every few seconds.

Polling every few seconds for new comments
Short polling (example)
BrowserServerGET /comments?after=41200 []GET /comments?after=41200 []GET /comments?after=41200 [comment 42]
  • nothing new
  • news, late

Two of three round trips carried nothing, and comment 42 waited up to one full interval before anyone asked for it.

Long polling improves on it: the server holds each request open until it has news (or a timeout passes), answers, and the client immediately asks again. Latency drops, but every message still costs a fresh request with full headers. The real fix is to keep one connection open and let the server write to it whenever it likes. There are two standard ways.

PollingUp to one interval lateSimple and works everywhere, but wastes requests when nothing changes and delays news when something does.
Long pollingOne request per messageNews arrives quickly, but each message needs a new request, and every waiting client holds a request open.
SSE or WebSocketOne connection, many messagesThe connection stays open and the server writes whenever it has something. The cost moves to keeping many connections alive.

02 Server-sent events: a response that never ends

Server-sent events (SSE) is the smaller idea. The browser makes one normal GET, and the server sends headers and then keeps the response body open, writing a short text block each time there is news. The browser’s EventSource object reads those blocks and fires an event for each.

Server-sent events, with one dropped connection
Step 1 of 9
One SSE connection (example events)
BrowserServerNothing sent yet
EventSource in the browser
readyState→0 CONNECTINGlastEventId→none
  • just sent
  • just changed
  • lost

The page runs new EventSource('/events'). Nothing has been sent yet, and the object starts in state 0, CONNECTING.

On the wire an event is just lines of text, ended by a blank line. data: is the payload, id: is what the browser echoes back in Last-Event-ID, event: gives it a name, and retry: sets the reconnect delay in milliseconds. A line starting with : is a comment, which servers send as a heartbeat.

HTTP
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 1
data: {"user":"ana","text":"hi"}
: heartbeat
id: 2
event: typing
data: {"user":"bo"}
feed.js
const source = new EventSource('/events');
// Events with no `event:` line arrive as "message".
source.onmessage = (e) => showComment(JSON.parse(e.data));
// Named events need their own listener.
source.addEventListener('typing', (e) => showTyping(JSON.parse(e.data)));

The browser only sends Last-Event-ID. Resuming is your job: the server has to keep recent events (in memory, Redis or the database) and replay everything after that id. If it ignores the header, every reconnect silently loses whatever was sent during the gap.

03 WebSocket: a request that becomes a socket

SSE only goes one way: the server talks, the client listens, and anything the client says still goes as a separate HTTP request. A WebSocket gives both sides a channel. It starts as an HTTP/1.1 request that asks to switch protocols; once the server agrees, the same TCP connection carries WebSocket frames in both directions until one side closes it.

A WebSocket from upgrade to close
Step 1 of 8
One WebSocket connection (example frames)
BrowserServerNothing sent yet
The connection
protocol→HTTP/1.1readyState→0 CONNECTING
  • just sent
  • just changed

The page runs new WebSocket('wss://chat.example.com/chat'). The TCP and TLS connection opens as for any HTTPS request; no HTTP has been sent yet.

The Sec-WebSocket-Accept value proves the server really speaks WebSocket and is not an HTTP server that happened to echo headers. It is the Base64 of the SHA-1 of the client’s key joined to a fixed string from the spec, RFC 6455:

JavaScript
const crypto = require('node:crypto');
const key = 'dGhlIHNhbXBsZSBub25jZQ=='; // the example key from RFC 6455
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
console.log(crypto.createHash('sha1').update(key + GUID).digest('base64'));
// s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

This is a handshake check, not security. Authentication still comes from a cookie or a token sent with the upgrade request, and the browser adds an Origin header the server should check, because cross-site pages can open WebSockets too.

04 What a frame looks like

After the upgrade, every message travels as one or more frames. A frame header is at least 2 bytes, so a small message costs a few bytes of overhead instead of a full set of HTTP headers.

The first two bytes of the frame a browser sends for "hi"
Frame header (marked bits explained below)
1286432168421value
byte 0 = 0x8110000001129
byte 1 = 0x8210000010130

Byte 0: the top bit is FIN (this is the last piece of the message) and the low four bits are the opcode, 1 for text. Byte 1: the top bit is MASK (set on every client frame) and the low seven bits are the payload length, 2. Four bytes of masking key and the two masked bytes of hi follow.

Opcodes you will meet
OpcodeFrameUsed for
0x1textA UTF-8 message, e.g. JSON
0x2binaryRaw bytes, e.g. audio or a compact encoding
0x0continuationThe next piece of a message split over several frames
0x8closeEnding the connection, with a code such as 1000
0x9 / 0xAping / pongChecking the connection is alive

Lengths up to 125 fit in byte 1. A length of 126 there means the real length follows in the next 2 bytes, and 127 means the next 8. Client frames are masked: XORed with a random 4-byte key carried in the frame. That is not encryption (the key is right there); it stops a page from writing bytes that a confused proxy on the path might read as an HTTP request. Server frames are not masked.

05 Watch both from a terminal

This server uses only Node’s built-in modules. /events streams three SSE events a second apart and honours Last-Event-ID. An upgrade request gets the 101 handshake, one text frame (hi) and a close frame, written as raw bytes so you can see there is no magic.

server.js
const http = require('node:http');
const crypto = require('node:crypto');
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
const server = http.createServer((req, res) => {
if (req.url !== '/events') return res.writeHead(404).end();
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
});
let id = Number(req.headers['last-event-id'] ?? 0);
const timer = setInterval(() => {
id += 1;
res.write(`id: ${id}\ndata: {"tick":${id}}\n\n`);
if (id >= 3) { clearInterval(timer); res.end(); }

Run node server.js, then in a second terminal stream the events. -N turns off curl’s buffering, so each event prints the moment it arrives:

Shell
curl -N http://localhost:3000/events
curl -N -H 'Last-Event-ID: 1' http://localhost:3000/events
Text
id: 1
data: {"tick":1}
id: 2
data: {"tick":2}
id: 3
data: {"tick":3}
# second command, resuming after event 1:
id: 2
data: {"tick":2}
id: 3
data: {"tick":3}

Now send an upgrade request by hand, using the example key from the RFC. curl prints the 101 response; the frame bytes that follow show up as a couple of odd characters and hi.

Shell
curl -i --max-time 2 http://localhost:3000/chat \
-H 'Connection: Upgrade' -H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ=='
HTTP
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Finally a real client. Node 22 and later ship the same WebSocket class as browsers:

client.mjs
const ws = new WebSocket('ws://localhost:3000/chat');
ws.onopen = () => console.log('open');
ws.onmessage = (e) => console.log('message:', e.data);
ws.onclose = (e) => console.log('closed, code', e.code);
Text
open
message: hi
closed, code 1000

These outputs are from real runs on Node 24 with curl 8.7. If you remove the close frame from the server, the client prints closed, code 1006: the connection ended without a close handshake, which is what you see when a network drops.

06 SSE or WebSocket?

The two side by side
QuestionServer-sent eventsWebSocket
DirectionServer to client onlyBoth ways
DataUTF-8 textText or binary
ProtocolPlain HTTP responseIts own framing after an HTTP upgrade
ReconnectBuilt in, with Last-Event-IDWrite it yourself
Custom headers from the browserNo (cookies only)No (cookies, or a token in the URL or first message)
Through proxies and HTTP/2Usually just worksNeeds upgrade support on every proxy

Pick SSE when the server mostly talks and the client mostly listens: live comments, notifications, progress bars, a stream of tokens from a language model. Pick a WebSocket when both sides send often and with low latency: chat with typing indicators, multiplayer games, collaborative editing.

07 When it bites

proxy_read_timeout 60sIdle connections get cutLoad balancers and proxies close connections that stay quiet; nginx’s default read timeout is 60 seconds. Send a heartbeat (an SSE comment or a WebSocket ping) more often than the shortest timeout on the path.
X-Accel-Buffering: noA proxy buffers the streamA buffering proxy holds SSE events until it has a full buffer, so they arrive in bursts or not at all. Turn buffering off for the stream route, and avoid compressing it.
6 per hostSSE over HTTP/1.1 runs out of connectionsBrowsers allow about 6 HTTP/1.1 connections per host, and each open EventSource keeps one. Several tabs can block the rest of the site. HTTP/2 carries all of them on one connection.
user A on server 1, B on server 2Each connection lives on one serverA message posted on server 2 must reach the socket held by server 1. Add a pub/sub layer, such as Redis pub/sub, so every server hears every message.
deploy → 50,000 reconnectsReconnect stormsWhen a server restarts, every client reconnects at once. Add random jitter to the reconnect delay (SSE’s retry: only sets a fixed value, so add jitter on the server side or in your own WebSocket client).

A WebSocket has no built-in resume. If the connection drops, frames sent during the gap are simply gone. Give messages ids and let a reconnecting client ask for everything after the last id it saw, just as SSE does with Last-Event-ID.

08 Check yourself

Question

An SSE connection drops and the browser reconnects with Last-Event-ID: 41. The server ignores the header. What happens to events 42 and 43, sent while the client was away?

Question

Why must a browser mask every WebSocket frame it sends?

Question

Users get a live score feed and never send anything back. Which fits best?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?