Use Server-Sent Events (SSE) when data only needs to flow from the server to the browser: notifications, live dashboards, job progress, an LLM answer streamed token by token. Use WebSocket when the client also sends a steady flow of messages and both directions have to be quick, as in chat with typing indicators, multiplayer games or collaborative editing, or when you need to send binary data. If you're unsure, start with SSE: it is ordinary HTTP, the browser reconnects by itself, and the pub/sub layer behind it stays the same if you move to WebSocket later.
The protocols themselves are the easy part. What decides most real projects is how a browser connection gets authenticated, what your proxy does with a response that never ends, and what a client sees after it drops off for ten seconds. Most of this post is about those, with Node.js examples you can run.
The short comparison
| SSE | WebSocket |
|---|---|---|
Direction | Server to client | Both ways, at any time |
What it runs on | One HTTP response that stays open | Its own framing, after an HTTP/1.1 upgrade |
Payload | UTF-8 text | Text or binary |
Browser API | | |
Reconnects after a drop | Yes, automatically | Only if you write it |
Catching up on missed messages | | Your own design |
Custom headers from the browser | Not possible, cookies only | Not possible, cookies only |
Connections per browser | 6 per domain on HTTP/1.1, shared by all tabs; many more on HTTP/2 | One TCP connection per socket |
Through proxies and CDNs | Usually fine; watch for response buffering | Every hop has to pass the upgrade |
Typical uses | Notifications, feeds, dashboards, progress bars, LLM streaming | Chat, games, shared editing, tools where users act as often as they watch |
How SSE works
The browser makes a GET request and the server never finishes the response. It answers with Content-Type: text/event-stream and then writes events as plain text: one or more data: lines, optionally an event: name, an id: and a retry: (the reconnect delay in milliseconds), with a blank line closing each event. A line that starts with a colon is a comment, which makes a cheap keep-alive. MDN's guide to server-sent events has the full format.
When the connection drops, EventSource waits a few seconds and reconnects without any code from you. If the stream carried id: fields, the new request includes a Last-Event-ID header with the last ID the browser received. That header is all the browser does. Sending the missed events again is the server's job, so the server has to keep recent events somewhere. A minimal Node.js server with replay:
import http from 'node:http';
const clients = new Set();
const recent = []; // the last 1,000 events, for clients that reconnect
let lastId = 0;
export function publish(type, payload) {
const id = ++lastId;
const frame = `id: ${id}\nevent: ${type}\ndata: ${JSON.stringify(payload)}\n\n`;
recent.push({ id, frame });
if (recent.length > 1000) recent.shift();
for (const res of clients) res.write(frame);
}
http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname !== '/events') return res.writeHead(404).end();
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'X-Accel-Buffering': 'no', // tells nginx not to buffer this response
});
res.flushHeaders(); // send headers now so EventSource opens even with nothing to replay
// The browser sends Last-Event-ID when it reconnects by itself; a page that
// reopened the stream passes ?since= instead. Replay what the client missed.
const seen = Number(req.headers['last-event-id'] ?? url.searchParams.get('since')) || 0;
for (const e of recent) if (e.id > seen) res.write(e.frame);
clients.add(res);
req.on('close', () => clients.delete(res));
}).listen(3000);
// A comment line every 15 seconds stops idle proxies from closing the stream.
setInterval(() => {
for (const res of clients) res.write(': keep-alive\n\n');
}, 15_000);The page needs one thing the browser won't do for you. Automatic reconnects only cover network errors. If a reconnect gets any status other than 200 (a 502 from your proxy halfway through a deploy, a 401 after the session expired), the HTML standard says the browser fails the connection: readyState becomes CLOSED and it never tries again. A dashboard left open over a deploy then sits there showing old numbers. So watch for that case and open a new stream yourself:
let lastId = '';
function listen() {
// Same origin, so the session cookie is sent.
const events = new EventSource(lastId ? `/events?since=${lastId}` : '/events');
events.addEventListener('price', (e) => {
lastId = e.lastEventId;
render(JSON.parse(e.data));
});
events.addEventListener('error', () => {
// Dropped connections are retried by the browser. After an HTTP error it
// gives up, so start a new stream after a random 1 to 5 second wait.
if (events.readyState === EventSource.CLOSED) {
setTimeout(listen, 1_000 + Math.random() * 4_000);
}
});
}
listen();A new EventSource starts without a Last-Event-ID, which is why the server also reads ?since=. The error event doesn't say which status came back, so if sessions can expire, check the session with a normal request before reopening. And if a client comes back with an ID older than anything you still hold, send it a full snapshot instead of a partial replay.
Two limits surprise people. First, EventSource only makes GET requests, and the only option it accepts is withCredentials. You can't set an Authorization header or send a body. Second, over HTTP/1.1 a browser opens at most six connections per domain, counted across all tabs, and every open stream holds one of them. A user with six tabs of your app open has used them all, and the next request to your domain waits. Over HTTP/2 the streams share one connection and the server sets the limit, usually 100 or more, so serving SSE over HTTP/2 makes the problem go away for most apps.
The most visible SSE users right now are LLM APIs. Anthropic's Messages API, for one, streams its response as server-sent events when you send "stream": true in a POST. If you relay a stream like that to your own frontend, you'll probably read it with fetch() and parse the events yourself, because EventSource can't send the POST body. The Model Context Protocol took the same route: in its Streamable HTTP transport each message is a POST, and the reply comes back as JSON or as an SSE stream.
How WebSocket works
A WebSocket connection starts as an HTTP/1.1 GET that asks to switch protocols. This exchange is adapted from the example in RFC 6455, the 2011 standard that defines WebSocket:
GET /ws HTTP/1.1
Host: app.example.com
Upgrade: websocket
Connection: Upgrade
Origin: https://app.example.com
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The server computes Sec-WebSocket-Accept by appending a fixed GUID to the client's key, hashing it with SHA-1 and encoding the result in Base64. That proves the server really read this handshake. Checking who is connecting is a separate job, covered below.
After the 101, the same TCP connection carries WebSocket frames. A frame header is 2 to 14 bytes, every frame the client sends is masked with a 4-byte key, and either side can send a ping that the other must answer with a pong. ws:// defaults to port 80 and wss://, WebSocket over TLS, to 443, so a socket can share the port your site already uses.
What WebSocket leaves to you is everything above the frame: reconnecting, message IDs, acknowledgements, topics or rooms. You write those or pick a library that has them. Socket.IO, for example, gives you reconnection, buffering while offline, acknowledgements and rooms. Keep in mind that it's a protocol of its own that uses WebSocket (or HTTP long-polling) underneath, so a plain WebSocket client can't connect to a Socket.IO server. That's fine when you own both ends; for a public API, offer plain WebSocket.
Running WebSocket over HTTP/2 (RFC 8441) and HTTP/3 (RFC 9220) is standardized too, but it needs support in the browser, the server and every proxy in between. Plan as if each socket is its own TCP connection.
Five questions that settle it
- Does the client send more than the occasional message? If users mostly watch and only sometimes act (submit a form, approve a request), an SSE stream plus normal POST requests is simpler than a socket, and your API stays in one style. Choose WebSocket when the client sends several messages a second, like cursor positions in a shared editor, or when one ordered channel in both directions keeps the logic simpler.
- Do you need binary data? SSE is text only, and Base64 makes binary about a third larger. WebSocket sends the bytes as they are.
- What sits between your server and your users? Some networks block or break upgraded connections. A plain HTTP stream gets through more often, though a proxy may buffer it. If your users work behind locked-down corporate networks, test from there before you commit.
- How will the browser authenticate? Neither browser API lets you set a header. The next section covers the options, and they rule out more designs than people expect.
- How often does the data change? If it's once a minute, poll. A GET every 30 seconds is cacheable, passes every proxy and holds nothing open on your servers. Push pays off when users would notice the delay.
Between your own backend services, neither is the obvious tool. A message queue or gRPC streaming usually fits better there.
Authenticating browser connections
The browser's WebSocket constructor takes a URL and an optional list of subprotocols, nothing else. EventSource takes a URL and the withCredentials flag. So the Authorization: Bearer header your REST API expects can't be sent by either. The options that work:
- A session cookie. Browsers send cookies with the WebSocket handshake and with
EventSourcerequests. For WebSocket this opens a hole: browsers don't apply CORS to the handshake, so a page on another site can open a socket to your server and the user's cookie goes along (cross-site WebSocket hijacking). The OWASP WebSocket Security Cheat Sheet says to check theOriginheader against an explicit allowlist on every handshake and to useSameSite=LaxorStrictcookies. - A token in the first message. Open the socket over
wss://, send the token as the first message, and send nothing protected until it checks out. - A token in the query string is the one to avoid, because URLs end up in access logs. If you have no other choice, fetch a short-lived, single-use ticket from your REST API right before connecting and put that in the URL.
For SSE, cookies work the same way: same origin, or cross-origin with withCredentials: true and matching CORS headers. If you need a bearer token, use fetch() and read the stream yourself.
Run the check before the upgrade completes. With the ws library for Node.js, that means handling the HTTP server's upgrade event yourself; the library's docs discourage its older verifyClient hook. A sketch:
import http from 'node:http';
import { WebSocketServer } from 'ws';
const ALLOWED_ORIGINS = new Set(['https://app.example.com']);
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
server.on('upgrade', async (req, socket, head) => {
socket.on('error', console.error);
// sessionUser() is yours: look up the session cookie, return null if invalid.
const user = ALLOWED_ORIGINS.has(req.headers.origin)
? await sessionUser(req.headers.cookie)
: null;
if (!user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req, user));
});
wss.on('connection', (ws, req, user) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
ws.on('error', console.error);
ws.on('message', (data) => {
let msg;
try { msg = JSON.parse(data); } catch { return ws.close(1008, 'invalid JSON'); }
handleMessage(user, msg, ws);
});
});
// Every 30 seconds: drop sockets that didn't answer the last ping, ping the rest.
setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) { ws.terminate(); continue; }
ws.isAlive = false;
ws.ping();
}
}, 30_000);
server.listen(8080);maxPayload is worth setting: ws accepts messages up to 100 MiB by default, and OWASP suggests 64 KB or less for typical apps. Above the limit, ws closes the socket with code 1009. The 30-second ping loop catches connections that died without a close frame, such as a phone that lost signal in a lift, and it also keeps idle proxies from cutting healthy ones.
One more browser quirk. When a handshake fails, the page never learns the HTTP status. It gets an error event and a close event with code 1006, whether you answered 401 or the server was down. So if a session can expire while a client is away, either check the session with a normal request before reconnecting, or accept the upgrade and close the socket at once with your own code. RFC 6455 leaves 4000 to 4999 for applications; 4001 could mean "log in again".
Proxies, load balancers and idle timeouts
Upgrade and Connection are hop-by-hop headers, so a reverse proxy drops them unless you forward them explicitly. In nginx, following its WebSocket proxying docs:
location /ws/ {
proxy_pass http://app;
proxy_http_version 1.1; # already the default from nginx 1.29.7
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /events {
proxy_pass http://app;
proxy_buffering off; # or send X-Accel-Buffering: no from the app
}nginx also closes a proxied connection when the backend sends nothing for 60 seconds (proxy_read_timeout). You can raise that, but it's better to make sure something crosses the wire more often: the 30-second WebSocket ping and the 15-second SSE comment above both do. With response buffering left on, SSE events arrive in bursts, and a gzip middleware in your app can cause the same effect.
Sticky sessions come up in every scaling discussion, often wrongly. A plain WebSocket is one TCP connection. Once the load balancer has sent it to a server, it stays there until it closes, so it doesn't need sticky sessions, and neither does an SSE stream. Socket.IO is the exception: by default a client starts with HTTP long-polling, and those separate requests have to reach the same process, so Socket.IO's docs require sticky sessions unless you limit the client to the WebSocket transport.
Running more than one server
As soon as there are two instances, an event produced on one has to reach clients connected to the other. The usual answer is a pub/sub channel that every instance subscribes to. Redis is the common pick, and Socket.IO has adapters for it.
Redis pub/sub delivers each message at most once: a subscriber that is disconnected at that moment misses it for good. That's acceptable for typing indicators. If clients must catch up after a drop, store events somewhere persistent, such as a Redis Stream or a database table, and use its IDs as your SSE id: values, so a reconnect that lands on a different instance can still be served. The in-memory buffer in the SSE example above only works for a single process.
Deploys need a thought too. Restarting a server disconnects all of its clients at once, and if they all retry on the same schedule they come back in the same second. Add random jitter to the client's backoff:
function connect(attempt = 0) {
const ws = new WebSocket('wss://app.example.com/ws');
ws.onopen = () => { attempt = 0; };
ws.onmessage = (e) => render(JSON.parse(e.data));
ws.onclose = (e) => {
if (e.code === 4001) return showLogin(); // our own "session expired" code
// "Full jitter": wait a random time between 0 and min(30 s, 1 s × 2^attempt)
const delay = Math.random() * Math.min(30_000, 1_000 * 2 ** attempt);
setTimeout(() => connect(attempt + 1), delay);
};
}
connect();WebSocket on a live odds platform we ran
We built and ran the odds data platform for EdgeHunters, a Dublin company that sells betting-analytics tools, from July 2023 to early 2026. WebSocket showed up at both ends. Some sportsbooks publish their odds over WebSocket feeds, so several of our scrapers were WebSocket clients themselves. That's the easy side: a server-side client sends whatever headers it needs and has none of the browser limits above. Inside the system, Redis was the queue for the Celery workers and a cache for the frontend, and live odds reached the product's frontend over WebSocket.
The socket was a small part of that platform. Most of the work described in the case study sits behind it: one scraper per sportsbook, tables that map each book's team and league names to the same game, anomaly checks that post to Slack, and a third-party odds API that takes over when a scraper fails. If you're planning something similar, put most of your effort there. A WebSocket delivers whatever the pipeline hands it, stale prices included.
Frequently asked questions
Is WebSocket faster than SSE?
For pushing a message from server to client over an open connection, neither has a built-in latency advantage: both write to a TCP connection that already exists. WebSocket has less overhead per message and can carry binary, which starts to matter at high message rates. Proxy buffering and reconnect behaviour usually affect how fast an app feels more than the protocol does.
Do WebSockets need sticky sessions?
Plain WebSockets don't, because the connection stays on the server where it was opened. Socket.IO does, unless the client uses only the WebSocket transport, because its long-polling requests must reach the same process.
Can EventSource send an Authorization header?
No. Its only option is withCredentials, which controls whether cookies go with cross-origin requests. Use cookie-based auth, or read the stream with fetch(), which can send any header.
Does SSE work over HTTP/2 and HTTP/3?
Yes. It's a normal HTTP response, so it runs over any version. HTTP/2 or newer is the better choice, because many streams share one connection and the six-connection limit of HTTP/1.1 no longer applies.
Should I use Socket.IO or plain WebSocket?
Socket.IO if you control both client and server and want rooms, acknowledgements, reconnection and a long-polling fallback without writing them. Plain WebSocket, with ws on Node.js, if other people's clients will connect or you only need one or two of those features.
If you're making this call for a product of your own and want a second opinion, it's part of the backend and API work we do.
Related Articles
Kong vs Traefik vs AWS API Gateway: How to Choose
Kong, Traefik and AWS API Gateway compared as of October 2026: features, licensing, Kubernetes support and what AWS charges for 100 million requests a month.
Read More: Kong vs Traefik vs AWS API Gateway: How to ChoosegRPC vs REST for Microservices: When gRPC Is Worth It
When gRPC beats REST between services, what it adds to your operations (load balancing, deadlines, browser access), and what our own protobuf vs JSON test showed.
Read More: gRPC vs REST for Microservices: When gRPC Is Worth ItRPA Implementation: From Process Choice to Bots That Keep Running
Most of an RPA implementation is choosing the process and designing for exceptions. The order we work in, current license prices, and what broke in the n8n and LLM automation we built with an agency.
Read More: RPA Implementation: From Process Choice to Bots That Keep Running
