Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

WebSocket Explained: What It Is, Why to Use It, and How to Build Real-Time Apps

A complete guide to WebSocket: how the handshake works, why it beats HTTP polling for real-time features, and how to build, secure and scale a WebSocket app with Node.js.

Sumit KumarUpdated Oct 8, 202610 min readNode.js
WebSocket Explained: What It Is, Why to Use It, and How to Build Real-Time Apps

Chat apps, live sports scores, stock tickers, collaborative editors and multiplayer games all share one need: data has to reach the user the moment it changes. Plain HTTP was never designed for that. WebSocket is the protocol that fills the gap, and in this guide you will learn what it is, why it exists, how it works under the hood, and how to build, secure and scale it with Node.js.

What is WebSocket?#

WebSocket is a communication protocol (standardised as RFC 6455) that gives you a persistent, full-duplex connection between a client and a server over a single TCP socket.

  • Persistent: the connection is opened once and stays open until either side closes it.
  • Full-duplex: both the client and the server can send messages at any time, independently of each other.
  • Lightweight: after the opening handshake, each message carries only a few bytes of framing overhead instead of a full set of HTTP headers.

WebSocket URLs use the ws:// scheme, or wss:// for the encrypted version (the WebSocket equivalent of HTTPS). Every modern browser supports it natively through the WebSocket API.

Why use WebSocket? The problem with HTTP#

HTTP follows a strict request-response model: the client asks, the server answers, and the exchange is over. The server cannot speak first. To build "live" features on top of that, developers used workarounds:

  • Short polling: the client asks "anything new?" every few seconds. Most answers are "no", which wastes bandwidth, server CPU and battery, and updates still arrive late.
  • Long polling: the server holds the request open until it has data, then the client immediately opens another. Better, but each message still pays for a new HTTP request with full headers.

The diagram below shows the difference. With polling, the client keeps knocking on the door. With WebSocket, the door stays open and either side can talk whenever it wants.

HTTP polling vs WebSocket: repeated requests compared with one open connection where the server pushes updates

HTTP polling vs WebSocket at a glance#

AspectHTTP pollingWebSocket
ConnectionNew request for every checkOne long-lived connection
DirectionClient asks, server answersBoth sides send any time
LatencyUp to one polling intervalNear-instant
Overhead per messageHundreds of bytes of headers2 to 14 bytes of framing
Server loadHigh, mostly empty responsesLow per message, but connections stay open
Best forRare, non-urgent updatesFrequent, real-time, two-way data

Common use cases#

  • Chat and messaging apps, typing indicators and read receipts
  • Live dashboards: stock prices, crypto tickers, sports scores, analytics
  • Collaborative tools such as shared documents and whiteboards
  • Multiplayer browser games
  • Notifications and activity feeds
  • IoT device telemetry and control

How WebSocket works under the hood#

Step 1: The opening handshake#

A WebSocket connection starts life as an ordinary HTTP request. The client sends a GET request with an Upgrade: websocket header and a random Sec-WebSocket-Key. If the server agrees, it replies with status 101 Switching Protocols and a Sec-WebSocket-Accept value derived from the key. From that point on, the same TCP connection stops speaking HTTP and starts carrying WebSocket frames.

WebSocket handshake: browser sends an HTTP Upgrade request, server replies 101 Switching Protocols, and the same TCP connection becomes a WebSocket

Here is what the raw exchange looks like:

HTTP
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Note

Because the handshake is plain HTTP on ports 80 and 443, WebSocket traffic passes through most firewalls and can share a port with your existing web server.

Step 2: Frames#

After the handshake, data travels as frames. Each frame has a tiny header that says what kind of frame it is:

  • Text frames carry UTF-8 text, usually JSON.
  • Binary frames carry raw bytes such as images, audio or Protocol Buffers.
  • Ping and pong frames check that the other side is still alive.
  • Close frames end the connection politely with a status code, for example 1000 for a normal closure.

Frames sent from the browser to the server are always masked with a random key. This protects intermediary proxies from cache-poisoning attacks; your code never has to deal with it directly.

Step 3: The connection lifecycle#

A browser WebSocket object moves through four states, exposed as readyState: CONNECTING (0), OPEN (1), CLOSING (2) and CLOSED (3). Your code reacts to four events: open, message, error and close.

WebSocket connection lifecycle: CONNECTING, OPEN, CLOSING and CLOSED readyStates with their events, a reconnect-with-backoff loop and a ping/pong heartbeat

How to use WebSocket: a hands-on example#

