| |

Node.js 59 🟢 Low-Level Real-Time WebSockets with the ws Library

⏱️ Estimated read: 12 min | |

A WebSocket connection begins as an HTTP request. The client sends an Upgrade header, the server responds with 101 Switching Protocols, and the TCP socket transitions from request-response to full-duplex messaging. The ws library implements this handshake and the framing that follows. It is the most widely deployed WebSocket library in the Node.js ecosystem, with over 320 million downloads per month and close to a million dependent repositories . It is deliberately low-level: no fallbacks, no rooms, no reconnection. Those are built on top of it, or replaced by a higher-level library like Socket.IO.

Key point: A WebSocket server is stateful. Every open connection is a reference held in memory, and every message is a frame on that connection. The server must track the clients, route the messages, and clean up the references when connections close. A missing close handler is a memory leak.


Why the ws library exists

The handshake problem. A WebSocket connection starts as an HTTP request with an Upgrade header. The server must respond with the correct Sec-WebSocket-Accept value, which is derived from the client’s Sec-WebSocket-Key. The ws library implements the handshake and the framing, so the application only sees connection, message, close, and error events .

The frame problem. After the handshake, data travels as WebSocket frames. Each frame has an opcode, a length, and a payload mask. The ws library handles the framing, the masking, the fragmentation, and the control frames (ping, pong, close) .

The stateful-connection problem. An HTTP server handles each request independently. A WebSocket server holds a reference to every open connection. The application must store the references, broadcast to them, and remove them on close .

The performance problem. The ws library is a thin wrapper around Node.js’s socket and crypto modules. It is fast because it does not add a protocol layer. Optional binary addons (bufferutil and utf-8-validate) speed up masking and UTF-8 validation further .

The browser problem. The ws library is for Node.js backends. It does not run in a browser. A browser client uses the native WebSocket object, which is part of the WebSocket standard .

The fallback problem. The ws library does not provide a fallback for clients that do not support WebSockets. Socket.IO does, and it is the right choice when the client environment is unknown. The ws library is the right choice when the client is a modern browser or a Node.js backend .


a. The server

The WebSocketServer class accepts connections. It can listen on its own port, or attach to an existing HTTP server.

The standalone server

import { WebSocketServer } from 'ws';

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

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    console.log('received: %s', data);
  });
  ws.send('something');
});

The port option creates the server on that port. The connection event fires for each new client, and the ws argument is the connection object .

The attached server

An HTTP server handles the initial request, and the ws server attaches to the upgrade event.

import { createServer } from 'http';
import { WebSocketServer } from 'ws';

const server = createServer();
const wss = new WebSocketServer({ server });

server.listen(8080);

The server option attaches the WebSocket server to the HTTP server. The HTTP server must be listening for the WebSocket to accept connections .

The Express integration

import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';

const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });

app.get('/', (req, res) => res.send('Hello'));

server.listen(3000);

The Express app handles the HTTP routes, and the ws server handles the WebSocket upgrade on the same port .

The multiple-server pattern

A single HTTP server can host multiple WebSocket servers on different paths.

import { createServer } from 'http';
import { WebSocketServer } from 'ws';

const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });

server.on('upgrade', (request, socket, head) => {
  const { pathname } = new URL(request.url, 'wss://base.url');
  if (pathname === '/foo') {
    wss1.handleUpgrade(request, socket, head, (ws) => {
      wss1.emit('connection', ws, request);
    });
  } else if (pathname === '/bar') {
    wss2.handleUpgrade(request, socket, head, (ws) => {
      wss2.emit('connection', ws, request);
    });
  } else {
    socket.destroy();
  }
});

server.listen(8080);

The noServer: true option disables the automatic server, and the handleUpgrade method is called manually for each path .


b. The connection object

Each connection is a WebSocket object. It has events, methods, and properties that describe the connection’s state.

The events

EventFires when
openThe connection is established
messageA message arrives
closeThe connection closes
errorAn error occurs
pingA ping frame arrives
pongA pong frame arrives

The readyState property

The readyState property is a number: 0 for CONNECTING, 1 for OPEN, 2 for CLOSING, 3 for CLOSED .

if (ws.readyState === WebSocket.OPEN) {
  ws.send('message');
}

The check is required before every send, because sending on a closed connection throws.

The send method

