The 'ws' Library: WebSockets for Node.js Servers
The `ws` library is the standard for adding WebSocket servers to Node.js for real-time features like chat or live data feeds. It provides both server and client APIs for backend-to-backend communication.
WHY IT EXISTS Node.js's core http module handles the request-response cycle, which is unsuitable for persistent, bidirectional communication. WebSockets were created for this real-time need, and the ws library provides a robust, high-performance, and widely adopted implementation for the Node.js ecosystem.
THE MENTAL MODEL Think of ws as the equivalent of Node's built-in http module, but for the WebSocket protocol (ws://). It gives you the low-level tools to create a WebSocketServer that listens for connections, and a WebSocket client to connect to other servers, all within a Node.js environment. It's the foundational layer for real-time communication on the backend.
HOW IT WORKS After installing with npm install ws, you create a server by instantiating WebSocketServer and typically attaching it to an existing HTTP/S server. The server object emits a connection event for each new client. This event provides a client socket object with a send() method and a message event for sending and receiving data. The library handles the complex WebSocket handshake, protocol framing, and data masking, exposing a simple event-driven API. For maximum performance, you can optionally install binary addons like bufferutil.
WHEN TO USE IT Use ws to build a WebSocket server in Node.js. This is ideal for applications requiring real-time updates: live chat, collaborative editing tools, real-time monitoring dashboards, and multiplayer game servers. You can also use its client component for backend services that need to consume a third-party WebSocket API.
WHEN NOT TO USE IT The biggest mistake is trying to use ws in a web browser. Browsers have their own built-in WebSocket API for client-side connections; ws is strictly for Node.js environments. If you need higher-level features like automatic reconnection, rooms, or fallback transports, consider a framework like Socket.IO, which uses ws under the hood but adds more functionality.
ONE CANONICAL EXAMPLE A simple echo server that broadcasts every message it receives to all other connected clients:
const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) { ws.on('message', function message(data) { wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === 1) { // 1 is WebSocket.OPEN client.send(String(data)); } }); }); });
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.