Let's build a small real-time chat. The server uses the popular ws library for Node.js, and the client uses the browser's built-in WebSocket API, so there is nothing to install on the front end.

1. Set up the project#

Bash
mkdir ws-chat && cd ws-chat
npm init -y
npm install ws

2. Write the server#

JavaScript
// server.js
const { WebSocketServer, WebSocket } = require('ws');

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (socket, req) => {
  console.log('Client connected from', req.socket.remoteAddress);

  socket.send(JSON.stringify({ type: 'welcome', text: 'Connected to chat!' }));

  socket.on('message', (raw) => {
    let msg;
    try {
      msg = JSON.parse(raw);
    } catch {
      return socket.send(JSON.stringify({ type: 'error', text: 'Invalid JSON' }));
    }

    // Broadcast to every connected client
    const payload = JSON.stringify({ type: 'chat', user: msg.user, text: msg.text });
    for (const client of wss.clients) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(payload);
      }
    }
  });

  socket.on('close', (code, reason) => {
    console.log('Client left:', code, reason.toString());
  });

  socket.on('error', (err) => console.error('Socket error:', err.message));
});

console.log('WebSocket server running on ws://localhost:8080');

Run it with node server.js. The connection event fires once per client, message fires for every frame received, and wss.clients holds every open socket so you can broadcast.

3. Write the client#

HTML
<input id="text" placeholder="Type a message">
<button id="send">Send</button>
<ul id="log"></ul>

<script>
  const socket = new WebSocket('ws://localhost:8080');
  const log = document.getElementById('log');

  socket.addEventListener('open', () => {
    console.log('Connected');
  });

  socket.addEventListener('message', (event) => {
    const msg = JSON.parse(event.data);
    const li = document.createElement('li');
    li.textContent = msg.type === 'chat' ? `${msg.user}: ${msg.text}` : msg.text;
    log.appendChild(li);
  });

  socket.addEventListener('close', (event) => {
    console.log('Disconnected', event.code);
  });

  document.getElementById('send').onclick = () => {
    const input = document.getElementById('text');
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify({ user: 'Sumit', text: input.value }));
      input.value = '';
    }
  };
</script>

Open the page in two browser tabs and send a message: it appears in both instantly, without any polling.

Tip

Always check socket.readyState === WebSocket.OPEN before calling send(). Sending while the socket is still connecting throws an error.

4. Design a simple message protocol#

WebSocket only moves bytes; it does not define what your messages mean. Agree on a small JSON envelope with a type field so both sides know how to handle each message:

JavaScript
{ "type": "chat",   "room": "general", "text": "Hello!" }
{ "type": "typing", "room": "general", "user": "sumit" }
{ "type": "join",   "room": "general" }

On the server, route on msg.type with a switch statement or a map of handlers. This keeps the code tidy as features grow.

Making it production-ready#

Heartbeats: detect dead connections#

If a phone loses signal or a laptop goes to sleep, the TCP connection can die silently and the server never receives a close frame. Use ping/pong heartbeats to find and clean up these zombie sockets:

JavaScript
wss.on('connection', (socket) => {
  socket.isAlive = true;
  socket.on('pong', () => { socket.isAlive = true; });
});

const interval = setInterval(() => {
  for (const socket of wss.clients) {
    if (!socket.isAlive) {
      socket.terminate(); // no pong since the last ping
      continue;
    }
    socket.isAlive = false;
    socket.ping();
  }
}, 30000);

wss.on('close', () => clearInterval(interval));

Browsers answer ping frames automatically, so no client code is needed for this part.

Automatic reconnection on the client#

Networks drop. A good client reconnects on its own, waiting a little longer after each failure (exponential backoff) so thousands of clients don't hammer the server at the same moment:

JavaScript
function connect(attempt = 0) {
  const socket = new WebSocket('wss://example.com/chat');

  socket.onopen = () => { attempt = 0; };

  socket.onclose = () => {
    const delay = Math.min(30000, 1000 * 2 ** attempt) + Math.random() * 1000;
    setTimeout(() => connect(attempt + 1), delay);
  };

  socket.onmessage = (event) => handleMessage(JSON.parse(event.data));
  return socket;
}

connect();

Security checklist#

  • Always use wss:// in production. It encrypts traffic with TLS, just like HTTPS.
  • Authenticate during the handshake. Validate a session cookie or a short-lived token before accepting the connection, then trust the socket for its lifetime.
  • Check the Origin header. Browsers don't apply CORS to WebSocket, so reject origins you don't recognise to prevent cross-site WebSocket hijacking.
  • Validate every message. Treat incoming data like any user input: parse safely, check types and lengths, and never execute it.
  • Limit message size and rate. Set maxPayload in ws and throttle chatty clients.

