Guide · Open source
How to use ws: a Node.js WebSocket library guide
Updated · written with AI from the project's own documentation and checked against our catalogue data
ws is an open-source WebSocket client and server library for Node.js. It lets a backend server and a client exchange messages over one persistent connection, which suits live, two-way features. This guide shows you how to install it, open a client connection, run a simple server and use a few options, so you can build a working WebSocket setup in Node.js.
Quick start
- 1Check your Node.js version. Confirm you run a Node.js version that the package supports. The README mentions older versions before v18.14.0 only for an optional module, so check the package for the current minimum.
- 2Install ws. In your project folder, run npm install ws to add the library.
- 3Create a server. Create a WebSocketServer on a port and handle the connection event for each client.
- 4Create a client. Create a WebSocket object with your server address and attach open, message and error handlers.
- 5Send and receive messages. Call send inside the open handler and read incoming data in the message handler.
- 6Add optional performance and compression. Optionally install bufferutil, and enable or tune permessage-deflate only if your workload needs it.
What ws is and where it runs
ws is a WebSocket implementation for Node.js, published under the MIT licence and written in JavaScript. It covers both the client role and the server role of the WebSocket protocol.
The README states that the module does not work in the browser. Browser code should use the native WebSocket object. If you need the same code to run on Node.js and in the browser, the README points to wrappers available on npm, such as isomorphic-ws.
Install ws with npm
Install ws from npm inside your Node.js project. The README lists this as the installation method.
Optionally, you can add the bufferutil module, a binary addon that the README says improves performance for operations such as masking and unmasking frame payloads. Prebuilt binaries are provided for popular platforms. To stop ws from using it, set the WS_NO_BUFFER_UTIL environment variable.
npm install ws
npm install --save-optional bufferutilSend and receive messages with a client
Create a WebSocket object with the server address, then attach handlers. The open event fires when the connection is ready, so send messages inside it. The message event receives incoming data. Always attach an error handler so connection problems are logged.
The README also shows sending binary data, such as a Float32Array, using the same send method.
- error: attach ws.on('error', console.error) to log failures.
- open: send your first message once the connection is established.
- message: read incoming data in the callback.
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});Run a simple WebSocket server
Create a WebSocketServer on a port. For each new client, the connection event gives you a socket object. Attach message and error handlers to it and use send to reply.
If you already run an HTTP or HTTPS server, pass it in with the server option instead of a port. The README's external server example shows this with an HTTPS server. To share one server between several WebSocket servers, use noServer: true and route upgrade requests yourself, as the README's multiple-servers example demonstrates.
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});Understand compression before you enable it
ws supports the permessage-deflate extension, which compresses message payloads. On the server it is disabled by default. On the client it is enabled by default, and you can turn it off by setting perMessageDeflate to false.
The README warns that compression adds significant overhead in performance and memory use, so enable it only when you need it. It also notes Node.js zlib issues under high concurrency on Linux. If you use it in production, test it against a workload that resembles yours. Options such as threshold, concurrencyLimit and the zlib options can be tuned.
const wss = new WebSocketServer({
port: 8080,
perMessageDeflate: {
threshold: 1024,
concurrencyLimit: 10
}
});Where to find the full API
The README links to doc/ws.md for Node.js-style documentation of the ws classes and utility functions. For options beyond the examples here, such as the full server options, check that file.
The README also has a FAQ covering how to get a client's IP address, how to detect and close broken connections, and how to connect through a proxy.
What people use it for
- Pushing live updates from a Node.js server to a client that stays connected.
- Building a backend WebSocket client that talks to another service.
- Running a WebSocket server alongside an existing HTTPS server on one port.
- Routing several WebSocket endpoints by path on one HTTP server, using noServer mode.
- Adding client authentication during the upgrade step, as the README's authentication example shows.
Frequently asked questions
Is ws free to use?
ws is published under the MIT licence, as stated in the project information. Check the LICENSE file in the repository for the full terms.
How do I install ws?
Run npm install ws in your Node.js project. The README lists this as the install command. You can add the optional bufferutil module with npm install --save-optional bufferutil.
Can I use ws in the browser?
No. The README says the module does not work in the browser. Use the native WebSocket object in browser code, or a wrapper such as isomorphic-ws if you want shared code.
Should I turn on permessage-deflate compression?
Only if you need it. The README says the extension is disabled by default on the server, adds significant performance and memory cost, and can run into Node.js zlib issues under high concurrency. Test it with a representative workload before using it in production.
How do I share one HTTP server with several WebSocket servers?
Create each WebSocketServer with noServer: true, listen for the upgrade event on your HTTP server, and call handleUpgrade based on the request path. The README's multiple-servers example shows the pattern.
How does ws compare to socket.io?
The project's comparison list includes socket.io, uWebSockets.js, faye-websocket and µWS. ws is a low-level library that implements the WebSocket protocol. This guide does not cover feature-by-feature comparisons, so check each project's documentation for details.
New agent skills, repos and AI tools — every week
The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.
Our verdict
ws suits Node.js developers who want a small, widely used WebSocket client and server that follows the protocol closely and has a documented API. It is a poor fit for browser-only front-end code, which should use the native WebSocket object, and for people who want a ready-made app rather than a code library.
Install options & downloads