ws.send('text message');
ws.send(JSON.stringify({ type: 'chat', text: 'hello' }));
ws.send(new Uint8Array([1, 2, 3]));

The send method accepts strings, Buffer, TypedArray, and ArrayBuffer. Strings are sent as text frames; binary data is sent as binary frames .

The close method

ws.close(1000, 'Normal closure');

The close method starts the closing handshake. The code is a number, and the reason is a string of at most 123 bytes .

The ping and pong

ws.ping();
ws.on('pong', () => {
  ws.isAlive = true;
});

The ping and pong frames are used to detect dead connections. The server sends a ping periodically, and the client responds with a pong .


c. The broadcast and room patterns

A broadcast sends a message to all connected clients. A room sends a message to a subset.

The broadcast

function broadcast(data, exclude = null) {
  wss.clients.forEach((client) => {
    if (client !== exclude && client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
}

The wss.clients is a Set of all open connections. The loop checks the readyState before sending .

The room pattern

A room is a Map of room names to Set of connections.

const rooms = new Map();

function joinRoom(ws, roomName) {
  if (!rooms.has(roomName)) {
    rooms.set(roomName, new Set());
  }
  rooms.get(roomName).add(ws);
  ws.room = roomName;
}

function broadcastToRoom(roomName, data, exclude = null) {
  const room = rooms.get(roomName);
  if (!room) return;
  room.forEach((client) => {
    if (client !== exclude && client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
}

The room is removed when the last client leaves .

The client tracking

const clients = new Set();

wss.on('connection', (ws) => {
  clients.add(ws);

  ws.on('close', () => {
    clients.delete(ws);
  });
});

The close handler removes the reference. A missing cleanup is a memory leak .

The message routing

ws.on('message', (data) => {
  const message = JSON.parse(data.toString());

  switch (message.type) {
    case 'chat':
      broadcast(JSON.stringify(message), ws);
      break;
    case 'typing':
      broadcastToRoom(ws.room, JSON.stringify(message), ws);
      break;
    default:
      ws.send(JSON.stringify({ type: 'error', message: 'Unknown type' }));
  }
});

The type field is the routing key. The server dispatches to the appropriate handler .


Complete Example Session

// ============================================
// PART 1: THE BASIC SERVER
// ============================================

import { WebSocketServer } from 'ws';

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

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    console.log('received: %s', data);
  });
  ws.send('something');
});

// ============================================
// PART 2: THE CHAT SERVER
// ============================================

const clients = new Set();

wss.on('connection', (ws) => {
  clients.add(ws);

  ws.on('message', (data) => {
    const message = JSON.parse(data);
    broadcast(JSON.stringify(message), ws);
  });

  ws.on('close', () => {
    clients.delete(ws);
  });
});

function broadcast(data, exclude = null) {
  clients.forEach((client) => {
    if (client !== exclude && client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
}

// ============================================
// PART 3: THE ROOM SERVER
// ============================================

const rooms = new Map();

ws.on('message', (data) => {
  const message = JSON.parse(data);

  if (message.action === 'join') {
    if (!rooms.has(message.room)) {
      rooms.set(message.room, new Set());
    }
    rooms.get(message.room).add(ws);
    ws.room = message.room;
  }

  if (message.action === 'chat') {
    broadcastToRoom(ws.room, JSON.stringify(message), ws);
  }
});

// ============================================
// PART 4: THE HEARTBEAT
// ============================================

const interval = setInterval(() => {
  wss.clients.forEach((ws) => {
    if (ws.isAlive === false) return ws.terminate();
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);

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

// ============================================
// PART 5: THE EXPRESS INTEGRATION
// ============================================

import express from 'express';
import { createServer } from 'http';

const app = express();
const server = createServer(app);
const wss2 = new WebSocketServer({ server });

app.get('/', (req, res) => res.send('Hello'));

server.listen(3000);

// ============================================
// PART 6: THE COMPLETE PATTERN
// ============================================

// 1. Create the WebSocketServer.
// 2. Track the clients in a Set.
// 3. Handle connection, message, close, and error.
// 4. Broadcast and room patterns.
// 5. Heartbeat with ping/pong.
// 6. Clean up on close.

The six parts showed the basic server, the chat server, the room server, the heartbeat, the Express integration, and the complete pattern.


Quick Reference

The Server Options

OptionPurpose
portListen on its own port
serverAttach to an HTTP server
noServerManual upgrade handling
perMessageDeflateCompression
maxPayloadMaximum message size

The Connection Events

EventFires when
openConnection established
messageMessage arrives
closeConnection closes
errorError occurs
pingPing frame arrives
pongPong frame arrives

The Connection Methods

MethodPurpose
send(data)Send a message
close(code, reason)Close the connection
ping()Send a ping
terminate()Force close

The readyState Values

ValueConstant
0CONNECTING
1OPEN
2CLOSING
3CLOSED

The Broadcast Pattern

PatternData Structure
Broadcast allwss.clients
Client trackingSet<WebSocket>
RoomMap<string, Set<WebSocket>>
Heartbeatws.isAlive flag

Best Practices

✅ Do This:

// Track clients in a Set.
const clients = new Set();
clients.add(ws);  // ✅

// Clean up on close.
ws.on('close', () => {
  clients.delete(ws);
});  // ✅

// Check readyState before send.
if (ws.readyState === WebSocket.OPEN) {
  ws.send(data);
}  // ✅

// Use ping/pong for heartbeat.
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });  // ✅

// Parse JSON in a try/catch.
try {
  const message = JSON.parse(data);
} catch (e) {
  ws.send(JSON.stringify({ type: 'error' }));
}  // ✅

// Limit the payload size.
new WebSocketServer({ maxPayload: 1024 * 1024 });  // ✅

❌ Don’t Do This:

// Don't forget to remove the client on close.
clients.add(ws);  // ❌ Memory leak

// Don't send without checking readyState.
ws.send(data);  // ❌ Throws on closed connection

// Don't skip the heartbeat.
// Dead connections accumulate.  // ❌

// Don't trust the client's JSON.
JSON.parse(data);  // ❌ Wrap in try/catch

// Don't use a single Set for rooms.
// Use a Map of Sets.  // ❌

// Don't enable perMessageDeflate without testing.
// It adds significant overhead.  // ❌

Common Pitfalls

PitfallWhy It HappensFix
Memory leakclose handler missingRemove the reference
Send throwsreadyState not checkedCheck before send
Dead connectionsNo heartbeatPing/pong interval
JSON parse errorMalformed messageTry/catch
Broadcast to closedreadyState not checkedCheck in the loop
Room not cleanedclose handler missingRemove from room
Payload too largeNo limitSet maxPayload

Real-World Examples

1. Basic Server

const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
  ws.send('something');
});

2. Broadcast

wss.clients.forEach((client) => {
  if (client.readyState === WebSocket.OPEN) {
    client.send(data);
  }
});

3. Room

const rooms = new Map();
rooms.get(roomName).add(ws);

4. Heartbeat

setInterval(() => {
  wss.clients.forEach((ws) => {
    if (ws.isAlive === false) return ws.terminate();
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);

5. Express

const server = createServer(app);
const wss = new WebSocketServer({ server });

6. Cleanup

ws.on('close', () => {
  clients.delete(ws);
});

7. JSON Routing

ws.on('message', (data) => {
  const message = JSON.parse(data);
  switch (message.type) { /* ... */ }
});

8. Multiple Servers

const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });

9. Payload Limit

new WebSocketServer({ maxPayload: 1024 * 1024 });

10. Compression

new WebSocketServer({ perMessageDeflate: true });

Visual

The WebSocket Handshake

┌────────────────────────────────────────────────────────────┐
│  THE WEBSOCKET HANDSHAKE                                   │
│                                                            │
│  CLIENT                          SERVER                    │
│  ──────                          ──────                    │
│                                                            │
│  GET /chat HTTP/1.1                                        │
│  Upgrade: websocket                                        │
│  Connection: Upgrade                                       │
│  Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==              │
│  ──────────────────────────────▶                          │
│                                                            │
│                              HTTP/1.1 101 Switching Protocols│
│                              Upgrade: websocket            │
│                              Connection: Upgrade           │
│                              Sec-WebSocket-Accept: s3pPL...│
│  ◀──────────────────────────────                          │
│                                                            │
│  The TCP connection is now a WebSocket.                    │
│  Frames flow in both directions.                           │
└────────────────────────────────────────────────────────────┘

The Stateful Connection

┌────────────────────────────────────────────────────────────┐
│  STATEFUL CONNECTIONS                                      │
│                                                            │
│  SERVER MEMORY                                             │
│  ┌──────────────────────────────────────────────────┐     │
│  │  clients = Set<WebSocket>                         │     │
│  │                                                   │     │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐           │     │
│  │  │ ws1     │  │ ws2     │  │ ws3     │           │     │
│  │  │ OPEN    │  │ OPEN    │  │ OPEN    │           │     │
│  │  └─────────┘  └─────────┘  └─────────┘           │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  ON CLOSE:                                                 │
│  ┌──────────────────────────────────────────────────┐     │
│  │  clients.delete(ws);                              │     │
│  │                                                   │     │
│  │  The reference is removed.                        │     │
│  │  The garbage collector frees the memory.          │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  A missing cleanup is a memory leak.                       │
└────────────────────────────────────────────────────────────┘

The Heartbeat

┌────────────────────────────────────────────────────────────┐
│  THE HEARTBEAT                                             │
│                                                            │
│  Every 30 seconds:                                         │
│  ┌──────────────────────────────────────────────────┐     │
│  │  For each client:                                 │     │
│  │    if (ws.isAlive === false) → ws.terminate()     │     │
│  │    ws.isAlive = false                             │     │
│  │    ws.ping()                                      │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  On pong:                                                  │
│  ┌──────────────────────────────────────────────────┐     │
│  │  ws.isAlive = true                                │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  A client that does not respond is terminated.             │
│  Dead connections do not accumulate.                       │
└────────────────────────────────────────────────────────────┘

The Broadcast and Room

┌────────────────────────────────────────────────────────────┐
│  BROADCAST AND ROOM                                        │
│                                                            │
│  BROADCAST                                                 │
│  ┌──────────────────────────────────────────────────┐     │
│  │  wss.clients.forEach((client) => {                │     │
│  │    if (client.readyState === WebSocket.OPEN) {    │     │
│  │      client.send(data);                           │     │
│  │    }                                              │     │
│  │  });                                              │     │
│  │                                                   │     │
│  │  Sends to every open connection.                  │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  ROOM                                                      │
│  ┌──────────────────────────────────────────────────┐     │
│  │  rooms.get(roomName).forEach((client) => {        │     │
│  │    if (client !== ws && client.readyState === OPEN)│    │
│  │      client.send(data);                           │     │
│  │  });                                              │     │
│  │                                                   │     │
│  │  Sends only to the clients in the room.           │     │
│  └──────────────────────────────────────────────────┘     │
└────────────────────────────────────────────────────────────┘

Summary

ItemValue
wsThe standard Node.js WebSocket library
WebSocketServerThe server class
connectionFires for each new client
messageFires when a message arrives
closeFires when the connection closes
readyStateThe connection state (0-3)
sendSends a message
wss.clientsThe set of open connections
HeartbeatPing/pong for dead connection detection
maxPayloadThe maximum message size

Key takeaways:

  • The ws library implements the WebSocket protocol for Node.js. It handles the HTTP upgrade handshake, the frame parsing, and the control frames. The application sees connection, message, close, and error events .
  • A WebSocket server is stateful. Every open connection is a reference held in memory. The server must track the clients, route the messages, and remove the references on close. A missing close handler is a memory leak .
  • The readyState must be checked before every send. Sending on a closed connection throws. The check is client.readyState === WebSocket.OPEN .
  • The heartbeat detects dead connections. The server sends a ping periodically, and the client responds with a pong. A client that does not respond is terminated .
  • The broadcast pattern iterates over wss.clients. The loop checks the readyState and sends to every open connection. The room pattern uses a Map of Set objects .
  • The message routing uses a type field. The server parses the JSON, reads the type, and dispatches to the appropriate handler. The pattern is {"type": "messageType", "payload": {...}} .
  • The ws library does not run in a browser. It is for Node.js backends. A browser client uses the native WebSocket object .
  • The perMessageDeflate option adds compression. It is disabled by default on the server and enabled on the client. It adds significant overhead and should be tested before production use .

Remember: The ws library is the low-level WebSocket implementation for Node.js. It handles the handshake, the framing, and the control frames, and it exposes a stateful connection object with send, close, and readyState. The application tracks the clients, broadcasts the messages, routes them by type, and cleans up the references on close. The heartbeat keeps dead connections from accumulating. The result is a real-time channel that pushes data to the client without polling, and a server that maintains the connections for as long as they are useful.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!