WebSocket Library for Node.js
`ws` is a highly performant, thoroughly tested WebSocket client and server implementation designed specifically for Node.js environments. As of version 8.20.0, it provides robust support for the WebSocket protocol, including the permessage-deflate extension for compression and passing the extensive Autobahn test suite. It differentiates itself through its focus on speed, reliability, and full protocol compliance in Node.js. `ws` maintains an active release cadence, frequently addressing bug fixes, performance improvements, and minor features. It's crucial to note that `ws` is intended for backend Node.js applications; browser-based WebSocket clients should use the native `WebSocket` API or a wrapper like `isomorphic-ws`. The library offers both server and client capabilities, allowing Node.js to act as either endpoint in WebSocket communication.
Common errors
-
Cannot find module 'bufferutil'
cause The optional `bufferutil` binary addon, used for performance, is not installed or failed to compile for your specific Node.js environment.fixInstall it as an optional dependency: `npm install --save-optional bufferutil`. If compilation fails, ensure you have Python and C++ build tools installed, or use the `WS_NO_BUFFER_UTIL=1` environment variable to disable its use. -
TypeError: WebSocket is not a constructor
cause Attempting to instantiate `ws.WebSocket` in a web browser environment, where the `ws` package is not designed to run.fixIn web browsers, use the native `window.WebSocket` constructor. If you see `ReferenceError: WebSocket is not defined`, it's the same root cause – `ws` isn't providing the browser global. -
The requested module 'ws' does not provide an export named WebSocketServer
cause This typically occurs in an ES Modules context when `import { WebSocketServer } from 'ws'` is used, but the environment or `package.json` configuration is not correctly set up for ESM, or if there's confusion with the default CommonJS export.fixEnsure your `package.json` has `"type": "module"`. If still facing issues or sticking with CommonJS, use `const { WebSocketServer } = require('ws');` or `const WebSocket = require('ws'); const wss = new WebSocket.Server();`. -
HTTP/1.1 426 Upgrade Required
cause A regular HTTP client is attempting to connect to a WebSocket server without performing the correct WebSocket handshake, or the handshake itself is malformed/unsupported.fixEnsure your client is initiating a proper WebSocket connection (e.g., `new WebSocket('ws://...')` in a browser or Node.js client) and that the server is correctly configured to handle WebSocket upgrade requests.
Warnings
- breaking The `ws` package is designed exclusively for Node.js environments and does not function directly in web browsers. Attempting to use it in a browser will result in errors.
- gotcha `bufferutil` and `utf-8-validate` are optional binary addons that can significantly improve `ws` performance for specific operations. Without them, `ws` will fall back to slower JavaScript implementations.
- breaking A Denial of Service (DoS) vulnerability (CVE-2024-37890) was fixed in `ws` v8.17.1 (and backports to v7.5.10, v6.2.3, v5.2.4). Prior versions could crash if a client sent a request with an excessive number of HTTP headers, exceeding `server.maxHeadersCount`.
- gotcha `ws` v8.19.0 included a fix for a 'forthcoming breaking change in Node.js core'. Older `ws` versions might encounter compatibility issues with future Node.js releases if not updated.
- gotcha When using `ws` with ES Modules (ESM) in Node.js, there can be confusion between the default import (`import WebSocket from 'ws'`) for the client and the named import (`import { WebSocketServer } from 'ws'`) for the server. Some environments or configurations might default to CommonJS behavior, leading to import errors.
Install
-
npm install ws -
yarn add ws -
pnpm add ws
Imports
- WebSocket
const WebSocket = require('ws')import WebSocket from 'ws'
- WebSocketServer
const WebSocketServer = require('ws').Serverimport { WebSocketServer } from 'ws' - PerMessageDeflate
import { PerMessageDeflate } from 'ws'
Quickstart
import { WebSocketServer, WebSocket } from 'ws';
import * as http from 'http';
// Create a simple HTTP server to attach the WebSocket server to
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('WebSocket server is running\n');
});
const wss = new WebSocketServer({ server });
wss.on('connection', function connection(ws) {
console.log('Client connected');
ws.on('message', function message(data, isBinary) {
const message = isBinary ? data : data.toString();
console.log('Received:', message);
// Echo the message back to the client
ws.send(`Echo: ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
ws.send('Welcome to the WebSocket server!');
});
server.listen(8080, () => {
console.log('HTTP and WebSocket server listening on http://localhost:8080');
// Example client connecting to the server
const client = new WebSocket('ws://localhost:8080');
client.onopen = () => {
console.log('Client connected to WebSocket server');
client.send('Hello from client!');
};
client.onmessage = (event) => {
console.log('Client received:', event.data);
client.close(); // Close after receiving an echo
};
client.onerror = (error) => {
console.error('Client WebSocket error:', error);
};
client.onclose = () => {
console.log('Client disconnected');
server.close(); // Close the server after client disconnects
};
});