{"id":12679,"library":"ws","title":"WebSocket Library for Node.js","description":"`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.","status":"active","version":"8.20.0","language":"javascript","source_language":"en","source_url":"https://github.com/websockets/ws","tags":["javascript","HyBi","Push","RFC-6455","WebSocket","WebSockets","real-time"],"install":[{"cmd":"npm install ws","lang":"bash","label":"npm"},{"cmd":"yarn add ws","lang":"bash","label":"yarn"},{"cmd":"pnpm add ws","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Optional binary addon for improved performance in masking and unmasking WebSocket frame payloads.","package":"bufferutil","optional":true},{"reason":"Optional binary polyfill for `buffer.isUtf8()` for performance, primarily relevant for Node.js versions prior to v18.14.0.","package":"utf-8-validate","optional":true}],"imports":[{"note":"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+).","wrong":"const WebSocket = require('ws')","symbol":"WebSocket","correct":"import WebSocket from 'ws'"},{"note":"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.","wrong":"const WebSocketServer = require('ws').Server","symbol":"WebSocketServer","correct":"import { WebSocketServer } from 'ws'"},{"note":"The `PerMessageDeflate` class, used for customizing the permessage-deflate extension, was explicitly exported starting from `ws` v8.20.0.","symbol":"PerMessageDeflate","correct":"import { PerMessageDeflate } from 'ws'"}],"quickstart":{"code":"import { WebSocketServer, WebSocket } from 'ws';\nimport * as http from 'http';\n\n// Create a simple HTTP server to attach the WebSocket server to\nconst server = http.createServer((req, res) => {\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('WebSocket server is running\\n');\n});\n\nconst wss = new WebSocketServer({ server });\n\nwss.on('connection', function connection(ws) {\n  console.log('Client connected');\n\n  ws.on('message', function message(data, isBinary) {\n    const message = isBinary ? data : data.toString();\n    console.log('Received:', message);\n\n    // Echo the message back to the client\n    ws.send(`Echo: ${message}`);\n  });\n\n  ws.on('close', () => {\n    console.log('Client disconnected');\n  });\n\n  ws.on('error', (error) => {\n    console.error('WebSocket error:', error);\n  });\n\n  ws.send('Welcome to the WebSocket server!');\n});\n\nserver.listen(8080, () => {\n  console.log('HTTP and WebSocket server listening on http://localhost:8080');\n\n  // Example client connecting to the server\n  const client = new WebSocket('ws://localhost:8080');\n\n  client.onopen = () => {\n    console.log('Client connected to WebSocket server');\n    client.send('Hello from client!');\n  };\n\n  client.onmessage = (event) => {\n    console.log('Client received:', event.data);\n    client.close(); // Close after receiving an echo\n  };\n\n  client.onerror = (error) => {\n    console.error('Client WebSocket error:', error);\n  };\n\n  client.onclose = () => {\n    console.log('Client disconnected');\n    server.close(); // Close the server after client disconnects\n  };\n});","lang":"typescript","description":"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."},"warnings":[{"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`.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"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.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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`.","severity":"breaking","affected_versions":"<8.17.1 || <7.5.10 || <6.2.3 || <5.2.4"},{"fix":"It is recommended to upgrade to `ws` v8.19.0 or newer to ensure continued compatibility and stability with upcoming Node.js versions.","message":"`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.","severity":"gotcha","affected_versions":"<8.19.0"},{"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`.","message":"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.","severity":"gotcha","affected_versions":">=7.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"The optional `bufferutil` binary addon, used for performance, is not installed or failed to compile for your specific Node.js environment.","error":"Cannot find module 'bufferutil'"},{"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.","cause":"Attempting to instantiate `ws.WebSocket` in a web browser environment, where the `ws` package is not designed to run.","error":"TypeError: WebSocket is not a constructor"},{"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();`.","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.","error":"The requested module 'ws' does not provide an export named WebSocketServer"},{"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.","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.","error":"HTTP/1.1 426 Upgrade Required"}],"ecosystem":"npm"}