APIs & Integrations

WebSockets

WebSockets provide persistent, full-duplex communication channels over TCP. Master connection lifecycle, message protocols, reconnection strategies, heartbeats, and when to use WebSockets versus Server-Sent Events.

How do you use WebSockets in JavaScript?

Create a connection with new WebSocket("wss://example.com/socket"), listen for open, message, close and error events, and send data with socket.send(), usually JSON strings. The connection stays open in both directions, which makes it ideal for chat, live collaboration and multiplayer games. Handle disconnects by reconnecting with a backoff.

const socket = new WebSocket("wss://chat.example.com");
socket.addEventListener("open", () => socket.send(JSON.stringify({ type: "hello" })));
socket.addEventListener("message", (e) => addMessage(JSON.parse(e.data)));
socket.addEventListener("close", () => setTimeout(connect, 2000));

readyState Values

0 CONNECTINGHandshake in progress
1 OPENReady to send/receive
2 CLOSINGClose handshake in progress
3 CLOSEDConnection closed

Common Close Codes

1000Normal closure — expected close
1001Going away — page navigation/reload
1002Protocol error
1003Unsupported data type
1006Abnormal closure (no close frame)
1007Invalid frame payload data
1008Policy violation
1011Internal server error
4000Custom application error (4000–4999)

Common Pitfalls

Sending messages before connection is OPEN — messages silently dropped
Check ws.readyState === WebSocket.OPEN (1) before sending. Queue messages or wait for onopen.
No reconnection logic — one network hiccup kills the connection permanently
Implement reconnection with exponential backoff. Use a ReconnectingWebSocket wrapper or a library.
Memory leaks — attaching event listeners in React effects without cleanup
In React: return () => ws.close() from useEffect. Remove listeners and close connection on unmount.
Sending sensitive data as plain text WebSocket (ws://)
Always use wss:// (WebSocket Secure) in production. Plain ws:// is unencrypted — vulnerable to MITM attacks.

Interactive Demo

Code Editor

<input id="msg" value="Hello server!">
<button id="send">Send</button>
<ul id="log"></ul>

Preview

WebSockets — step by step

1 / 4
1

WebSocket connection lifecycle

new WebSocket(url) begins the handshake (HTTP Upgrade request). ws.onopen fires when the connection is established. Send messages with ws.send(data) — strings or binary (ArrayBuffer, Blob). Receive with ws.onmessage. ws.onclose fires when either side closes the connection. ws.onerror fires on network errors. The readyState property tracks current state (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED).

1 of 4
⚠️WebSockets are not always the right tool
WebSockets shine for high-frequency bidirectional communication. For server-to-client only updates (notifications, live feeds), Server-Sent Events (SSE) are simpler — they use regular HTTP, work through proxies, and reconnect automatically. For infrequent updates, HTTP polling with a proper cache strategy may be sufficient and simpler to scale.

🎯 Quick Check

What is the key advantage of WebSockets over HTTP polling?

WebSockets in JavaScript: summary

Key points

  • Always use wss:// in production.
  • Messages can arrive out of order across reconnects; include IDs or timestamps.
  • Socket.IO adds rooms, automatic reconnection and fallbacks on top of WebSockets.

Frequently asked questions

›How do I send JSON over a WebSocket?

socket.send(JSON.stringify(obj)) to send, and JSON.parse(event.data) to read.