Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
Installations
npm install ws
Score
92.4
Supply Chain
100
Quality
85.9
Maintenance
100
Vulnerability
100
License
Developer
websockets
Developer Guide
Module System
CommonJS, ESM, UMD
Min. Node Version
>=10.0.0
Typescript Support
No
Node Version
22.4.0
NPM Version
10.8.1
Statistics
21,786 Stars
1,913 Commits
2,440 Forks
380 Watching
6 Branches
187 Contributors
Updated on 28 Nov 2024
Bundle Size
283.00 B
Minified
216.00 B
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
14,909,761,796
Last day
-7.5%
15,768,361
Compared to previous day
Last week
2.6%
92,539,564
Compared to previous week
Last month
11.4%
377,992,414
Compared to previous month
Last year
10.7%
3,910,174,225
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
2
ws: a Node.js WebSocket library
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation.
Passes the quite extensive Autobahn test suite: server, client.
Note: This module does not work in the browser. The client in the docs is a
reference to a backend with the role of a client in the WebSocket communication.
Browser clients must use the native
WebSocket
object. To make the same code work seamlessly on Node.js and the browser, you
can use one of the many wrappers available on npm, like
isomorphic-ws.
Table of Contents
Protocol support
- HyBi drafts 07-12 (Use the option
protocolVersion: 8
) - HyBi drafts 13-17 (Current default, alternatively option
protocolVersion: 13
)
Installing
npm install ws
Opt-in for performance
bufferutil is an optional module that can be installed alongside the ws module:
npm install --save-optional bufferutil
This is a binary addon that improves the performance of certain operations such as masking and unmasking the data payload of the WebSocket frames. Prebuilt binaries are available for the most popular platforms, so you don't necessarily need to have a C++ compiler installed on your machine.
To force ws to not use bufferutil, use the
WS_NO_BUFFER_UTIL
environment variable. This
can be useful to enhance security in systems where a user can put a package in
the package search path of an application of another user, due to how the
Node.js resolver algorithm works.
Legacy opt-in for performance
If you are running on an old version of Node.js (prior to v18.14.0), ws also supports the utf-8-validate module:
npm install --save-optional utf-8-validate
This contains a binary polyfill for buffer.isUtf8()
.
To force ws not to use utf-8-validate, use the
WS_NO_UTF_8_VALIDATE
environment variable.
API docs
See /doc/ws.md
for Node.js-like documentation of ws classes and
utility functions.
WebSocket compression
ws supports the permessage-deflate extension which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message.
The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed.
Note that Node.js has a variety of issues with high-performance compression, where increased concurrency, especially on Linux, can lead to catastrophic memory fragmentation and slow performance. If you intend to use permessage-deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.js/zlib will handle it with acceptable performance and memory usage.
Tuning of permessage-deflate can be done via the options defined below. You can
also use zlibDeflateOptions
and zlibInflateOptions
, which is passed directly
into the creation of raw deflate/inflate streams.
See the docs for more options.
1import WebSocket, { WebSocketServer } from 'ws';
2
3const wss = new WebSocketServer({
4 port: 8080,
5 perMessageDeflate: {
6 zlibDeflateOptions: {
7 // See zlib defaults.
8 chunkSize: 1024,
9 memLevel: 7,
10 level: 3
11 },
12 zlibInflateOptions: {
13 chunkSize: 10 * 1024
14 },
15 // Other options settable:
16 clientNoContextTakeover: true, // Defaults to negotiated value.
17 serverNoContextTakeover: true, // Defaults to negotiated value.
18 serverMaxWindowBits: 10, // Defaults to negotiated value.
19 // Below options specified as default values.
20 concurrencyLimit: 10, // Limits zlib concurrency for perf.
21 threshold: 1024 // Size (in bytes) below which messages
22 // should not be compressed if context takeover is disabled.
23 }
24});
The client will only use the extension if it is supported and enabled on the
server. To always disable the extension on the client, set the
perMessageDeflate
option to false
.
1import WebSocket from 'ws';
2
3const ws = new WebSocket('ws://www.host.com/path', {
4 perMessageDeflate: false
5});
Usage examples
Sending and receiving text data
1import WebSocket from 'ws'; 2 3const ws = new WebSocket('ws://www.host.com/path'); 4 5ws.on('error', console.error); 6 7ws.on('open', function open() { 8 ws.send('something'); 9}); 10 11ws.on('message', function message(data) { 12 console.log('received: %s', data); 13});
Sending binary data
1import WebSocket from 'ws'; 2 3const ws = new WebSocket('ws://www.host.com/path'); 4 5ws.on('error', console.error); 6 7ws.on('open', function open() { 8 const array = new Float32Array(5); 9 10 for (var i = 0; i < array.length; ++i) { 11 array[i] = i / 2; 12 } 13 14 ws.send(array); 15});
Simple server
1import { WebSocketServer } from 'ws'; 2 3const wss = new WebSocketServer({ port: 8080 }); 4 5wss.on('connection', function connection(ws) { 6 ws.on('error', console.error); 7 8 ws.on('message', function message(data) { 9 console.log('received: %s', data); 10 }); 11 12 ws.send('something'); 13});
External HTTP/S server
1import { createServer } from 'https'; 2import { readFileSync } from 'fs'; 3import { WebSocketServer } from 'ws'; 4 5const server = createServer({ 6 cert: readFileSync('/path/to/cert.pem'), 7 key: readFileSync('/path/to/key.pem') 8}); 9const wss = new WebSocketServer({ server }); 10 11wss.on('connection', function connection(ws) { 12 ws.on('error', console.error); 13 14 ws.on('message', function message(data) { 15 console.log('received: %s', data); 16 }); 17 18 ws.send('something'); 19}); 20 21server.listen(8080);
Multiple servers sharing a single HTTP/S server
1import { createServer } from 'http'; 2import { WebSocketServer } from 'ws'; 3 4const server = createServer(); 5const wss1 = new WebSocketServer({ noServer: true }); 6const wss2 = new WebSocketServer({ noServer: true }); 7 8wss1.on('connection', function connection(ws) { 9 ws.on('error', console.error); 10 11 // ... 12}); 13 14wss2.on('connection', function connection(ws) { 15 ws.on('error', console.error); 16 17 // ... 18}); 19 20server.on('upgrade', function upgrade(request, socket, head) { 21 const { pathname } = new URL(request.url, 'wss://base.url'); 22 23 if (pathname === '/foo') { 24 wss1.handleUpgrade(request, socket, head, function done(ws) { 25 wss1.emit('connection', ws, request); 26 }); 27 } else if (pathname === '/bar') { 28 wss2.handleUpgrade(request, socket, head, function done(ws) { 29 wss2.emit('connection', ws, request); 30 }); 31 } else { 32 socket.destroy(); 33 } 34}); 35 36server.listen(8080);
Client authentication
1import { createServer } from 'http'; 2import { WebSocketServer } from 'ws'; 3 4function onSocketError(err) { 5 console.error(err); 6} 7 8const server = createServer(); 9const wss = new WebSocketServer({ noServer: true }); 10 11wss.on('connection', function connection(ws, request, client) { 12 ws.on('error', console.error); 13 14 ws.on('message', function message(data) { 15 console.log(`Received message ${data} from user ${client}`); 16 }); 17}); 18 19server.on('upgrade', function upgrade(request, socket, head) { 20 socket.on('error', onSocketError); 21 22 // This function is not defined on purpose. Implement it with your own logic. 23 authenticate(request, function next(err, client) { 24 if (err || !client) { 25 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); 26 socket.destroy(); 27 return; 28 } 29 30 socket.removeListener('error', onSocketError); 31 32 wss.handleUpgrade(request, socket, head, function done(ws) { 33 wss.emit('connection', ws, request, client); 34 }); 35 }); 36}); 37 38server.listen(8080);
Also see the provided example using express-session
.
Server broadcast
A client WebSocket broadcasting to all connected WebSocket clients, including itself.
1import WebSocket, { WebSocketServer } from 'ws'; 2 3const wss = new WebSocketServer({ port: 8080 }); 4 5wss.on('connection', function connection(ws) { 6 ws.on('error', console.error); 7 8 ws.on('message', function message(data, isBinary) { 9 wss.clients.forEach(function each(client) { 10 if (client.readyState === WebSocket.OPEN) { 11 client.send(data, { binary: isBinary }); 12 } 13 }); 14 }); 15});
A client WebSocket broadcasting to every other connected WebSocket clients, excluding itself.
1import WebSocket, { WebSocketServer } from 'ws'; 2 3const wss = new WebSocketServer({ port: 8080 }); 4 5wss.on('connection', function connection(ws) { 6 ws.on('error', console.error); 7 8 ws.on('message', function message(data, isBinary) { 9 wss.clients.forEach(function each(client) { 10 if (client !== ws && client.readyState === WebSocket.OPEN) { 11 client.send(data, { binary: isBinary }); 12 } 13 }); 14 }); 15});
Round-trip time
1import WebSocket from 'ws'; 2 3const ws = new WebSocket('wss://websocket-echo.com/'); 4 5ws.on('error', console.error); 6 7ws.on('open', function open() { 8 console.log('connected'); 9 ws.send(Date.now()); 10}); 11 12ws.on('close', function close() { 13 console.log('disconnected'); 14}); 15 16ws.on('message', function message(data) { 17 console.log(`Round-trip time: ${Date.now() - data} ms`); 18 19 setTimeout(function timeout() { 20 ws.send(Date.now()); 21 }, 500); 22});
Use the Node.js streams API
1import WebSocket, { createWebSocketStream } from 'ws'; 2 3const ws = new WebSocket('wss://websocket-echo.com/'); 4 5const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); 6 7duplex.on('error', console.error); 8 9duplex.pipe(process.stdout); 10process.stdin.pipe(duplex);
Other examples
For a full example with a browser client communicating with a ws server, see the examples folder.
Otherwise, see the test cases.
FAQ
How to get the IP address of the client?
The remote IP address can be obtained from the raw socket.
1import { WebSocketServer } from 'ws'; 2 3const wss = new WebSocketServer({ port: 8080 }); 4 5wss.on('connection', function connection(ws, req) { 6 const ip = req.socket.remoteAddress; 7 8 ws.on('error', console.error); 9});
When the server runs behind a proxy like NGINX, the de-facto standard is to use
the X-Forwarded-For
header.
1wss.on('connection', function connection(ws, req) { 2 const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); 3 4 ws.on('error', console.error); 5});
How to detect and close broken connections?
Sometimes, the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord).
In these cases, ping messages can be used as a means to verify that the remote endpoint is still responsive.
1import { WebSocketServer } from 'ws'; 2 3function heartbeat() { 4 this.isAlive = true; 5} 6 7const wss = new WebSocketServer({ port: 8080 }); 8 9wss.on('connection', function connection(ws) { 10 ws.isAlive = true; 11 ws.on('error', console.error); 12 ws.on('pong', heartbeat); 13}); 14 15const interval = setInterval(function ping() { 16 wss.clients.forEach(function each(ws) { 17 if (ws.isAlive === false) return ws.terminate(); 18 19 ws.isAlive = false; 20 ws.ping(); 21 }); 22}, 30000); 23 24wss.on('close', function close() { 25 clearInterval(interval); 26});
Pong messages are automatically sent in response to ping messages as required by the spec.
Just like the server example above, your clients might as well lose connection without knowing it. You might want to add a ping listener on your clients to prevent that. A simple implementation would be:
1import WebSocket from 'ws'; 2 3function heartbeat() { 4 clearTimeout(this.pingTimeout); 5 6 // Use `WebSocket#terminate()`, which immediately destroys the connection, 7 // instead of `WebSocket#close()`, which waits for the close timer. 8 // Delay should be equal to the interval at which your server 9 // sends out pings plus a conservative assumption of the latency. 10 this.pingTimeout = setTimeout(() => { 11 this.terminate(); 12 }, 30000 + 1000); 13} 14 15const client = new WebSocket('wss://websocket-echo.com/'); 16 17client.on('error', console.error); 18client.on('open', heartbeat); 19client.on('ping', heartbeat); 20client.on('close', function clear() { 21 clearTimeout(this.pingTimeout); 22});
How to connect via a proxy?
Use a custom http.Agent
implementation like https-proxy-agent or
socks-proxy-agent.
Changelog
We're using the GitHub releases for changelog entries.
License
Stable Version
The latest stable version of the package.
Stable Version
8.18.0
HIGH
7
7.5/10
Summary
ws affected by a DoS when handling a request with many HTTP headers
Affected Versions
>= 8.0.0, < 8.17.1
Patched Versions
8.17.1
7.5/10
Summary
ws affected by a DoS when handling a request with many HTTP headers
Affected Versions
>= 7.0.0, < 7.5.10
Patched Versions
7.5.10
7.5/10
Summary
ws affected by a DoS when handling a request with many HTTP headers
Affected Versions
>= 6.0.0, < 6.2.3
Patched Versions
6.2.3
7.5/10
Summary
ws affected by a DoS when handling a request with many HTTP headers
Affected Versions
>= 2.1.0, < 5.2.4
Patched Versions
5.2.4
7.5/10
Summary
Denial of Service in ws
Affected Versions
>= 2.0.0, < 3.3.1
Patched Versions
3.3.1
7.5/10
Summary
Denial of Service in ws
Affected Versions
>= 0.2.6, < 1.1.5
Patched Versions
1.1.5
0/10
Summary
DoS due to excessively large websocket message in ws
Affected Versions
< 1.1.1
Patched Versions
1.1.1
MODERATE
3
5.3/10
Summary
ReDoS in Sec-Websocket-Protocol header
Affected Versions
>= 5.0.0, < 5.2.3
Patched Versions
5.2.3
5.3/10
Summary
ReDoS in Sec-Websocket-Protocol header
Affected Versions
>= 6.0.0, < 6.2.2
Patched Versions
6.2.2
5.3/10
Summary
ReDoS in Sec-Websocket-Protocol header
Affected Versions
>= 7.0.0, < 7.4.6
Patched Versions
7.4.6
LOW
1
0/10
Summary
Remote Memory Disclosure in ws
Affected Versions
< 1.0.1
Patched Versions
1.0.1
Reason
1 commit(s) and 12 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Info: Found linked content: SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: found token with 'none' permissions: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 7/30 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:49: update your workflow using https://app.stepsecurity.io/secureworkflow/websockets/ws/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:50: update your workflow using https://app.stepsecurity.io/secureworkflow/websockets/ws/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:68: update your workflow using https://app.stepsecurity.io/secureworkflow/websockets/ws/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:79: update your workflow using https://app.stepsecurity.io/secureworkflow/websockets/ws/ci.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:57
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 9 are checked with a SAST tool
Score
6.1
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More