Here is how to verify a token and the origin before upgrading, by attaching ws to an existing HTTP server:

JavaScript
const http = require('http');
const { WebSocketServer } = require('ws');

const server = http.createServer();
const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });

server.on('upgrade', (req, socket, head) => {
  const url = new URL(req.url, 'http://localhost');
  const user = verifyToken(url.searchParams.get('token')); // your own auth check
  const allowedOrigin = req.headers.origin === 'https://jiocoder.com';

  if (!user || !allowedOrigin) {
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    return socket.destroy();
  }

  wss.handleUpgrade(req, socket, head, (ws) => {
    ws.user = user;
    wss.emit('connection', ws, req);
  });
});

server.listen(8080);
Warning

Tokens in the URL can end up in server logs. Prefer an HTTP-only session cookie, or send a short-lived, single-use token that expires within seconds.

Scaling WebSockets across multiple servers#

A single Node.js process can hold tens of thousands of idle connections, but eventually you'll run several servers behind a load balancer. That raises two problems:

  1. Connections are stateful. A client stays attached to the server it first connected to, so the load balancer must support WebSocket upgrades and long-lived connections. Sticky sessions are needed if you use a fallback transport such as long polling.
  2. Clients are split across servers. If User A is on Server 1 and User B is on Server 2, a broadcast from Server 1 never reaches User B.

The usual fix is a pub/sub backbone such as Redis, NATS or Kafka. Every server publishes outgoing events to a shared channel and subscribes to it, then pushes each event to its own local clients.

Scaling WebSockets: four clients behind a load balancer connect to Server A and Server B, which share messages through Redis Pub/Sub
JavaScript
const { createClient } = require('redis');

const pub = createClient();
const sub = pub.duplicate();
await Promise.all([pub.connect(), sub.connect()]);

// Deliver events from any server to local clients
await sub.subscribe('chat', (payload) => {
  for (const client of wss.clients) {
    if (client.readyState === WebSocket.OPEN) client.send(payload);
  }
});

// When a local client sends a message, publish it to every server
socket.on('message', (raw) => {
  pub.publish('chat', raw.toString());
});

Also remember to raise your reverse proxy's idle timeout. Nginx, for example, closes idle proxied connections after 60 seconds by default, so set proxy_read_timeout higher than your heartbeat interval.

ws vs Socket.IO: which should you use?#

Socket.IO is a library built on top of WebSocket. It is not plain WebSocket, so a Socket.IO client can only talk to a Socket.IO server.

Featurews (plain WebSocket)Socket.IO
ProtocolStandard WebSocketCustom protocol over WebSocket
Auto-reconnectWrite it yourselfBuilt in
Rooms and namespacesWrite it yourselfBuilt in
AcknowledgementsWrite it yourselfBuilt in
Fallback to long pollingNoYes
Bundle size and overheadMinimalLarger
Works with any WebSocket clientYesNo

Choose ws when you want speed, control and standard compatibility, for example when mobile apps or IoT devices connect too. Choose Socket.IO when you want rooms, reconnection and acknowledgements out of the box and you control both ends.

When not to use WebSocket#

WebSocket is powerful, but it isn't always the right tool:

  • Server-to-client only updates such as notifications or a live feed? Server-Sent Events (SSE) are simpler, run over plain HTTP and reconnect automatically.
  • Data that changes every few minutes? Ordinary HTTP requests with caching are cheaper and easier to operate.
  • Request-response APIs like CRUD operations belong on REST or GraphQL, which bring caching, status codes and tooling that WebSocket lacks.
  • Serverless-only stacks struggle with long-lived connections unless you use a managed service such as AWS API Gateway WebSocket APIs.
NeedBest choice
Two-way, low-latency messagingWebSocket
One-way server pushServer-Sent Events
Occasional updatesHTTP polling or plain requests
Standard data fetchingREST or GraphQL

Key takeaways#

  • WebSocket keeps one TCP connection open so the client and server can both send messages at any time, with very low overhead.
  • It starts as an HTTP request with Upgrade: websocket and switches protocols after a 101 response.
  • Use it for chat, live dashboards, games, collaboration and anything that needs instant two-way updates.
  • In production, add heartbeats, client reconnection with backoff, wss://, handshake authentication, origin checks and message validation.
  • Scale horizontally with a load balancer that supports upgrades plus a pub/sub layer such as Redis.
  • Pick SSE for one-way push and plain HTTP for infrequent updates; WebSocket shines when data flows both ways.