Skip to content
Web Developmentintermediate

What are WebSockets?

Updated Nov 30, 20263 min readBased on official documentation
What are WebSockets?

In short

WebSockets are a way for a browser and a server to keep one open connection and exchange messages in both directions. The server can send data without waiting for the browser to ask, so the page can update in real time.

The problem WebSockets solve

A normal web request works like a question and an answer. The browser asks, the server replies, and the connection is done. If a page needs fresh data, it has to ask again and again. This repeated asking is called polling, and it wastes time and network traffic.

WebSockets offer a different model. After one initial handshake, the browser and the server keep a single connection open. Either side can send a message at any moment. The WebSocket API in the browser makes it possible to open this kind of two-way session and to send and receive data without polling the server for a reply.

This is useful for chat apps, live scores, collaborative editors, and dashboards that show data as it changes.

How it works

A WebSocket connection starts as a normal HTTP request. The browser sends an upgrade request with a few special headers. The most important one is Sec-WebSocket-Key, a random value the browser creates so the server can prove it understood the request. The browser adds this header on its own, so you do not set it yourself.

If the server agrees, it replies with Sec-WebSocket-Accept. This value is calculated from the key the browser sent. Once both sides accept, the connection switches from HTTP to the WebSocket protocol, and messages can flow in both directions.

The browser exposes the connection through a WebSocket object. You listen for a few events on it. The open event fires when the connection is ready. The message event fires when the server sends data. The close event fires when the connection ends. Because these events arrive whenever they happen, your code reacts to data instead of checking for it.

A simple example

Here is a small client that connects, sends one message, and prints whatever comes back. The address uses the ws:// scheme, or wss:// when the connection is encrypted.

const socket = new WebSocket("wss://example.com/chat");

socket.addEventListener("open", () => {
  socket.send("Hello, server");
});

socket.addEventListener("message", (event) => {
  console.log("Received:", event.data);
});

socket.addEventListener("close", () => {
  console.log("Connection closed");
});

The server side needs its own code that accepts the upgrade and handles messages. The browser only covers the client part.

Common mistakes

The first mistake is leaving connections open. If a page has an open WebSocket connection, the browser may not place the page in the back-forward cache, which is a store that lets pages reload instantly when the user navigates back. The good practice is to close the connection when the user has finished with the page.

The second mistake is assuming the browser will slow down for you. The WebSocket interface does not support backpressure. Backpressure is a way for a receiver to tell a sender to slow down. Without it, when messages arrive faster than your code can handle them, they pile up in memory, or the page can freeze because the CPU is fully busy. You need to keep message handlers light, or limit how much data the server sends.

The third mistake is forgetting the server. WebSockets need a server that supports the protocol. Many libraries exist for common languages, so you rarely need to build the protocol from scratch.

Alternatives

If you only need the server to push updates in one direction, Server-Sent Events may be a simpler choice. They use a standard HTTP connection and send messages from the server to the browser.

If backpressure is a real concern, the WebTransport API is worth a look. It supports backpressure and several features WebSocket does not, such as unidirectional streams, out-of-order delivery, and unreliable datagrams. The WebSocketStream interface was an earlier attempt at the same problem, but it is non-standard and has weaker browser support than WebTransport.

For general background on the request and response model that WebSockets start from, see our page on What is HTTP?. If you build interactive interfaces on top of real-time data, What is the DOM? explains how the page structure gets updated when new messages arrive.

For the full API details, read the WebSocket API documentation on MDN.

FAQ

Are WebSockets the same as HTTP?

No. WebSockets begin with an HTTP request, then switch to a separate protocol. After the switch, messages flow in both directions without the request and response pattern of HTTP.

Do I need a special server for WebSockets?

Yes. The server must accept the WebSocket upgrade and handle messages. Many libraries for common languages make this easier.

Should I use WebSockets or polling?

WebSockets suit data that changes often and needs to reach the browser quickly. Polling can be enough for updates that happen rarely.

Why should I close a WebSocket connection?

An open connection can stop the browser from storing the page in the back-forward cache. Closing it when the user leaves keeps navigation fast.

Sources

This page is based on the official documentation below. Read it for full detail.

WebSockets — official documentation ↗
blozhikDeveloper news from across the web, explained. Every story links to its original sources.