Skip to content

API in Capabilities

WebSocket API

Published Updated

WebSocket opens a two-way connection between a browser and a server. Events expose the text and binary messages. The standard can fail the WebSocket connection during the opening handshake or later for protocol- or API-level reasons; failing the connection closes it and fires error and close events (WebSockets Standard, WHATWG).

const socket = new WebSocket(url)
const socket = new WebSocket(url, protocol)
const socket = new WebSocket(url, protocols)
socket.send(data)
socket.close()
socket.close(code)
socket.close(code, reason)

The constructor accepts absolute and relative URLs with the ws or wss scheme. It also accepts http and https URLs. The standard changes http to ws and https to wss. It rejects a fragment and resolves a relative URL against the relevant settings object’s API base URL. Its optional second argument is one subprotocol string or a sequence of subprotocol strings. The server may establish the connection without selecting a subprotocol, in which case protocol is the empty string. If the server selects a subprotocol, that value must be one the client offered, and protocol returns the selected value after the handshake (WebSockets Standard: opening handshake, WHATWG).

send() accepts strings and binary data. Binary data may be a Blob or ArrayBuffer; an ArrayBufferView also works. Set binaryType to "arraybuffer" when incoming binary messages should arrive as ArrayBuffer; its default value is "blob". The standard does not expose protocol Ping or Pong frames through this API. RFC 6455 defines those control frames and lets either endpoint send them (RFC 6455 section 5.5, IETF).

BCD api.WebSocket records interface support including Chrome 5, Edge 12, Firefox 11 without a prefix, IE 10, Opera 12.1, Safari 5, and Opera Android 12.1. In that record, Chrome Android, Firefox for Android, Oculus Browser, Safari on iOS, Samsung Internet, WebView Android, and WebView on iOS use mirror entries. Under api.WebSocket.WebSocket.url_parameter_http_https_relative, BCD records support for http, https, and relative constructor URLs from Chrome 125, Firefox 124, and Safari 17.3. Chrome Android, Edge, Firefox for Android, Oculus Browser, Opera, Opera Android, Safari on iOS, Samsung Internet, WebView Android, and WebView on iOS use mirror entries for that behavior (WebSocket.json, MDN browser-compat-data).

Member Type Meaning
url USVString The URL used to establish the connection.
readyState unsigned short CONNECTING (0), OPEN (1), CLOSING (2), or CLOSED (3).
bufferedAmount unsigned long long Application-data bytes queued by send() but not yet transmitted to the network.
extensions DOMString Extensions selected by the server, or an empty string before selection.
protocol DOMString The selected subprotocol, or an empty string when none was selected.
binaryType BinaryType "blob" or "arraybuffer"; the initial value is "blob".
open Event Fires after the connection is established and readyState becomes OPEN.
message MessageEvent Carries a complete text or binary message in data.
error Event Fires when the connection fails.
close CloseEvent Reports code, reason, and whether the connection closed cleanly.

bufferedAmount counts UTF-8 text bytes and binary bytes queued by the script. It excludes WebSocket framing, operating-system buffers, and network-hardware buffers. Every send() invocation that does not throw increases bufferedAmount by the number of bytes needed to express the supplied data. If the closing handshake has started or the connection is closed, the browser discards the data. bufferedAmount still increases and does not reset to zero after closure. Check both readyState and an application queue limit before sending (WebSockets Standard, bufferedAmount, WHATWG; WebSockets Standard, send(), WHATWG).

RFC 7692 defines permessage-deflate, an extension that compresses WebSocket message payloads. The browser and server negotiate extensions during the opening handshake; read the result from extensions instead of assuming that compression was selected (RFC 7692, IETF).

Exception or event Condition
SyntaxError The constructor cannot parse the URL, the resulting scheme is not ws or wss, the URL contains a fragment, or a subprotocol is duplicated or invalid.
InvalidStateError send() is called while readyState is CONNECTING.
SyntaxError close() receives a UTF-8-encoded reason longer than 123 bytes.
InvalidAccessError close() receives a code other than 1000 or an integer from 3000 through 4999.
error followed by close Establishing the connection fails; the standard’s failure path closes the connection and fires close.

When send() runs in CLOSING or CLOSED, the standard discards the supplied data instead of transmitting it. A non-throwing call still increases bufferedAmount by the byte size of that data; after the connection is closed, later send() calls continue to increase the value (WebSockets Standard, send(), WHATWG; WebSockets Standard, bufferedAmount, WHATWG). When a connection disappears without a received Close frame, RFC 6455 defines the close code as 1006; code 1006 is reserved and cannot be passed to close() (RFC 6455 sections 7.1.5 and 7.4.1, IETF).

Start the local endpoint below before running the browser examples. It serves a page at http://localhost:8080, echoes WebSocket messages sent to /socket, and implements GET /api/updates?since=<cursor> for the polling fallback.

Running the local WebSocket and polling endpoint

Section titled “Running the local WebSocket and polling endpoint”

Create an empty directory. Run npm init -y followed by npm install ws, then save this code as server.mjs in that directory. Start it with node server.mjs and open http://localhost:8080 in a browser.

