What is the ws library?
ws is a lightweight, fast, and battle-tested WebSocket library for Node.js, written in TypeScript. It provides both client and server implementations of the WebSocket protocol (RFC 6455). The library features minimal dependencies, high performance, and full support for modern WebSocket standards, including permessage-deflate compression.
Why do you need ws?
WebSocket is a bidirectional communication protocol over TCP that allows real-time data exchange between a client and a server without the need for constant HTTP requests. The ws library is essential for building applications requiring instant data transfer: chats, online games, stock quotes, notification systems, collaborative document editing, and any other real-time services.
How to install?
Installation via npm or yarn:
npm install wsyarn add wsFor TypeScript projects, no additional types are required — the library already includes type declarations.
Main features
- Bidirectional communication — simultaneous sending and receiving of messages.
- Automatic reconnection (implemented via user code, but the library provides all necessary events).
- Compression support (permessage-deflate) to reduce traffic.
- Buffer and string handling — sending both text and binary data.
- Event-driven model — handling open, message, close, error events.
- Clustering — support for working with multiple processes (via broadcast).
- WebSocket extensions — support for custom protocols and extensions.
TypeScript code example
Simple WebSocket server and client:
// server.tsimport { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => { console.log('Client connected');
ws.on('message', (data) => { console.log('Received:', data.toString()); ws.send('Hello from server!'); });
ws.on('close', () => { console.log('Client disconnected'); });});
console.log('Server running on port 8080');// client.tsimport WebSocket from 'ws';
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => { console.log('Connected to server'); ws.send('Hello from client!');});
ws.on('message', (data) => { console.log('Server response:', data.toString()); ws.close();});
ws.on('close', () => { console.log('Connection closed');});When to use ws?
The ws library is ideal for:
- Building high-load real-time applications (chat systems, online games).
- Real-time data broadcasting (stock data, IoT streams).
- Notification and alert systems.
- Collaborative work (collaborative editing, task boards).
- Servers running in a cluster or under PM2.
If you need a minimalistic, fast, and reliable WebSocket library for TypeScript/Node.js — ws is the de facto standard.