Registry / http-networking / ws
library0.3.2jsnpmunverified

`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.

npm install ws
INSTALL
IMPORT
SIG · WS
W
ws
http-networkingjavascriptv0.3.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

WebSocket
✓ import WebSocket from 'ws'
✗ const WebSocket = require('ws')
For client-side WebSocket connections within Node.js, `WebSocket` is the default export. While CommonJS `require` is still supported, ESM imports are generally preferred in modern Node.js environments (v10+).
WebSocketServer
✓ import { WebSocketServer } from 'ws'
✗ const WebSocketServer = require('ws').Server
The WebSocket server constructor is a named export. Directly accessing `.Server` on the default CommonJS import is also common. Incorrectly using `import WebSocketServer from 'ws'` can lead to runtime errors in some ESM contexts.
PerMessageDeflate
✓ import { PerMessageDeflate } from 'ws'
The `PerMessageDeflate` class, used for customizing the permessage-deflate extension, was explicitly exported starting from `ws` v8.20.0.

Demonstrates how to set up a basic `ws` WebSocket server listening on an HTTP port, handle incoming messages, and how to connect to it using a `ws` client, sending and receiving text data.

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 }; });
Debug
Known issues
breakingThe `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.
fix
For browser environments, use the native `window.WebSocket` object. If isomorphic code (Node.js and browser compatible) is required, consider using a wrapper like `isomorphic-ws`.
affects: >=1.0.0
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.
fix
Install them as optional dependencies: `npm install --save-optional bufferutil utf-8-validate`. If you encounter build issues, ensure your system has the necessary C++ compiler tools. They can be explicitly disabled via `WS_NO_BUFFER_UTIL` and `WS_NO_UTF_8_VALIDATE` environment variables.
affects: >=1.0.0
breakingA 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`.
fix
Upgrade to `ws` v8.17.1 (or the latest patch in your major version line, e.g., 7.5.10, 6.2.3, 5.2.4) or newer immediately to mitigate this vulnerability. Consider configuring `server.maxHeadersCount` in Node.js HTTP servers if exposing them to untrusted clients.
affects: <8.17.1 || <7.5.10 || <6.2.3 || <5.2.4
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.
fix
It is recommended to upgrade to `ws` v8.19.0 or newer to ensure continued compatibility and stability with upcoming Node.js versions.
affects: <8.19.0
gotchaWhen 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.
fix
Ensure your project is configured correctly for ESM (`"type": "module"` in `package.json`) if using `import` statements. Use `import WebSocket from 'ws'` for the client and `import { WebSocketServer } = from 'ws'` for the server. For CommonJS, use `const WebSocket = require('ws')` and `const WebSocketServer = require('ws').Server`.
affects: >=7.0.0
Errors
Common errors & fixes
Cannot find module 'bufferutil'
The optional `bufferutil` binary addon, used for performance, is not installed or failed to compile for your specific Node.js environment.
fix
Install 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
Attempting to instantiate `ws.WebSocket` in a web browser environment, where the `ws` package is not designed to run.
fix
In 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
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.
fix
Ensure 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
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.
fix
Ensure 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.
Upgrade
Version history
0.3.2latest on npm
Audit
Dependencies
bufferutiloptionalOptional binary addon for improved performance in masking and unmasking WebSocket frame payloads.
utf-8-validateoptionalOptional binary polyfill for `buffer.isUtf8()` for performance, primarily relevant for Node.js versions prior to v18.14.0.
Agent activity
40 hits · last 30 days
node
36
OpenAI (training)
1
Resources
ws — npm install ws · libregistry