WebSockets and Real-Time Communication by kirupa (https://www.kirupa.com/me/index.htm) | filed under JavaScript 101 (https://www.kirupa.com/javascript/learn_javascript.htm) 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: [Image: A timeline from 0 to 30 seconds with the browser on top and the server below. Every 5 seconds the browser sends a request down to the server and gets a response back, 6 round trips in all. 5 of the responses come back with nothing new. A new chat message reaches the server at 11 seconds, but the browser only gets it with the poll at 15 seconds, 4 seconds late.] (https://www.kirupa.com/html5/images/ws_polling.png) (https://www.kirupa.com/html5/images/ws_polling.png?v=adcba19ed71b) 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 (https://www.kirupa.com/html5/making_http_requests_js.htm) 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: [Image: The same timeline from 0 to 30 seconds. At the start, the browser and server do one handshake, and the connection stays open the whole time. The new chat message that reaches the server at 11 seconds goes straight up to the browser. At 19 seconds the browser sends a message down, and at 24 seconds the server pushes another one up. Nothing gets sent when there's nothing to say.] (https://www.kirupa.com/html5/images/ws_open_connection.png) (https://www.kirupa.com/html5/images/ws_open_connection.png?v=d737fa548132) 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: [Image: Two HTTP messages. The browser sends a GET request for /room/42 with the headers Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==, and Sec-WebSocket-Version: 13. The server answers with HTTP/1.1 101 Switching Protocols, the same Upgrade and Connection headers, and Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=, a value it computed from the browser's key.] (https://www.kirupa.com/html5/images/ws_handshake.png) (https://www.kirupa.com/html5/images/ws_handshake.png?v=dd8232f54c54) 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: [Image: A browser on the left and a server on the right, joined by one open connection. Along the top, the browser sends {"type":"chat"} and {"type":"ping"} to the server. Along the bottom, the server sends {"type":"typing"} and {"type":"pong"} to the browser. Neither side waits for the other to ask first.] (https://www.kirupa.com/html5/images/ws_frames.png) (https://www.kirupa.com/html5/images/ws_frames.png?v=4a4079f91da6) 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: Interactive example: A WebSocket echo lab (https://www.kirupa.com/html5/examples/websocket_echo_lab.htm) Try it: 1. Type a message and press Enter 2. Press Disconnect and watch readyState 3. 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: [Image: Four boxes in a row: 0 CONNECTING, 1 OPEN, 2 CLOSING, and 3 CLOSED. The open event moves a socket from CONNECTING to OPEN. Calling close(), or the server saying goodbye, moves it to CLOSING, and the close event marks it CLOSED. A path above the row goes straight from CONNECTING to CLOSED when the handshake fails, with an error event and then a close event.] (https://www.kirupa.com/html5/images/ws_ready_state.png) (https://www.kirupa.com/html5/images/ws_ready_state.png?v=9c22d9560875) 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: [Image: A chart of the wait before reconnect attempts 1 through 7. Each bar spans the range our jitter picks from: 0.5 to 1 second, 1 to 2, 2 to 4, 4 to 8, and 8 to 16 seconds, then 15 to 30 seconds for attempts 6 and 7, because the delay is capped at 30 seconds.] (https://www.kirupa.com/html5/images/ws_backoff.png) (https://www.kirupa.com/html5/images/ws_backoff.png?v=36daaf722981) 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: [Image: Two timelines from 0 to 1.5 seconds after a server restarts. Without jitter, all 12 clients reconnect at exactly 1 second, piled up in one spot. With jitter, each client waits somewhere between 0.5 and 1 second, so the 12 reconnects are spread out from 0.50 to 0.98 seconds.] (https://www.kirupa.com/html5/images/ws_jitter.png) (https://www.kirupa.com/html5/images/ws_jitter.png?v=72a64a192ee9) 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: [Image: A timeline from 0 to 100 seconds with the browser on top and the server below. The browser sends a ping every 25 seconds. At 25 and 50 seconds a pong comes right back. At 66 seconds the connection dies without any close event. The ping at 75 seconds never gets a pong, so after waiting 10 seconds, at 85 seconds, the browser gives up on that connection and reconnects.] (https://www.kirupa.com/html5/images/ws_heartbeat.png) (https://www.kirupa.com/html5/images/ws_heartbeat.png?v=3e1dc9bd399a) 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 (https://github.com/websockets/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: [Image: On the left, a long-running server process holds open connections to four browsers at the same time, for as long as they want. On the right, a serverless function wakes up for one request, sends its response, and stops, so the connection to the browser gets cut.] (https://www.kirupa.com/html5/images/ws_hosting.png) (https://www.kirupa.com/html5/images/ws_hosting.png?v=88df2524c914) 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: [Image: Four rows. Polling with fetch: the browser asks the server over and over, and each answer comes back. Server-Sent Events: the server streams messages to the browser, one way. WebSockets: messages travel both ways at any time. WebRTC data channel: two browsers send messages straight to each other.] (https://www.kirupa.com/html5/images/ws_choices.png) (https://www.kirupa.com/html5/images/ws_choices.png?v=c5b71343d64e) 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 (https://www.kirupa.com/ai_fundamentals/streaming_responses.htm). 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 (https://www.kirupa.com/html5/simple_video_chat_with_webrtc.htm), 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 (https://www.kirupa.com/react/effects_with_useeffect.htm) 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: [Image: Two rows of steps. In development with StrictMode: the effect runs and opens socket A, the cleanup runs and calls A.close(), the effect runs again and opens socket B, messages flow over B, and when the component unmounts, B.close() runs. In production: the effect opens socket A, messages flow over A, and unmounting calls A.close().] (https://www.kirupa.com/html5/images/ws_hook_lifecycle.png) (https://www.kirupa.com/html5/images/ws_hook_lifecycle.png?v=5ef6347e6354) 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 (

{isOpen ? "Connected" : "Reconnecting..."}

Latest: {lastMessage?.text}

setText(event.target.value)} />
); } 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 (https://www.npmjs.com/package/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: 1. Test your knowledge by taking the quiz below. 2. Read the next article in the series, Getting the Mouse Click Position (https://www.kirupa.com/html5/getting_mouse_click_position.htm), or check out some related content: - Streaming Responses (https://www.kirupa.com/ai_fundamentals/streaming_responses.htm). Watch Server-Sent Events stream a chatbot's answer to the browser, piece by piece. - Simple Video Chatting with WebRTC (https://www.kirupa.com/html5/simple_video_chat_with_webrtc.htm). Connect two browsers directly and build a simple video chat with WebRTC. - Building Custom Hooks (https://www.kirupa.com/react/custom_hooks.htm). Pull reusable logic like our useWebSocket hook into custom hooks of your own. 3. Stuck on something, or curious about a detail we skipped? Ask on the forums (https://forum.kirupa.com/), and we'll help you out. [Mastery Quiz] Test your knowledge! Take the WebSockets and real-time communication Quiz: https://www.kirupa.com/quizzes/websockets_in_javascript.htm Practice with 12 multiple-choice questions and an explanation after every answer. [/Mastery Quiz]