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

@profullstack/websocket-client

v0.3.0

Published

Robust WebSocket client with connection management, reconnection logic, and message handling

Downloads

23

Readme

@profullstack/websocket-client

A robust WebSocket client with connection management, reconnection logic, and message handling.

Features

  • Universal: Works in both browser and Node.js environments
  • Reconnection: Automatic reconnection with exponential backoff
  • Event-based: Simple event-based API
  • Message Queue: Queues messages sent before connection is established
  • Adapters: Pluggable adapters for different environments
  • Customizable: Configurable reconnection behavior, protocols, and headers

Installation

npm install @profullstack/websocket-client

Basic Usage

import { createWebSocketClient } from '@profullstack/websocket-client';

// Create a WebSocket client
const client = createWebSocketClient({
  url: 'wss://echo.websocket.org'
});

// Listen for connection open
client.on('open', () => {
  console.log('Connected!');
  
  // Send a message
  client.send('Hello WebSocket!');
  
  // Send a JSON message
  client.send({
    type: 'greeting',
    content: 'Hello from client!'
  });
});

// Listen for messages
client.on('message', (data) => {
  console.log('Received:', data);
});

// Listen for connection close
client.on('close', (event) => {
  console.log(`Connection closed: ${event.code} ${event.reason}`);
});

// Listen for errors
client.on('error', (error) => {
  console.error('WebSocket error:', error);
});

API Reference

Creating a WebSocket Client

import { createWebSocketClient } from '@profullstack/websocket-client';

const client = createWebSocketClient({
  // WebSocket server URL (required)
  url: 'wss://example.com/socket',
  
  // WebSocket protocols (optional)
  protocols: ['v1.protocol.example'],
  
  // Additional headers for the connection (Node.js only, optional)
  headers: {
    'Authorization': 'Bearer token123'
  },
  
  // Reconnection interval in milliseconds (default: 1000)
  reconnectInterval: 1000,
  
  // Maximum reconnection interval in milliseconds (default: 30000)
  maxReconnectInterval: 30000,
  
  // Reconnection decay factor (default: 1.5)
  reconnectDecay: 1.5,
  
  // Maximum number of reconnection attempts (default: Infinity)
  maxReconnectAttempts: 10,
  
  // Whether to automatically connect on instantiation (default: true)
  automaticOpen: true,
  
  // Whether to automatically reconnect on disconnect (default: true)
  automaticReconnect: true,
  
  // Function to determine whether to reconnect (default: always)
  shouldReconnect: (event) => event.code !== 1000,
  
  // Custom WebSocket adapter (default: auto-detect)
  adapter: null
});

Connection Management

// Connect to the WebSocket server
await client.connect();

// Disconnect from the WebSocket server
client.disconnect(1000, 'Normal closure');

// Manually trigger reconnection
client.reconnect();

Sending Messages

// Send a string message
client.send('Hello WebSocket!');

// Send a JSON message (automatically stringified)
client.send({
  type: 'greeting',
  content: 'Hello from client!'
});

// Send binary data (ArrayBuffer or Blob)
const buffer = new ArrayBuffer(8);
client.send(buffer);

Event Handling

// Connection opened
client.on('open', (event) => {
  console.log('Connected!');
});

// Message received
client.on('message', (data, event) => {
  console.log('Received:', data);
});

// Connection closed
client.on('close', (event) => {
  console.log(`Connection closed: ${event.code} ${event.reason}`);
});

// Connection error
client.on('error', (error) => {
  console.error('WebSocket error:', error);
});

// Reconnecting
client.on('reconnecting', (info) => {
  console.log(`Reconnecting... Attempt ${info.attempt} after ${info.interval}ms`);
});

// Reconnection failed
client.on('reconnect_failed', () => {
  console.error('Failed to reconnect after maximum attempts');
});

// Remove event listener
const onMessage = (data) => console.log('Received:', data);
client.on('message', onMessage);
client.off('message', onMessage);

Advanced Usage

Custom Adapter

import { createWebSocketClient, createBrowserAdapter } from '@profullstack/websocket-client';

// Create a custom adapter
const customAdapter = createBrowserAdapter();

// Use the custom adapter
const client = createWebSocketClient({
  url: 'wss://example.com/socket',
  adapter: customAdapter
});

Custom Reconnection Logic

const client = createWebSocketClient({
  url: 'wss://example.com/socket',
  
  // Custom reconnection interval
  reconnectInterval: 2000,
  
  // Maximum reconnection interval
  maxReconnectInterval: 60000,
  
  // Exponential backoff factor
  reconnectDecay: 2.0,
  
  // Maximum number of reconnection attempts
  maxReconnectAttempts: 5,
  
  // Custom logic to determine whether to reconnect
  shouldReconnect: (event) => {
    // Don't reconnect on normal closure or if the server is going away
    if (event.code === 1000 || event.code === 1001) {
      return false;
    }
    
    // Don't reconnect if the server rejected the connection
    if (event.code === 1003 || event.code === 1008 || event.code === 1009) {
      return false;
    }
    
    // Reconnect on all other close codes
    return true;
  }
});

Node.js Usage with Headers

import { createWebSocketClient } from '@profullstack/websocket-client';

const client = createWebSocketClient({
  url: 'wss://api.example.com/socket',
  headers: {
    'Authorization': 'Bearer token123',
    'User-Agent': 'MyApp/1.0',
    'X-Custom-Header': 'CustomValue'
  }
});

Browser Support

The WebSocket client works in all modern browsers that support the WebSocket API:

  • Chrome 4+
  • Firefox 4+
  • Safari 5+
  • Edge 12+
  • Opera 10.7+
  • iOS Safari 4.2+
  • Android Browser 4.4+
  • Chrome for Android 86+

Examples

See the examples directory for complete usage examples.

License

MIT