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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cloudsignal/mqtt-client

v2.2.1

Published

CloudSignal WebSocket MQTT Client Library - Enterprise-grade MQTT client with V2 token management, AI agent communication patterns, and multi-transport support

Readme

CloudSignal WebSocket Client Library

Enterprise-grade MQTT client library for CloudSignal platform with V2 token authentication, AI agent communication patterns, and multi-platform support.

Features

  • V2 Token Authentication - Automatic token management with refresh scheduling
  • External IdP Support - Supabase, Firebase, Auth0, Clerk, OIDC integration
  • AI Agent Patterns - Request/response with MQTT 5 correlation
  • Multi-Transport - WebSocket (wss://) and native MQTT (mqtts://)
  • Platform Presets - Mobile, desktop, agent, and server configurations
  • Offline Queue - Messages queued during disconnection
  • Auto-Reconnect - Configurable reconnection with exponential backoff

Service URLs

| Service | URL | Purpose | |---------|-----|--------| | Token Service | https://auth.cloudsignal.app | JWT exchange, token refresh | | MQTT Broker | wss://connect.cloudsignal.app:18885/ | WebSocket connection | | REST Publisher | https://rest-publisher.cloudsignal.app | Server-side publish API | | Dashboard | https://dashboard.cloudsignal.app | Web management console |

Installation

Browser (CDN)

<!-- Latest version -->
<script src="https://cdn.cloudsignal.io/CloudSignalWS.js"></script>

<!-- Specific version (recommended for production) -->
<script src="https://cdn.cloudsignal.io/cloudsignal-mqtt.v2.2.0.js"></script>

npm

npm install @cloudsignal/mqtt-client

Quick Start

Basic Connection

import CloudSignal from '@cloudsignal/mqtt-client'

const client = new CloudSignal({ debug: true })

await client.connect({
  host: 'wss://connect.cloudsignal.app:18885/',
  username: 'user@org_abc123',
  password: 'your-token',
  clientId: 'my-client'
})

client.onMessage((topic, message) => {
  console.log('Received:', topic, message)
})

await client.subscribe('my/topic')
client.transmit('my/topic', { hello: 'world' })

V2 Token Authentication

const client = new CloudSignal({
  tokenServiceUrl: 'https://auth.cloudsignal.app',
  preset: 'desktop'
})

// Connect with automatic token management
await client.connectWithToken({
  host: 'wss://connect.cloudsignal.app:18885/',
  organizationId: 'your-org-uuid',
  secretKey: 'cs_live_xxxxx',
  userEmail: '[email protected]',
  userName: 'John Doe'
})

// Token auto-refreshes before expiration

External Identity Provider

const client = new CloudSignal({
  tokenServiceUrl: 'https://auth.cloudsignal.app'
})

// Connect via Supabase (or Firebase, Auth0, Clerk)
await client.connectWithToken({
  host: 'wss://connect.cloudsignal.app:18885/',
  organizationId: 'your-org-uuid',
  externalToken: supabaseSession.access_token
})

// Note: 'idToken' is also supported as an alias for 'externalToken'
// The provider is auto-detected from your organization's configuration

AI Agent Request/Response

const client = new CloudSignal({
  preset: 'agent',
  enableRequestResponse: true
})

await client.connect({ /* ... */ })

// Send request and await response
const response = await client.request(
  'agents/assistant/query',
  { question: 'What is CloudSignal?' },
  { timeout: 30000 }
)
console.log('Agent response:', response)

// Handle incoming requests
client.onRequest(async (topic, payload, respond) => {
  const answer = await processQuery(payload.question)
  await respond({ answer })
})

Mobile Optimization

const client = new CloudSignal({
  preset: 'mobile',
  // Override specific settings
  keepalive: 30,
  offlineQueueEnabled: true
})

API Reference

Constructor

new CloudSignal(options)

Options:

  • debug (boolean): Enable verbose logging. Default: false
  • preset (string): Platform preset ('mobile', 'desktop', 'agent', 'server')
  • autoDetectPlatform (boolean): Auto-detect and apply optimal settings. Default: false
  • tokenServiceUrl (string): CloudSignal token service URL (use https://auth.cloudsignal.app)
  • enableRequestResponse (boolean): Enable request/response pattern. Default: false

Connection Options:

  • keepalive (number): Keepalive interval in seconds. Default: 45
  • connectTimeout (number): Connection timeout in ms. Default: 30000
  • reconnectPeriod (number): Reconnect interval in ms. Default: 5000
  • cleanSession (boolean): Use clean session. Default: false
  • reconnectOnAuthError (boolean): Retry connection on auth errors. Default: false
  • maxAuthRetries (number): Max reconnect attempts for auth errors. Default: 0

Mobile Options:

  • offlineQueueEnabled (boolean): Queue messages when offline. Default: false
  • offlineQueueMaxSize (number): Max queued messages. Default: 100

Connection Methods

connect(config)

Connect to CloudSignal MQTT broker with credentials.

await client.connect({
  host: 'wss://connect.cloudsignal.app:18885/',
  username: 'user@org_id',
  password: 'token',
  clientId: 'optional-client-id',
  willTopic: 'status/user',       // Optional: Last will topic
  willMessage: 'offline',          // Optional: Last will message
  willQos: 1                       // Optional: Last will QoS
})

connectWithToken(config)

Connect using V2 token authentication.

// Direct authentication
await client.connectWithToken({
  host: 'wss://connect.cloudsignal.app:18885/',
  organizationId: 'org-uuid',
  secretKey: 'cs_live_xxxxx',
  userEmail: '[email protected]',
  userName: 'John Doe',            // Optional
  metadata: { role: 'admin' }      // Optional
})

// External IdP authentication (Supabase, Firebase, Auth0, Clerk)
await client.connectWithToken({
  host: 'wss://connect.cloudsignal.app:18885/',
  organizationId: 'org-uuid',
  externalToken: 'jwt-from-provider'  // Your IdP's access/ID token
})
// Note: 'idToken' is supported as an alias for backward compatibility

disconnect()

Disconnect from broker.

destroy()

Disconnect and cleanup all resources.

Messaging Methods

subscribe(topic, qos)

Subscribe to a topic.

await client.subscribe('my/topic', 1)  // QoS 1
await client.subscribe('data/#')        // Wildcard

unsubscribe(topic)

Unsubscribe from a topic.

await client.unsubscribe('my/topic')

transmit(topic, message, options)

Publish a message.

// Simple
client.transmit('topic', 'message')

// With options
client.transmit('topic', { data: 123 }, {
  qos: 1,
  retain: true,
  properties: {
    userProperties: { key: 'value' }
  }
})

onMessage(callback)

Register message handler.

client.onMessage((topic, message, packet) => {
  console.log(topic, message)
  // packet contains MQTT 5 properties
})

Request/Response Methods

Requires enableRequestResponse: true in constructor.

request(topic, payload, options)

Send request and await response.

const response = await client.request(
  'service/endpoint',
  { action: 'query' },
  { timeout: 10000 }  // Optional timeout
)

onRequest(handler)

Handle incoming requests.

client.onRequest(async (topic, payload, respond) => {
  const result = await processRequest(payload)
  await respond(result)
})

State Methods

isConnected()

Returns connection state.

getConnectionState()

Returns detailed state: 'disconnected', 'connecting', 'connected', 'reconnecting'

getSubscriptions()

Returns Set of active subscriptions.

getConfig()

Returns current configuration.

Event Callbacks

client.onConnectionStatusChange = (isConnected) => { }
client.onOffline = () => { }
client.onOnline = () => { }
client.onReconnecting = (attempt) => { }
client.onAuthError = (error) => {
  // Called on authentication failures
  // By default, reconnect attempts are stopped on auth errors
  // Use reconnectOnAuthError: true to override
}

Platform Presets

Mobile

Optimized for battery and intermittent connectivity.

new CloudSignal({ preset: 'mobile' })
// keepalive: 30s, offlineQueue: enabled, reconnectPeriod: 3s

Desktop

Balanced for desktop applications.

new CloudSignal({ preset: 'desktop' })
// keepalive: 45s, reconnectPeriod: 5s

Agent

Optimized for AI agents and bots.

new CloudSignal({ preset: 'agent' })
// keepalive: 60s, enableRequestResponse: true

Server

Optimized for server-side usage.

new CloudSignal({ preset: 'server' })
// keepalive: 120s, cleanSession: true

Node.js Usage

For Node.js with native MQTT (mqtts://):

const { CloudSignal } = require('@cloudsignal/cloudsignal-ws-client')

const client = new CloudSignal({
  transport: 'mqtt',  // Use native MQTT instead of WebSocket
  preset: 'server'
})

await client.connect({
  host: 'mqtts://connect.cloudsignal.app:8883/',
  username: 'user@org',
  password: 'token'
})

Development

npm install
npm run build:watch  # Watch mode
npm run build        # Production build

Build Output

  • cdn/CloudSignalWS.js - Browser bundle (latest)
  • cdn/CloudSignalWS.v2.0.0.js - Versioned browser bundle
  • dist/CloudSignal.node.js - Node.js bundle

Examples

See the examples/ directory for complete integrations:

Troubleshooting

See TROUBLESHOOTING.md for solutions to common issues:

  • Authentication errors and token expiry
  • React StrictMode double-connection issues
  • Infinite reconnect loops
  • WebSocket connection problems

Migration from v1.x

See MIGRATION.md for upgrade guide.

Breaking changes:

  • Constructor signature changed from boolean to options object
  • transmit() third parameter is now options object
  • Mobile optimizations require explicit preset or autoDetectPlatform: true

License

MIT