import { createServer } from "node:http";
import { WebSocketServer } from "ws";
const server = createServer((request, response) => {
const url = new URL(request.url, "http://localhost:8080");
if (url.pathname === "/api/updates") {
const previous = Number.parseInt(url.searchParams.get("since") || "0", 10);
const cursor = String(Number.isFinite(previous) ? previous + 1 : 1);
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ cursor, items: [{ type: "update", value: cursor }] }));
return;
}
response.writeHead(200, { "content-type": "text/html" });
response.end("<!doctype html><title>WebSocket demo</title><p>Open DevTools.</p>");
});
const sockets = new WebSocketServer({ noServer: true });
server.on("upgrade", (request, socket, head) => {
const url = new URL(request.url, "http://localhost:8080");
if (url.pathname !== "/socket") {
socket.destroy();
return;
}
sockets.handleUpgrade(request, socket, head, (webSocket) => {
sockets.emit("connection", webSocket, request);
});
});
sockets.on("connection", (socket) => {
socket.on("message", (data) => socket.send(data.toString()));
});
server.listen(8080, () => console.log("Listening on http://localhost:8080"));

The terminal prints Listening on http://localhost:8080. The browser page supplies the same origin used by the relative polling URL in the fallback example. The output named in the client examples below is illustrative.

Exchanging JSON and reporting a failed connection

Section titled “Exchanging JSON and reporting a failed connection”

Create handlers before sending. Wait for open, then validate message text before using it. This example reports malformed JSON and tells the user when the connection closes.

function connectChat(url, render, report) {
const socket = new WebSocket(url, "chat.v1");
socket.addEventListener("open", () => {
socket.send(JSON.stringify({ type: "hello", value: "browser" }));
});
socket.addEventListener("message", (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch (error) {
report(`Invalid JSON: ${error.message}`);
socket.close(1000, "invalid payload");
return;
}
render(message);
});
socket.addEventListener("error", () => report("WebSocket connection failed"));
socket.addEventListener("close", (event) => {
report(`Closed with code ${event.code}; clean=${event.wasClean}`);
});
return socket;
}
const socket = connectChat(
"ws://localhost:8080/socket",
(message) => console.log("message", message),
(status) => console.log("status", status),
);

With an endpoint that follows this echo contract, the console first prints the returned object. An invalid JSON message prints Invalid JSON: and starts a normal close with code 1000. A failed handshake reaches the error and close handlers; the error event itself does not expose an HTTP response status in the WebSocket API.

bufferedAmount lets a producer stop adding data when the browser’s application-data queue crosses a chosen application limit. The limit below is a policy in this example, not a protocol constant.

const MAX_QUEUED_BYTES = 256 * 1024;
function sendSample(socket, sample, onDeferred) {
if (socket.readyState !== WebSocket.OPEN) {
onDeferred(sample, "socket is not open");
return false;
}
const payload = JSON.stringify(sample);
const bytes = new TextEncoder().encode(payload).byteLength;
if (socket.bufferedAmount + bytes > MAX_QUEUED_BYTES) {
onDeferred(sample, "application queue limit reached");
return false;
}
socket.send(payload);
return true;
}
const accepted = sendSample(
socket,
{ type: "cursor", x: 12, y: 30 },
(sample, reason) => console.log("deferred", reason, sample),
);
console.log("accepted", accepted);

The function returns false without calling send() when the socket is not open or the local queue is above the selected limit. Keep or replace deferred samples according to the application’s delivery rules; bufferedAmount reports queued bytes but does not define that policy.

Detecting support and switching to polling

Section titled “Detecting support and switching to polling”

Detect the constructor before use. If it is missing, or if the socket fails before opening, stop the socket and start the documented HTTP polling route. The fallback remains useful only while the server implements that route.

async function startPolling(render, signal) {
let cursor = "";
while (!signal.aborted) {
const url = `/api/updates?since=${encodeURIComponent(cursor)}`;
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`Polling failed: HTTP ${response.status}`);
const batch = await response.json();
batch.items.forEach(render);
cursor = batch.cursor;
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
function subscribe(render) {
const controller = new AbortController();
if (!('WebSocket' in window)) {
startPolling(render, controller.signal).catch(console.error);
return () => controller.abort();
}
const socket = new WebSocket("ws://localhost:8080/socket");
let opened = false;
socket.addEventListener("open", () => { opened = true; });
socket.addEventListener("message", (event) => render(JSON.parse(event.data)));
socket.addEventListener("close", () => {
if (!opened) startPolling(render, controller.signal).catch(console.error);
}, { once: true });
return () => {
controller.abort();
if (socket.readyState === WebSocket.CONNECTING ||
socket.readyState === WebSocket.OPEN) {
socket.close(1000, "subscription stopped");
}
};
}

In a browser without WebSocket, the first request goes to /api/updates?since= and the local server returns an item whose first value is "1". If the constructor exists but the opening handshake fails, close starts the same route. The returned cleanup function aborts polling. Calling it while the socket is OPEN starts a WebSocket closing handshake; calling it while the socket is CONNECTING fails the connection; in CLOSING or CLOSED, it does not call close() again (WebSockets Standard: close(), WHATWG). To compare the transport with an alternative that offers streams and datagrams, use the WebTransport compatibility record.

This correction aligns the send() and bufferedAmount descriptions with the standard. Data passed to send() is not transmitted after the closing handshake starts, but every non-throwing call still increases bufferedAmount by the byte size of the supplied data, including calls made after the connection closes (WebSockets Standard, send(), WHATWG; WebSockets Standard, bufferedAmount, WHATWG). The original publishedAt date remains unchanged.

Specifications

SpecificationStatus
WebSockets Standard: The WebSocket interfaceWHATWG living standard
RFC 6455: The WebSocket ProtocolOther
RFC 7692: Compression Extensions for WebSocketOther