What Is the WebSocket API? Open, Exchange Messages, and Close Browser Connections
The browser `WebSocket` API opens a persistent, bidirectional connection so a browser and server can send messages whenever they need to. After an HTTP-based opening handshake, they can keep exchanging messages over the same connection until it closes. This is useful for chat or collaborative editing, where either side may need to send an update first. The application still has to design reconnection, authentication, and message-flow control.
The browser WebSocket API opens a persistent, bidirectional connection so a browser and server can send messages whenever they need to. After an HTTP-based opening handshake, they can keep exchanging messages over the same connection until it closes. This is useful for chat or collaborative editing, where either side may need to send an update first. The application still has to design reconnection, authentication, and message-flow control.
How is WebSocket different from an HTTP request?
With ordinary HTTP, a client usually sends a request and the server returns a response, completing that exchange. If the server has new information, the client must request it again or use another transport. WebSocket starts with an HTTP handshake and then switches protocols, allowing both client and server to initiate messages over one connection. Messages can contain text or binary data. This is not an API that exposes raw TCP sockets to the browser: it is a web protocol and browser API with message boundaries. (RFC 6455, WHATWG WebSockets Standard)
The usual WebSocket scheme is ws://; wss:// protects the connection with TLS. Use wss:// for production connections from HTTPS pages so traffic is encrypted in transit. The browser API constructor accepts a URL and an optional list of subprotocols. A subprotocol, such as chat.v1, is a name the client and server use to agree on the application's message rules. A connection may fail if the server does not select one of the offered protocols. (WebSocket() constructor, WHATWG interface)
How does a connection open and close?
Calling new WebSocket(url, protocols) starts a connection attempt, and the object begins in the CONNECTING state. If the handshake succeeds, the browser fires open and changes the state to OPEN, when the application can send and receive. The connection passes through CLOSING as it shuts down and ends in CLOSED, including when it could not be opened. You can inspect the state with readyState.
To see the browser-side flow, replace the example address with a real WebSocket server's wss:// URL and run this in the developer-tools console. inventory.v1 and the JSON message shape below are an illustrative application contract. The server must implement the same subprotocol and message format; this example does not demonstrate a tested live server.
const socket = new WebSocket(
"wss://example.com/realtime",
["inventory.v1"]
);
socket.addEventListener("open", () => {
console.log("Connected", socket.protocol);
socket.send(JSON.stringify({
type: "subscribe",
itemId: "SKU-42"
}));
});
socket.addEventListener("message", (event) => {
try {
const message = JSON.parse(event.data);
console.log("Server message", message);
} catch {
console.log("Text message", event.data);
}
});
socket.addEventListener("error", () => {
console.error("WebSocket connection error");
});
socket.addEventListener("close", (event) => {
console.log("Connection closed", {
code: event.code,
reason: event.reason,
wasClean: event.wasClean
});
});Once the connection is open, the server can send updates through message, while the client can use send() for subscriptions, commands, or replies. send() places data in the outgoing queue; it does not guarantee that the data has already reached the network. Calling it while the socket is CONNECTING throws an exception. Calls while it is CLOSING or CLOSED are discarded. Wait for open and check the connection state before sending. (send(), readyState)
Call close() when the task is finished or the feature is being shut down. This begins the WebSocket closing handshake. If messages are already queued, the browser may send them before starting that handshake; do not assume close() immediately cancels pending sends. After the connection ends, the close event exposes code, reason, and wasClean. A reason is defined by the server and application protocol, so it has no universal meaning across implementations. (close(), CloseEvent)
How do you use it for real-time features?
In a chat interface, the browser can open a connection, send a user's message with send(), and display messages from other participants when message fires. WebSocket itself does not define whether a message was saved, which room it belongs to, or whether the sender is allowed to view that room. The client and server need an application protocol: for example, a JSON schema, event names, message IDs, error replies, and subscribe/unsubscribe commands.
When a transport connection drops, the application generally needs to open a new one and restore the state it needs. The browser API does not reconnect automatically. Use exponential backoff with random jitter when retrying so a service outage does not trigger a surge of reconnects, and resume subscriptions after the connection opens again. If events missed during a disconnect must be recovered, design a last-confirmed position, event sequence number, or server-side replay mechanism. These are application-layer guarantees, not features WebSocket provides automatically.
What should you do when messages accumulate?
The browser's standard WebSocket API has no automatic backpressure that slows a sender to match the receiver's processing rate. If a server sends messages faster than the application can process them, browser-side messages can accumulate, increasing memory use or slowing the interface. The outgoing queue can also grow if the client calls send() too quickly. (MDN WebSocket API)
Check bufferedAmount before sending to see how many bytes have been queued by send() but not yet transmitted over the network. An application can pause new sends above a chosen limit, combine older low-priority state updates, or reduce its sending rate. The receiver can also limit message size and frequency, and the server protocol can define acknowledgments, batching, or flow-control rules. bufferedAmount describes the browser's outgoing queue; it is not confirmation that the peer processed a message. (bufferedAmount, WHATWG WebSockets Standard)
WHATWG WebSocketStream is an alternative that provides a stream API with backpressure, but MDN currently describes it as experimental and non-standard, with limited browser support. Check compatibility rather than assuming it can replace standard WebSocket in production. (WebSocketStream)
How should you handle authentication and security?
wss:// protects traffic in transit with TLS, but it does not identify a user or decide whether a message is authorized. The server must authenticate the connection using a method suitable for its deployment, such as a session cookie, and validate authorization and input for each message. The browser constructor accepts a URL and subprotocols; it has no argument for arbitrary request headers such as Authorization. If the design requires an authorization header, work with the server team on a browser-compatible authentication flow. Avoid putting long-lived secrets in URL query strings because URLs may be captured in logs or history. (WHATWG constructor definition, RFC 6455 security considerations)
Browsers include an Origin in the connection request. In deployments that attach cookies automatically, a malicious site may try to use a visitor's browser to open a WebSocket connection. The server should compare the origin against an explicit allow-list and reject disallowed origins during the handshake. However, non-browser clients can forge Origin, so it is not authentication by itself. Also use input validation, per-message authorization, TLS, session expiry, and connection termination as appropriate. (RFC 6455 Origin considerations)
Should you choose WebSocket, Server-Sent Events, or HTTP?
| Need | Consider first | Reason and limitation |
|---|---|---|
| Browser and server frequently initiate messages in both directions on the same connection | WebSocket | Suits bidirectional messaging, but the application must design reconnection, flow control, authentication, and message rules. |
| The server pushes events to the browser, while client replies use separate HTTP requests | Server-Sent Events (SSE) with HTTP | A one-way server-to-client stream can be simpler; two-way interaction needs another request path. |
| The user reads or changes information only when making a request | HTTP request/response API | Often fits request-level caching, error handling, and common web infrastructure; frequent polling can add requests and delay. |
Long-lived connections also affect operations: servers must manage connection counts, deployments and restarts, proxy timeouts, horizontal scaling, and session state. If users only need a small number of timely server events, first consider whether HTTP or SSE meets the requirement. Choose WebSocket when the feature actually needs bidirectional messages.
Checklist before implementation
From an HTTPS page, does the server use `wss://` with a valid TLS certificate?
Does the server compare browser `Origin` values against an allow-list and account for cross-site risks with cookie sessions?
Do client and server agree on the subprotocol and text, binary, or JSON message format?
Are `error` and `close` events observed, and is reconnection behavior defined for relevant close codes?
Are subscription restoration and recovery of missed data defined after reconnecting?
Are message size, frequency, and an outgoing `bufferedAmount` limit defined to control memory and CPU use?
Does the server validate each message and check permissions for each user, channel, or operation?
References
[RFC 6455: The WebSocket Protocol](https://www.rfc-editor.org/rfc/rfc6455)
[WHATWG WebSockets Standard](https://websockets.spec.whatwg.org/)
[MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
[WebSocket() constructor](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket)
[readyState](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState)
[send()](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send)
[close()](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close)
[CloseEvent](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent)
[bufferedAmount](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/bufferedAmount)
[WebSocketStream](https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream)