npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

js-websocket-reconnect-client

v0.0.15

Published

This is light-weight JavaScript WebSocket library that supports reconnect

Readme

WebSocket Client with Automatic Reconnect

npm version CI/CD codecov TypeScript

A lightweight, modern TypeScript WebSocket client library with automatic reconnection capabilities, comprehensive error handling, and full type safety.

✨ Features

  • 🔄 Automatic Reconnection - Intelligent reconnection with configurable retry strategies
  • 📦 TypeScript First - Full type safety and IntelliSense support
  • 🎯 Event-Driven - Clean event handler system
  • 🛡️ Error Handling - Robust error handling and recovery
  • 🧪 Well Tested - Comprehensive test suite with Vitest
  • 🌐 Universal - Works in browsers and Node.js environments
  • 📱 Lightweight - Minimal bundle size with zero dependencies

📦 Installation

Using yarn (recommended):

yarn add js-websocket-reconnect-client

Using npm:

npm install js-websocket-reconnect-client

Note: This project uses Yarn as the preferred package manager. All examples show both yarn and npm commands.

🚀 Quick Start

import WebSocketClient from 'js-websocket-reconnect-client';

const client = new WebSocketClient('ws://localhost:8080');

// Set up event handlers
client.addOnOpenHandler(() => {
  console.log('Connected to WebSocket server');
});

client.addOnMessageHandler((message, event) => {
  console.log('Received message:', message);
});

client.addOnCloseHandler((event) => {
  console.log('Connection closed:', event.code, event.reason);
});

client.addOnErrorHandler((event) => {
  console.error('WebSocket error:', event);
});

// Connect
client.connect();

// Send messages
client.send({ type: 'greeting', message: 'Hello Server!' });

🔧 Configuration

Constructor Options

new WebSocketClient(url, protocols?, options?)

Parameters

| Parameter | Type | Required | Description | |-----------|------|----------|-------------| | url | string | ✅ | WebSocket server URL | | protocols | string \| string[] | ❌ | Sub-protocols | | options | WebSocketClientOptions | ❌ | Configuration options |

Options Interface

interface WebSocketClientOptions {
  shouldReconnect?: boolean;          // Enable automatic reconnection (default: true)
  reconnectRetryTimeout?: number;     // Delay between reconnection attempts in ms (default: 1000)
  reconnectRetryMaxNumber?: number;   // Maximum number of reconnection attempts (default: 10)
  parsedMessage?: boolean;            // Auto-parse JSON messages (default: true)
  debug?: boolean;                    // Enable debug logging (default: false)
}

Example with Custom Options

const client = new WebSocketClient('ws://localhost:8080', ['wamp', 'soap'], {
  shouldReconnect: true,
  reconnectRetryTimeout: 2000,
  reconnectRetryMaxNumber: 5,
  parsedMessage: true,
  debug: true
});

📚 API Reference

Event Handlers

addOnOpenHandler(handler)

Set the connection open event handler.

client.addOnOpenHandler((event: Event) => {
  console.log('WebSocket connection opened');
});

addOnMessageHandler(handler)

Set the message received event handler.

client.addOnMessageHandler((message: any, event: MessageEvent) => {
  console.log('Message received:', message);
});

addOnCloseHandler(handler)

Set the connection close event handler.

client.addOnCloseHandler((event: CloseEvent) => {
  console.log('Connection closed:', event.code, event.reason);
});

addOnErrorHandler(handler)

Set the error event handler.

client.addOnErrorHandler((event: Event) => {
  console.error('WebSocket error occurred');
});

Connection Management

connect()

Establish WebSocket connection.

client.connect();

close(reconnect?: boolean)

Close the WebSocket connection.

client.close(); // Close permanently
client.close(true); // Close and allow reconnection

restart()

Restart the WebSocket connection.

client.restart();

send(data: any)

Send data through the WebSocket connection.

const success = client.send({ type: 'message', data: 'Hello!' });
if (success) {
  console.log('Message sent successfully');
}

Utility Methods

getCurrentState()

Get the current WebSocket connection state.

const state = client.getCurrentState(); // "CONNECTING" | "OPEN" | "CLOSING" | "CLOSED"

getUrl()

Get the WebSocket URL.

const url = client.getUrl();

getProtocol()

Get the active protocol.

const protocol = client.getProtocol();

getBinaryType()

Get the binary data type.

const binaryType = client.getBinaryType();

getBufferedAmount()

Get the amount of buffered data.

const buffered = client.getBufferedAmount();

🧪 Development

Prerequisites

  • Node.js 16.x or higher
  • npm or yarn

Setup

# Clone the repository
git clone https://github.com/ratep1/js-websocket-reconnect-client.git
cd js-websocket-reconnect-client

# Install dependencies
yarn install
# or
npm install

# Run tests
yarn test
# or
npm test

# Build the project
yarn build
# or
npm run build

# Run code quality checks
yarn check
# or
npm run check

Scripts

| Script | Description | |--------|-------------| | yarn build / npm run build | Build the project with Vite | | yarn build:watch / npm run build:watch | Build in watch mode with Vite | | yarn dev / npm run dev | Start Vite development server | | yarn test / npm test | Run Vitest tests | | yarn test:watch / npm run test:watch | Run tests in watch mode | | yarn test:coverage / npm run test:coverage | Run tests with coverage report | | yarn test:ui / npm run test:ui | Open Vitest UI for interactive testing | | yarn check / npm run check | Run Biome checks (lint + format) | | yarn check:fix / npm run check:fix | Fix Biome issues automatically | | yarn format / npm run format | Format code with Biome | | yarn format:check / npm run format:check | Check code formatting |

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🛠️ Built With

  • TypeScript - Type-safe JavaScript
  • Vite - Lightning-fast build tool
  • Vitest - Blazing fast testing framework
  • Biome - Fast formatter and linter

📈 Changelog

v0.0.13

  • 🎉 Complete modernization with TypeScript 5.x
  • ✅ Added comprehensive test suite
  • 🔧 Modern development tooling (ESLint, Prettier, Jest)
  • 📚 Updated documentation
  • 🐛 Fixed WebSocket state constants bug
  • 🚀 CI/CD pipeline with GitHub Actions

📚 Documentation


Made with ❤️ by ratep1