Creating Node.js WebSocket Server

1. Installing ws Library

PackageNotes
wsDe-facto standard, no deps
uWebSockets.jsC++ binding, highest perf
socket.ioWS + fallbacks + rooms

Example: Install

npm install ws
npm install --save-dev @types/ws

2. Creating WebSocket Server

Example: Minimal server

import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws, req) => {
  ws.on("message", (data, isBinary) => ws.send(data, { binary: isBinary }));
});
OptionDescription
portBind port
hostBind interface
serverAttach to existing http server
pathOnly accept this URL path
noServerManual upgrade handling

3. Handling Server Events

EventArgs
connection(ws, req)
error(err)
close()
headers(headers, req)
listening()

4. Accessing Client Connections

Example: Iterate clients

for (const client of wss.clients) {
  if (client.readyState === 1) client.send(payload);
}
PropertyDetail
wss.clientsSet<WebSocket>
clientTracking: falseDisable set (save memory)

5. Handling Client Events

EventArgs
message(data, isBinary)
close(code, reason)
error(err)
ping / pong(data)
open() — client only

6. Accessing Request Info

Example: Read headers

wss.on("connection", (ws, req) => {
  const ip = req.headers["x-forwarded-for"] ?? req.socket.remoteAddress;
  const ua = req.headers["user-agent"];
  const url = new URL(req.url, `http://${req.headers.host}`);
});
FieldFrom
req.urlPath + query
req.headersHTTP upgrade headers
req.socket.remoteAddressPeer IP

7. Implementing HTTP Server Integration

Example: Share port with Express

import http from "node:http";
import express from "express";
import { WebSocketServer } from "ws";
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: "/ws" });
server.listen(3000);
ApproachUse
{ server }Single port for HTTP + WS
{ noServer: true }Manual upgrade handling for routing

8. Handling Multiple Servers

Example: Path-based routing

const chat = new WebSocketServer({ noServer: true });
const feed = new WebSocketServer({ noServer: true });
server.on("upgrade", (req, sock, head) => {
  const { pathname } = new URL(req.url, "http://x");
  const target = pathname === "/chat" ? chat : pathname === "/feed" ? feed : null;
  if (!target) return sock.destroy();
  target.handleUpgrade(req, sock, head, (ws) => target.emit("connection", ws, req));
});

9. Gracefully Shutting Down Server

StepAction
1Stop accepting new connections (wss.close())
2Broadcast going-away (1001)
3Wait for client close or timeout
4Terminate remaining sockets
5Close HTTP server

10. Broadcasting Messages

Example: Broadcast helper

function broadcast(msg, filter = () => true) {
  const data = typeof msg === "string" ? msg : JSON.stringify(msg);
  for (const c of wss.clients) {
    if (c.readyState === 1 && filter(c)) c.send(data);
  }
}
PatternUse
All clientsServer-wide announcement
Room/topicTag clients with channel set
Exclude senderChat fan-out