WebSockets
A WebSocket is a long-lived, bidirectional channel that starts as an HTTP upgrade and then exchanges messages. Either side can send at any time.
Detailed Explanation
HTTP is one request, one response. Live dashboards, chats, and game ticks want the server to push. Polling GET every second wastes connections. A WebSocket does one handshake (GET plus Upgrade: websocket) and then frames of text or binary go both ways.
In the browser: const ws = new WebSocket(url). Listen for open, message, error, close. ws.send(text) or ws.send(buffer). ws.close(). URL schemes are ws: and wss: (TLS). Cookies on the same origin are sent on the handshake depending on the browser; tokens often go in a query or a first message because you cannot set arbitrary headers on the constructor in browsers.
Messages are not HTTP requests. You invent a protocol: JSON { type, payload }, protobuf, etc. Heartbeats (ping/pong at the protocol layer, or app-level pings) detect half-open connections. Reconnect with backoff; the close event is not the end of the product.
Node has ws and built-in WebSocket in newer releases. Load balancers must support the upgrade (sticky sessions help if you store state per connection). Horizontal scale needs a pub/sub backplane so a message to user 7 reaches the node that holds that socket.
What it costs you: state. Each connection is memory and a file descriptor. Auth on a socket that lives for hours must handle token expiry (re-auth or close). Proxies time out idle sockets. Fall back to SSE or short poll when a corporate proxy blocks ws.
Reach for WebSockets when both sides send often. Reach for Server-Sent Events when only the server pushes text. Reach for HTTP when a request/response is enough.
Code Examples
const ws = new WebSocket("wss://example.com/socket");
ws.addEventListener("open", () => {
ws.send(JSON.stringify({ type: "hello" }));
});
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
console.log(data.type);
});
ws.addEventListener("close", (event) => {
console.log(event.code, event.reason);
});function connect(url, onMessage) {
let ws;
let delay = 500;
function start() {
ws = new WebSocket(url);
ws.onmessage = (e) => onMessage(e.data);
ws.onclose = () => {
setTimeout(start, delay);
delay = Math.min(delay * 2, 10_000);
};
ws.onopen = () => {
delay = 500;
};
}
start();
return () => ws.close();
}Common Gotchas
You cannot set `Authorization` on browser `new WebSocket`
use a ticket query, a cookie, or a first-message auth.
`JSON.parse` on every message can throw
wrap and close or skip bad frames.
`close` codes
`1000` is normal. `1006` is abnormal (no close frame). Reconnect policy should differ.
Binary messages arrive as `Blob` by default
set `ws.binaryType = "arraybuffer"` if you want a buffer.