Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Browser and Web APIs

The WebSocket object

Reference for the JavaScript WebSocket API: opening a connection, send(), message, open, close and error events, readyState, close codes and reconnecting.

A WebSocket keeps one connection open between the browser and a server so that either side can send messages at any time. Unlike an HTTP request, there is no request/response pairing: the server can push data the moment it exists, and the browser can send small messages without the overhead of new headers each time. That makes WebSockets a good fit for chat, live dashboards, multiplayer games and collaborative editing.

You create one with new WebSocket(url), using a ws:// or (preferably) wss:// address. The constructor returns immediately while the connection is made in the background; you react to events such as open, message, error and close.

JavaScript
const socket = new WebSocket("wss://example.com/live");
socket.addEventListener("message", (event) => console.log(event.data));

Try it

The sandboxed editors on this site have no network access, so these examples use a small in-memory stand-in with the same events. Your own code only has to swap in new WebSocket(url).

JS The events and readyState, with a stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Sending JSON and reconnecting with backoff

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
const socket = new WebSocket(url, protocols)
socket.send(data)
socket.close(code, reason)
Name Description
url A ws:// or wss:// URL. A page served over HTTPS should use wss://.
protocols Optional string or array naming subprotocols the client supports. The server picks one, readable as socket.protocol.
data A string, Blob, ArrayBuffer or typed array.
code Optional close code: 1000 for a normal close, or a number from 3000 to 4999 for your own use.
reason Optional short string (up to 123 bytes) explaining the close.

Properties: readyState (0 connecting, 1 open, 2 closing, 3 closed), bufferedAmount (bytes queued but not yet sent), binaryType ("blob" or "arraybuffer"), url, protocol, extensions.

Events: open, message (event.data), error (no details, by design) and close (event.code, event.reason, event.wasClean).

Exceptions: the constructor throws SyntaxError for an invalid URL or scheme and SecurityError for a blocked connection. send() throws InvalidStateError while the state is CONNECTING.

Usage notes

  • Wait for open before sending, or queue messages yourself.
  • Connections drop. WebSockets do not reconnect by themselves. On close, schedule a new connection with growing delays, as in the second example.
  • Send structured messages as JSON with a type field, and validate what you receive. Treat all incoming data as untrusted.
  • Backpressure. If you send a lot of data, watch bufferedAmount to avoid piling up memory.
  • Authentication. Browsers do not let you set custom headers on the handshake. Use cookies, a short-lived token in the URL, or send credentials as the first message.
  • Heartbeats. Idle connections may be closed by proxies. Send a small ping message every 20 to 30 seconds.
  • Not for everything. For one-way server updates, EventSource is simpler; for ordinary requests, use fetch().

Browser support

WebSocket is supported in every current browser. The newer WebSocketStream API, which adds backpressure, is not, so check a compatibility table before using it.