Installations
npm install websocket-ts
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
22.13.1
NPM Version
10.9.2
Score
87.7
Supply Chain
99.6
Quality
84.7
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (99.16%)
JavaScript (0.84%)
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Developer
Download Statistics
Total Downloads
487,695
Last Day
1,256
Last Week
6,531
Last Month
33,261
Last Year
240,095
GitHub Statistics
MIT License
121 Stars
190 Commits
20 Forks
2 Watchers
5 Branches
1 Contributors
Updated on Mar 05, 2025
Bundle Size
10.50 kB
Minified
2.48 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.2.1
Package Id
websocket-ts@2.2.1
Unpacked Size
281.06 kB
Size
69.78 kB
File Count
133
NPM Version
10.9.2
Node Version
22.13.1
Published on
Feb 16, 2025
Total Downloads
Cumulative downloads
Total Downloads
487,695
Last Day
-7.2%
1,256
Compared to previous day
Last Week
-13.8%
6,531
Compared to previous week
Last Month
22.8%
33,261
Compared to previous month
Last Year
49.9%
240,095
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Features
- Lightweight & Standalone: No dependencies, 2.1 kB minified & gzipped.
- Browser-native: Utilizes WebSocket API, offers direct access.
- Smart Reconnect: Optional auto-reconnect and message buffering.
- Easy Setup: Optional builder class for quick initialization.
- Well-Tested: High test coverage, well-documented for extensibility.
- Module Support: Supports CommonJS and ES6 modules.
Installation
Install websocket-ts
with npm:
1$ npm install websocket-ts
Quickstart
This example shows how to use the package, complete with message buffering and automatic reconnection. The created websocket will echo back any received messages. It will buffer messages when disconnected and attempt to reconnect every 1 second.
1import { 2 ArrayQueue, 3 ConstantBackoff, 4 Websocket, 5 WebsocketBuilder, 6 WebsocketEvent, 7} from "websocket-ts"; 8 9// Initialize WebSocket with buffering and 1s reconnection delay 10const ws = new WebsocketBuilder("ws://localhost:8080") 11 .withBuffer(new ArrayQueue()) // buffer messages when disconnected 12 .withBackoff(new ConstantBackoff(1000)) // retry every 1s 13 .build(); 14 15// Function to output & echo received messages 16const echoOnMessage = (i: Websocket, ev: MessageEvent) => { 17 console.log(`received message: ${ev.data}`); 18 i.send(`echo: ${ev.data}`); 19}; 20 21// Add event listeners 22ws.addEventListener(WebsocketEvent.open, () => console.log("opened!")); 23ws.addEventListener(WebsocketEvent.close, () => console.log("closed!")); 24ws.addEventListener(WebsocketEvent.message, echoOnMessage);
Usage
This will demonstrate how to use websocket-ts
in your project using the provided WebsocketBuild
-class.
For a more detailed description of the API, please refer to the API Documentation.
Initialization
Create a new instance with the WebsocketBuilder
:
1const ws = new WebsocketBuilder("ws://localhost:42421").build();
Events
There are six events which can be subscribed to through with event listeners:
1export enum WebsocketEvent { 2 open = "open", // Connection opened 3 close = "close", // Connection closed 4 error = "error", // Error-induced closure 5 message = "message", // Message received 6 retry = "retry", // Reconnect attempt 7 reconnect = "reconnect" // Successful reconnect 8}
Add Event Listeners
Event listeners receive the websocket instance (i
) and the triggering event (ev
) as arguments.
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .onOpen((i, ev) => console.log("opened")) 3 .onClose((i, ev) => console.log("closed")) 4 .onError((i, ev) => console.log("error")) 5 .onMessage((i, ev) => console.log("message")) 6 .onRetry((i, ev) => console.log("retry")) 7 .onReconnect((i, ev) => console.log("reconnect")) 8 .build();
Remove Event Listeners
To unregister a specific event listener, use removeEventListener
:
1let ws: Websocket 2/* ... */ 3ws.removeEventListener(WebsocketEvent.open, openEventListener);
Send Message
Use the send
method to send a message to the server:
1let ws: Websocket; 2/* ... */ 3ws.send("Hello World!");
Reconnect & Backoff (Optional)
If you'd like the websocket to automatically reconnect upon disconnection, you can optionally provide a Backoff
strategy.
This sets the delay between reconnection attempts. There are three built-in Backoff
implementations, or you can create
your own by implementing the Backoff
interface. If no Backoff is provided, the websocket will not attempt to reconnect.
ConstantBackoff
The ConstantBackoff
strategy enforces a fixed delay between each reconnection attempt.
To set a constant 1-second wait time, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBackoff(new ConstantBackoff(1000)) // 1000ms = 1s 3 .build();
LinearBackoff
The LinearBackoff
strategy increases the delay between reconnection attempts linearly,
up to an optional maximum. For example, to start with a 0-second delay and increase by
10 second for each retry, capping at 60 seconds, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBackoff(new LinearBackoff(0, 10000, 60000)) // 0ms, 10s, 20s, 30s, 40s, 50s, 60s 3 .build();
ExponentialBackoff
The ExponentialBackoff
strategy doubles the delay between each reconnection attempt, up
to a specified maximum. This approach is inspired by the binary exponential backoff algorithm
commonly used in networking. For example, to generate a backoff series like [1s, 2s, 4s, 8s]
, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBackoff(new ExponentialBackoff(1000, 6)) // 1s, 2s, 4s, 8s, 16s, 32s, 64s 3 .build();
Buffer (Optional)
To buffer outgoing messages when the websocket is disconnected, you can optionally specify
a Queue
. This queue will temporarily store your messages and send them in sequence when
the websocket (re)connects. Two built-in Queue
implementations are available, or you can
create your own by implementing the Queue
interface. If no queue is provided, messages
won't be buffered.
RingQueue
The RingQueue
is a fixed-capacity, first-in-first-out (FIFO) queue. When it reaches capacity,
the oldest element is removed to accommodate new ones. Reading from the queue returns and
removes the oldest element. For instance, to set up a RingQueue
with a 100-element capacity,
use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBuffer(new RingQueue(100)) 3 .build();
ArrayQueue
The ArrayQueue offers an unbounded capacity, functioning as a first-in-first-out (FIFO) queue.
Reading from this queue returns and removes the oldest element. To use an ArrayQueue
, use:
1const ws = new WebsocketBuilder("ws://localhost:42421") 2 .withBuffer(new ArrayQueue()) 3 .build();
Build & Tests
To compile the project, execute npm run build
.
To run tests, use npm run test
.

No vulnerabilities found.
Reason
12 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
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 0/20 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/build.yml:1
- Warn: no topLevel permission defined: .github/workflows/coverage.yml:1
- Warn: no topLevel permission defined: .github/workflows/documentation.yml:1
- Warn: no topLevel permission defined: .github/workflows/lint.yml:1
- Warn: no topLevel permission defined: .github/workflows/package-npm.yml:1
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/build.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/build.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/coverage.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/coverage.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/coverage.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/coverage.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/documentation.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/documentation.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/documentation.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/documentation.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/documentation.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/documentation.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/lint.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/lint.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/package-npm.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/package-npm.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/package-npm.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/package-npm.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/test.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/jjxxs/websocket-ts/test.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/build.yml:15
- Warn: npmCommand not pinned by hash: .github/workflows/coverage.yml:15
- Warn: npmCommand not pinned by hash: .github/workflows/documentation.yml:18
- Warn: npmCommand not pinned by hash: .github/workflows/documentation.yml:19
- Warn: npmCommand not pinned by hash: .github/workflows/documentation.yml:20
- Warn: npmCommand not pinned by hash: .github/workflows/lint.yml:15
- Warn: npmCommand not pinned by hash: .github/workflows/package-npm.yml:20
- Warn: npmCommand not pinned by hash: .github/workflows/test.yml:15
- Info: 0 out of 12 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 0 out of 8 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
Project has not signed or included provenance with any releases.
Details
- Warn: release artifact v2.2.1 not signed: https://api.github.com/repos/jjxxs/websocket-ts/releases/200587447
- Warn: release artifact v2.1.5 not signed: https://api.github.com/repos/jjxxs/websocket-ts/releases/124192001
- Warn: release artifact v2.1.4 not signed: https://api.github.com/repos/jjxxs/websocket-ts/releases/121458499
- Warn: release artifact v2.1.3 not signed: https://api.github.com/repos/jjxxs/websocket-ts/releases/121457955
- Warn: release artifact v2.1.2 not signed: https://api.github.com/repos/jjxxs/websocket-ts/releases/121457501
- Warn: release artifact v2.2.1 does not have provenance: https://api.github.com/repos/jjxxs/websocket-ts/releases/200587447
- Warn: release artifact v2.1.5 does not have provenance: https://api.github.com/repos/jjxxs/websocket-ts/releases/124192001
- Warn: release artifact v2.1.4 does not have provenance: https://api.github.com/repos/jjxxs/websocket-ts/releases/121458499
- Warn: release artifact v2.1.3 does not have provenance: https://api.github.com/repos/jjxxs/websocket-ts/releases/121457955
- Warn: release artifact v2.1.2 does not have provenance: https://api.github.com/repos/jjxxs/websocket-ts/releases/121457501
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 13 are checked with a SAST tool
Score
4.4
/10
Last Scanned on 2025-03-10
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 MoreOther packages similar to websocket-ts
microsoft-cognitiveservices-speech-sdk
Microsoft Cognitive Services Speech SDK for JavaScript
light-websocket-client-ts
轻量 Websocket 封装
tsrpc
A TypeScript RPC Framework, with runtime type checking and built-in serialization, support both HTTP and WebSocket.
node-napcat-ts
napcat SDK for Node