Server-Sent Events and WebSockets: Real-Time Updates in the Browser
Push data from server to browser: how SSE keeps an HTTP response open, the text/event-stream format, EventSource events, IDs and reconnection, a Node chat server, WebSocket connections, messages, binary data, closing codes, reconnecting with backoff, and choosing between fetch, SSE and WebSockets.
kvi5hnuCode Sprout team member7 min readOn this page
HTTP is request and response: the client asks, the server answers, and the exchange ends. Chat, live dashboards, notifications, collaborative editing and multiplayer games need the opposite as well: the server must be able to send data whenever something happens. Browsers offer two standard tools for that: Server-Sent Events for one-way streams from server to client, and WebSockets for two-way messaging.

Server-Sent Events
The idea behind SSE is simple: the client makes an ordinary HTTP request, and the server never finishes the response. It keeps the connection open and writes a small block of text each time it has news. The browser's EventSource API makes the request, parses the blocks into events and reconnects automatically if the connection drops:
const updates = new EventSource("/events"); // a GET request, started immediately
updates.addEventListener("message", (event) => { // events without a type
showNotice(event.data);
});
updates.addEventListener("price", (event) => { // events with "event: price"
const { sku, price } = JSON.parse(event.data);
updatePrice(sku, price);
});
updates.addEventListener("error", () => {
// fired when the connection is lost; EventSource retries on its own
console.log("reconnecting... readyState =", updates.readyState); // 0 = CONNECTING
});
// later: updates.close() stops it for good (readyState 2 = CLOSED)
event.data is always a string: send JSON and parse it. event.lastEventId holds the latest event ID. For cross-origin streams that need cookies, use new EventSource(url, { withCredentials: true }), and the server must allow it with CORS headers.
The wire format
The response has the content type text/event-stream. Each event is a group of field: value lines, ended by a blank line:
| Line | Meaning |
|---|---|
data: ... | the payload; several data lines are joined with newlines |
event: price | the event type (default message), which selects the listener |
id: 17 | an event ID; on reconnect, the browser sends it back in a Last-Event-ID header |
retry: 3000 | the reconnection delay in milliseconds |
: anything | a comment, often sent periodically as a keep-alive |
Parsing this format is a good exercise in streams. This runnable example does the job of EventSource itself, using fetch and the streaming techniques from article 117:
const http = require("node:http");
// The server writes events in the text/event-stream format
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
res.write("retry: 3000\n\n"); // reconnection delay hint
res.write(": comments start with a colon and are ignored\n\n");
res.write("data: plain message\n\n"); // type defaults to "message"
res.write("event: price\nid: 17\ndata: {\"sku\":\"oolong\",\"price\":12.5}\n\n");
res.write("event: chat\ndata: line one\ndata: line two\n\n"); // data lines are joined with \n
res.end();
});
// A minimal parser for the format, the same job EventSource does in browsers
async function* readEvents(response) {
const decoder = new TextDecoderStream();
let buffer = "";
for await (const text of response.body.pipeThrough(decoder)) {
buffer += text;
let end;
while ((end = buffer.indexOf("\n\n")) !== -1) { // a blank line ends an event
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = { type: "message", data: [], id: undefined };
for (const line of block.split("\n")) {
if (line.startsWith(":")) continue;
const colon = line.indexOf(":");
const field = line.slice(0, colon);
const value = line.slice(colon + 1).replace(/^ /, "");
if (field === "event") event.type = value;
else if (field === "data") event.data.push(value);
else if (field === "id") event.id = value;
}
if (event.data.length) yield { ...event, data: event.data.join("\n") };
}
}
}
async function main() {
await new Promise((resolve) => server.listen(0, resolve));
const response = await fetch(`http://localhost:${server.address().port}/events`);
for await (const event of readEvents(response)) {
console.log(event.type, event.id ?? "-", JSON.stringify(event.data));
}
server.close();
}
main();
message - "plain message"
price 17 "{\"sku\":\"oolong\",\"price\":12.5}"
chat - "line one\nline two"
(A complete parser also remembers the last id across events and handles \r\n line endings; this one keeps only the essentials.) Parsing the stream yourself is also how you consume SSE-style APIs that need a POST request or custom headers, which EventSource can't send. Many AI APIs stream generated text this way.
Reconnection and missed events
If the connection drops, EventSource fires error, waits (3 seconds by default, or the retry value), and connects again, sending the last ID it saw in the Last-Event-ID header. A server that keeps recent events can then resend the ones the client missed. If the server responds with an HTTP error status or a different content type, the browser gives up and sets readyState to CLOSED. To stop the stream on purpose, the server can return status 204.
A server in Node
On the server, an SSE endpoint keeps its response objects in a list and writes to all of them when something happens. This chat server uses fetch POSTs for sending messages and SSE for receiving them:
const http = require("node:http");
const clients = new Set();
http.createServer((req, res) => {
if (req.url === "/chat" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
res.write(": connected\n\n");
clients.add(res);
req.on("close", () => clients.delete(res)); // the browser went away
} else if (req.url === "/chat" && req.method === "POST") {
let text = "";
req.on("data", (chunk) => { text += chunk; });
req.on("end", () => {
const lines = text.split("\n").map((line) => `data: ${line}`).join("\n");
for (const client of clients) client.write(`event: chat\n${lines}\n\n`);
res.writeHead(204).end();
});
} else {
res.writeHead(404).end();
}
}).listen(8080);
Every line of the message gets its own data: prefix, so a message containing newlines can't inject fake fields or events. Each open stream holds a connection, so with HTTP/1.1 browsers allow only about six per domain; HTTP/2 and HTTP/3 remove that practical limit.
WebSockets
A WebSocket is a persistent, two-way connection. It starts as an HTTP request with an Upgrade: websocket header. If the server agrees (101 Switching Protocols), the same TCP connection switches to the WebSocket protocol, and from then on either side can send messages, text or binary, at any time. URLs use wss:// (secure) or ws://.
const socket = new WebSocket("wss://chat.example/rooms/teas");
socket.addEventListener("open", () => {
socket.send(JSON.stringify({ type: "join", name: "Ana" }));
});
socket.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (message.type === "chat") addLine(`${message.from}: ${message.text}`);
});
socket.addEventListener("close", (event) => {
console.log("closed", event.code, event.reason, event.wasClean);
});
socket.addEventListener("error", () => {
// no details are exposed; a close event always follows
});
The connection opens asynchronously, so calling send() before the open event throws an InvalidStateError. readyState tracks the state: WebSocket.CONNECTING (0), OPEN (1), CLOSING (2) and CLOSED (3).
Messages and binary data
send()accepts strings,ArrayBuffers, typed arrays andBlobs.- Incoming text arrives as a string. Binary arrives as a
Blobby default; setsocket.binaryType = "arraybuffer"to receiveArrayBuffers instead. - WebSocket guarantees messages arrive whole and in order, but the protocol itself has no message types or request/response matching. Applications add their own, typically JSON objects with a
typefield and sometimes an ID for replies. socket.bufferedAmountcounts bytes queued bysend()but not yet transmitted. Check it before sending large or frequent messages to avoid flooding a slow connection.
Closing and reconnecting
socket.close(code, reason) starts a clean shutdown. Code 1000 means a normal closure; 4000–4999 are free for applications; codes such as 1001 (going away) and 1006 (connection lost without a close frame) are set by the browser. Unlike EventSource, a WebSocket doesn't reconnect by itself, so apps reconnect with growing delays to avoid overwhelming a recovering server:
function connect(url, onMessage, attempt = 0) {
const socket = new WebSocket(url);
socket.addEventListener("open", () => { attempt = 0; });
socket.addEventListener("message", (event) => onMessage(JSON.parse(event.data)));
socket.addEventListener("close", (event) => {
if (event.code === 1000) return; // closed on purpose
const delay = Math.min(30_000, 500 * 2 ** attempt) * (0.5 + Math.random() / 2);
setTimeout(() => connect(url, onMessage, attempt + 1), delay);
});
return socket;
}
The random factor (jitter) stops thousands of clients from reconnecting at the same instant after a server restart. Long-lived connections can also be silently cut by proxies, so apps often exchange small "ping" messages periodically to detect dead connections.
WebSockets aren't restricted by CORS. The server receives an Origin header and must check it, along with authentication (cookies or a token sent in the first message), before trusting the connection. The server side needs a WebSocket implementation, such as the ws package for Node or the built-in support in Deno and Bun. Node itself provides a standard WebSocket client as a global.
Newer, more specialized options exist: WebSocketStream (a promise and stream-based version, currently in Chromium only) and WebTransport, a multiplexed protocol over HTTP/3 for low-latency uses such as games and media.
Which one should you use?
| Need | Choose |
|---|---|
| Request/response, occasional updates | fetch, possibly polling every few seconds or minutes |
| Server pushes updates to the browser: feeds, notifications, progress, streamed AI text | SSE: plain HTTP, works with existing auth, caching layers and HTTP/2, automatic reconnection |
| Frequent messages in both directions: chat with typing indicators, games, collaborative editing | WebSocket |
| Binary, low-latency or unreliable-delivery streams | WebSocket or WebTransport |
SSE is often overlooked, but for one-way updates it's simpler to build, scale and debug than WebSockets. The client can still send data with ordinary fetch requests, as in the chat server above.
Common questions
Why does my EventSource keep reconnecting every few seconds?
The server is ending the response, either deliberately or because a proxy or framework buffers and closes it. An SSE response must stay open. Disable response buffering and compression for the endpoint, and send periodic : comment lines as a keep-alive.
Can I send headers like Authorization with EventSource?
No. EventSource only supports cookies, via withCredentials. Use cookie-based authentication, a short-lived token in the URL, or read the stream with fetch, which can send any headers.
Why did send() throw an InvalidStateError?
The socket isn't open yet (or is already closed). Send only after the open event, or queue messages until then.
Summary
- Server-Sent Events keep an HTTP response open and stream
text/event-streamblocks (data,event,id,retry).EventSourceparses them into events and reconnects automatically, sendingLast-Event-ID. event.datais a string; event types select listeners; the stream is one-way, server to client.- WebSockets upgrade an HTTP connection to a two-way message channel for text and binary data, with
open,message,closeanderrorevents. - WebSockets don't reconnect on their own: use exponential backoff with jitter, and verify
Originand authentication on the server. - Use
fetchfor request/response, SSE for server-to-client streams and WebSockets for frequent two-way messaging.
Practice Questions
What event does this stream produce in the browser, and what is its data?
event: score
data: home 2
data: away 1
Answer
An event of type score (handled by addEventListener("score", ...), not onmessage) whose data is "home 2\naway 1". Multiple data lines are joined with a newline.
A server restarts and 10,000 clients reconnect at exactly 1-second intervals. What goes wrong, and how do you fix it?
Answer
All the clients hit the server at the same moments, which can overload it again as soon as it comes back. Use exponential backoff (growing delays) with random jitter, so reconnections are spread out over time.
How do you receive WebSocket binary messages as ArrayBuffers instead of Blobs?
Answer
Set socket.binaryType = "arraybuffer" before the messages arrive. Then event.data is an ArrayBuffer for binary messages, while text messages are still strings.
For a page that shows live delivery status updates pushed by the server, would you pick SSE or WebSockets? Why?
Answer
SSE. The data only flows from server to client, and SSE works over plain HTTP with your existing cookies and infrastructure, reconnects automatically, and can resume missed events with Last-Event-ID.
Previous: Networking with fetch: Requests, Responses, Errors, Streaming, Uploads and Cancellation
Next: Web Storage, Cookies and IndexedDB: Saving Data in the Browser

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.