TL;DR
When a page needs to hear about things the moment they happen, the browser and server can keep one connection open that either side can send messages over at any time. That connection is a WebSocket. It starts as an HTTP request that gets upgraded with a 101 status, and we use it through new WebSocket(url), its events, and send().
- When a connection drops, we reconnect with exponential backoff (1 second, doubling, capped at 30 seconds) plus random jitter, so thousands of pages don't all reconnect at the same instant.
- A ping every 25 seconds that expects a pong within 10 seconds notices connections that died without ever firing a close event.
- Always use wss://, check the Origin header on the server, and keep long-lived secrets out of the socket's URL, because URLs end up in logs.
- In React, a useWebSocket hook opens the socket in an effect and closes it in the cleanup, which also handles StrictMode running the effect twice in development.
Chat apps, live sports scores, multiplayer games, and that little "Kirupa is typing..." bubble all have something in common. The page finds out about something the moment it happens, and nobody has to hit refresh. That is surprisingly tricky with the regular way the web works, where the browser has to ask before the server is allowed to answer.
The fix is one connection that stays open, so both sides can talk whenever they want, and that is what WebSockets give us. We are going to see what goes over the wire, play with a live connection to a real server, make our code survive dropped connections, and wrap it all up in a React hook.
Onwards!
Why Is Plain HTTP Awkward for Live Updates?
With plain HTTP, a server can only send something back when the browser asks for it. If we want live updates, our page has to keep asking, and this is known as polling. It's Donkey in Shrek 2, asking "Are we there yet?" for the whole trip.
Here is what polling every 5 seconds looks like for a chat room:
Our page asks 6 times in 30 seconds, and 5 of those trips come back with nothing new. Now look at the envelope at 11 seconds. A chat message reaches the server, but our page doesn't hear about it until the poll at 15 seconds, so it shows up 4 seconds late. The HTTP requests we usually make are perfect for one question and one answer. Live updates need something that stays open.
What we want is one connection that stays open, so either side can speak up whenever it likes:
After a quick back-and-forth at the start, the connection stays open. The chat message at 11 seconds reaches the browser right away, and our page sends its own message at 19 seconds over the same connection. When nobody has anything to say, nothing gets sent.
What Is a WebSocket?
A WebSocket is one long-lived connection between a browser and a server that either side can send messages over at any time. It starts out as a regular HTTP request asking to switch protocols, and the server agrees by answering with 101 Switching Protocols.
This switch is called the handshake, and here is what it looks like for a chat room at /room/42:
The Upgrade: websocket header is the browser asking to switch. The server mixes the browser's random Sec-WebSocket-Key with a fixed string from the WebSocket spec, hashes it, and sends back the result. That is how the browser knows it is talking to a real WebSocket server. The browser writes all of these headers for us.
Once the 101 comes back, the same connection carries small packets of data called frames, and frames can travel in either direction:
Our server tells us someone is typing without waiting for us to ask. Each message is a little JSON object whose type says what kind of message it is. The protocol doesn't care what is inside a frame, so type is a convention we pick.
Trying a Real WebSocket
Before we write any code, let's poke at a real WebSocket. The example below connects to a public echo server, which sends back whatever we send it:
Try it
- Type a message and press Enter
- Press Disconnect and watch readyState
- Press Reconnect to open a new socket
The server sent us a hello the moment our connection opened, before you typed anything. When you press Disconnect, readyState sits on 2 CLOSING for a moment (about 2 seconds in Chrome when I tried it) and then lands on 3 CLOSED with a code of 1000.
How Do We Use WebSockets in JavaScript?
We open a connection with new WebSocket(url), using a URL that starts with wss://. From there, we listen for four events (open, message, error, and close) and call send() to talk to the server. Here is a chat client that joins our room:
const socket = new WebSocket("wss://chat.example.com/room/42");
socket.addEventListener("open", () => {
socket.send(JSON.stringify({ type: "chat", text: "Hi everyone!" }));
});
socket.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (message.type === "chat") {
showChatMessage(message);
} else if (message.type === "typing") {
showTypingIndicator(message.name);
}
});
socket.addEventListener("error", () => {
console.log("Something went wrong. A close event is on its way.");
});
socket.addEventListener("close", (event) => {
console.log(`Closed with code ${event.code}. Clean? ${event.wasClean}`);
});
Calling send() before the connection opens throws an InvalidStateError, so our first message goes inside the open handler. Incoming messages show up in event.data, and we parse each one and check its type. The error event doesn't say what went wrong. A close event with the details always follows it.
Our socket's readyState property tells us which of four states it is in:
A healthy socket walks from left to right. What if the handshake fails? Then it jumps straight from 0 to 3. Sending on a closing or closed socket doesn't throw an error, and our data just quietly disappears, so we check that readyState is 1 before sending anything important.
When we are done, we call socket.close(1000, "Leaving the room"). The close event's code property tells us how a connection ended, and a handful of codes come up all the time:
| Code | What it means |
|---|---|
| 1000 | A normal goodbye, like when we call close(1000) |
| 1001 | Going away, like a server shutting down or a page being left |
| 1006 | The connection dropped without a goodbye (never sent, only reported to us) |
| 1008 | A policy violation, like a server turning away a site it doesn't trust |
| 1011 | The server ran into an unexpected error |
| 3000-4999 | Ours to define, like 4000 for "No pong" |
From the browser, close() only accepts 1000 or our own codes from 3000 to 4999. One more property is worth knowing: bufferedAmount counts the bytes still waiting to go out, and if it keeps growing, we are sending faster than the connection can handle.
Reconnecting With Backoff and Jitter
Connections drop. A laptop goes to sleep, or we deploy a new server. If every page keeps retrying instantly, a struggling server gets hammered...and nearly every attempt fails.
A kinder approach is exponential backoff. We start with a delay of 1 second, double it after each attempt, and cap it at 30 seconds. Each attempt will then wait a random amount of time between half of that delay and the full delay:
By the sixth attempt, we are waiting 15 to 30 seconds, and that is as slow as it gets. When a connection opens, we reset our attempt counter. Why the randomness? Imagine our server restarts while 12 people are connected:
Without randomness, all 12 come knocking at exactly 1 second. With 50,000 people, that stampede can knock a freshly restarted server right back over. The random part is called jitter, and it turns the stampede into a steady trickle.
Noticing a Dead Connection With Heartbeats
What happens when a connection dies and nobody tells us? If a router gets unplugged, our socket can sit at readyState 1 for a long time, looking perfectly healthy. Quiet connections have another problem: many proxies hang up on a connection that has been silent for a while (nginx's default is 60 seconds).
The fix for both is a heartbeat. Every 25 seconds, we will send a ping message, and our server will answer with a pong. If no pong shows up within 10 seconds, we will treat the connection as dead:
At 66 seconds, the connection quietly dies, so the ping at 75 seconds never gets its pong. At 85 seconds, we give up and start a fresh connection. (The protocol has its own ping frames, but browser JavaScript can't send them, so we use regular messages.)
Here is our chat client with reconnecting and a heartbeat built in:
const url = "wss://chat.example.com/room/42";
let socket = null;
let attempt = 0;
let heartbeatTimer;
let pongTimer;
function connect() {
const ws = new WebSocket(url);
socket = ws;
ws.addEventListener("open", () => {
attempt = 0;
startHeartbeat(ws);
});
ws.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (message.type === "pong") {
clearTimeout(pongTimer);
} else if (message.type === "chat") {
showChatMessage(message);
}
});
ws.addEventListener("close", () => {
if (ws === socket) {
reconnectLater();
}
});
}
function reconnectLater() {
clearInterval(heartbeatTimer);
clearTimeout(pongTimer);
socket = null;
const delay = Math.min(30000, 1000 * 2 ** attempt);
const wait = delay / 2 + Math.random() * (delay / 2);
attempt++;
setTimeout(connect, wait);
}
function startHeartbeat(ws) {
heartbeatTimer = setInterval(() => {
ws.send(JSON.stringify({ type: "ping" }));
pongTimer = setTimeout(() => {
ws.close(4000, "No pong");
reconnectLater();
}, 10000);
}, 25000);
}
connect();
Take a look at the ws === socket check. When a pong never arrives, we reconnect right away, because a dead connection can't finish saying goodbye. When I tried this in Chrome against a frozen server, its close event took over 90 seconds to show up! By then, socket points to our newer connection, so the check ignores the old one.
A Tiny WebSocket Server
Here is a small chat server for Node using the popular ws package:
import { WebSocketServer, WebSocket } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (socket, request) => {
if (request.headers.origin !== "https://www.example.com") {
socket.close(1008, "Origin not allowed");
return;
}
socket.on("message", (data) => {
let message;
try {
message = JSON.parse(data);
} catch {
return;
}
if (message.type === "ping") {
socket.send(JSON.stringify({ type: "pong" }));
} else if (message.type === "chat") {
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: "chat", text: message.text }));
}
}
}
});
});
Each time a browser finishes the handshake, the connection event hands us a socket for that browser plus the original HTTP request. We check the Origin header, answer pings, and send each chat message to everyone. This server has to keep running and hold every connection open, which rules out a lot of hosting:
Typical shared hosting and serverless functions run our code for one request and then stop, so neither can hold a socket open for hours. We need a small virtual server or container that runs all the time, or a hosted service that keeps the connections open for us.
Keeping WebSockets Secure
WebSockets skip some protections regular requests get, so a few rules really matter:
- Always use wss://. It encrypts everything like https:// does, and an HTTPS page can't open a plain ws:// connection anyway.
- Check the Origin header on the server. Same-origin rules don't stop another site from opening a WebSocket to our server, and the browser sends our visitor's cookies along with it.
- Keep long-lived secrets out of the URL. The WebSocket API can't add an Authorization header, but URLs end up in logs. Use a cookie, or fetch a short-lived, single-use ticket and pass that instead.
- Treat every message as untrusted. Our server ignores anything that isn't JSON with a type it knows, and the ws package's maxPayload option caps how big a message can be.
WebSockets vs. Server-Sent Events vs. Polling: Which Should You Use?
Pick WebSockets when both sides send frequent messages, and pick Server-Sent Events when only the server talks. Polling with fetch is the simplest choice when updates are rare. Here is which way the messages travel with each option:
Server-Sent Events (the EventSource API) are plain HTTP and reconnect on their own, which makes them great for notifications or a chatbot streaming its answer. For checking something every few minutes, a fetch on a timer works with any host. When two browsers need to talk directly, like in a video chat, a WebRTC data channel skips the server in the middle. WebSockets shine for chat, multiplayer cursors, and editing a document together. The newer WebTransport, built on HTTP/3, can do even more once your visitors' browsers support it.
Building a useWebSocket Hook in React
In React, we want our socket to open when a component shows up and close when it goes away. That is exactly what an effect with a cleanup function does, so we will wrap one in a custom hook:
import { useCallback, useEffect, useRef, useState } from "react";
export function useWebSocket(url) {
const socketRef = useRef(null);
const [readyState, setReadyState] = useState(WebSocket.CONNECTING);
const [lastMessage, setLastMessage] = useState(null);
useEffect(() => {
let stopped = false;
let attempt = 0;
let retryTimer;
function connect() {
const socket = new WebSocket(url);
socketRef.current = socket;
setReadyState(WebSocket.CONNECTING);
socket.addEventListener("open", () => {
attempt = 0;
setReadyState(WebSocket.OPEN);
});
socket.addEventListener("message", (event) => {
setLastMessage(JSON.parse(event.data));
});
socket.addEventListener("close", () => {
if (stopped) return;
setReadyState(WebSocket.CLOSED);
const delay = Math.min(30000, 1000 * 2 ** attempt);
attempt++;
retryTimer = setTimeout(connect, delay / 2 + Math.random() * (delay / 2));
});
}
connect();
return () => {
stopped = true;
clearTimeout(retryTimer);
socketRef.current.close(1000, "Component unmounted");
socketRef.current = null;
};
}, [url]);
const sendMessage = useCallback((message) => {
const socket = socketRef.current;
if (socket?.readyState !== WebSocket.OPEN) return false;
socket.send(JSON.stringify(message));
return true;
}, []);
return { readyState, lastMessage, sendMessage };
}
Our socket lives in a ref, because we hold on to it without showing it. The readyState and lastMessage values do show up in our UI, so they live in state. Our cleanup sets stopped, cancels any pending retry, and closes the socket. The sendMessage function never changes between renders, because it reads socketRef.current at the moment we call it.
There is one surprise in development. With StrictMode on, React runs our effect, runs its cleanup right away, and then runs our effect again:
React does this on purpose to check that our cleanup really undoes our effect. Socket A gets closed while it is still connecting (Chrome logs a harmless warning about it), and our stopped flag keeps it from scheduling a reconnect. We end up with exactly one open socket, and in production, the effect runs just once.
Using our hook in a component looks as follows:
function ChatRoom() {
const { readyState, lastMessage, sendMessage } = useWebSocket(
"wss://chat.example.com/room/42"
);
const [text, setText] = useState("");
const isOpen = readyState === WebSocket.OPEN;
function handleSubmit(event) {
event.preventDefault();
if (sendMessage({ type: "chat", text })) {
setText("");
}
}
return (
<form onSubmit={handleSubmit}>
<p>{isOpen ? "Connected" : "Reconnecting..."}</p>
<p>Latest: {lastMessage?.text}</p>
<input value={text} onChange={(event) => setText(event.target.value)} />
<button disabled={!isOpen}>Send</button>
</form>
);
}
Keep in mind that lastMessage only holds the newest message, and if two arrive back to back, our component may only see the second one. For a chat log where every message counts, we would append each message to a list in the message handler instead. If you'd rather not maintain a hook yourself, the react-use-websocket package has a similar API with options for shared sockets, heartbeats, and reconnecting.
Conclusion
Phew! WebSockets swap the ask-and-wait rhythm of HTTP for one connection that starts as an HTTP request, gets upgraded with a 101, and carries frames both ways. The browser API is small. The real work is in the parts it leaves to us: reconnecting with backoff and jitter, heartbeats, and a server that checks who is knocking.
WebSockets need a server that stays running, and Server-Sent Events are simpler when only the server talks. When both sides really do need to chat, though, WebSockets are the tool to reach for. Now go build that "is typing..." bubble. Unlike Donkey, your visitors won't have to keep asking.
Before you go, here are a few things you can do:
-
Keep reading
Read the next article in the series, Getting the Mouse Click Position, or check out some related content:
-
Ask a question
Stuck on something, or curious about a detail we skipped? Ask on the forums, and we’ll help you out.
Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.
Your support keeps this site going! 😇












