What is the WebSocket API?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
WebSocket gives you a persistent, two-way connection between browser and server. Unlike HTTP, where the client asks and the server answers, either side can send a message at any time over a connection that stays open.
const socket = new WebSocket("wss://example.com/live");
socket.addEventListener("open", () => socket.send("hello"));
socket.addEventListener("message", (e) => console.log(e.data));
socket.addEventListener("close", (e) => console.log("closed", e.code));
socket.addEventListener("error", () => console.log("connection failed"));
The connection starts as a normal HTTP request carrying an Upgrade: websocket header, then switches protocol. That is why it works through the same ports as HTTP and passes most firewalls. Always use wss:// in production — ws:// is unencrypted and browsers block it on HTTPS pages.
When it is the right choice
Use it when the server needs to push data the client did not ask for, and when messages flow both ways frequently: chat, collaborative editing, multiplayer games, live dashboards.
When something simpler is better
- Polling — fine when updates are rare and a few seconds of delay is acceptable.
- Server-Sent Events — if data only flows server to client, SSE is far simpler: it runs over plain HTTP and reconnects automatically. Notifications and live feeds usually fit here.
What the API does not do for you
socket.send(JSON.stringify({ type: "ping" })); // you handle serialisation
There is no built-in reconnection, no message acknowledgement, no automatic heartbeat. A connection can drop silently, so production code sends periodic pings and reconnects with exponential backoff. Libraries such as Socket.IO exist mainly to provide those pieces. Also check socket.readyState before sending — calling send() before the connection opens throws.
