Creating WebSocket Connections (Client-Side)

1. Creating Client Connection

SignatureDescription
new WebSocket(url)Open connection
new WebSocket(url, protocol)Single subprotocol
new WebSocket(url, protocols[])Preferred-order list

Example: Basic connect

const ws = new WebSocket("wss://api.example.com/ws");
ws.addEventListener("open", () => console.log("connected"));

2. Creating Secure Connection

RequirementDetail
Valid TLS certBrowsers reject self-signed in prod
TLS 1.2+1.3 preferred
SNIRequired for shared hosts
HSTSInherits from origin

3. Specifying Subprotocols

Example: Subprotocol negotiation

const ws = new WebSocket("wss://x.example.com/ws", ["chat.v2", "chat.v1"]);
ws.addEventListener("open", () => console.log("active:", ws.protocol));
AspectDetail
OrderMost preferred first
NegotiationServer picks one (or none)
FailureIf none chosen, server should close

4. Setting Connection URL

PropertyValue
ws.urlResolved URL (read-only)
Note: The URL is fixed at construction; you cannot change it after.

5. Checking Connection State

Example: State check

if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "ping" }));
StateNumeric
WebSocket.CONNECTING0
WebSocket.OPEN1
WebSocket.CLOSING2
WebSocket.CLOSED3

6. Setting Binary Type

ValueEffect on incoming binary
"blob" (default)Delivered as Blob
"arraybuffer"Delivered as ArrayBuffer

Example: ArrayBuffer mode

ws.binaryType = "arraybuffer";
ws.addEventListener("message", (e) => {
  if (e.data instanceof ArrayBuffer) decode(new DataView(e.data));
});

7. Using WebSocket Properties

PropertyTypeDescription
urlstringResolved URL
readyStatenumberConnection state
bufferedAmountnumberQueued bytes not yet sent
extensionsstringNegotiated extensions
protocolstringNegotiated subprotocol
binaryTypestring"blob" / "arraybuffer"

8. Feature Detection

Example: Detect support

if (typeof WebSocket === "undefined") {
  showLegacyFallback();
}
CheckMeaning
"WebSocket" in windowAPI present
WebSocket.CLOSING === 2Spec-compliant

9. Handling Browser Compatibility

ConcernMitigation
Old browsersUse Socket.IO / SockJS fallback
Safari deflate quirksDisable permessage-deflate if issues
Mobile backgroundReconnect on visibility change

10. Using WebSocket in Workers

Example: WS inside Web Worker

// worker.js
const ws = new WebSocket("wss://api.example.com/ws");
ws.addEventListener("message", (e) => self.postMessage(e.data));
self.onmessage = (e) => ws.send(e.data);
ContextSupported?
Dedicated WorkerYes
Shared WorkerYes
Service WorkerLimited Support (no persistent WS)