Registry / messaging / websocket-heartbeat-miniprogram

websocket-heartbeat-miniprogram

JSON →
library1.0.3jsnpmunverified

Websocket-heartbeat-miniprogram (v1.0.3) is a lightweight WebSocket heartbeat library designed for WeChat Mini Programs and compatible platforms (Alipay, Baidu, Uni-app, Taro). It wraps the mini-program's WebSocket API with automatic heartbeat detection and reconnection logic, ensuring stable long-lived connections in unreliable network environments. Key differentiator: it handles platform-specific quirks (e.g., Alipay's single-socket limit) and preserves custom event hooks across reconnections, unlike the native socketTask that loses listeners after reconnect. The library is ESM-only, returns a promise, and provides a task object with stable hooks (onOpen, onClose, onMessage, onError, onReconnect) as well as the raw socketTask. Release cadence appears low; last release was a while ago. The package has minimal dependencies and is focused solely on mini-program environments.

npm install websocket-heartbeat-miniprogram
INSTALL
IMPORT
SIG · WEBSOCKET-HEARTBEA
W
websocket-heartbeat-miniprogram
messagingjavascriptv1.0.3
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

WebsocketHeartbeat
import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram'
const WebsocketHeartbeat = require('websocket-heartbeat-miniprogram')
The package is ESM-only; CommonJS require will fail. Use default import.
WebsocketHeartbeat (type import)
import type { Task, Options } from 'websocket-heartbeat-miniprogram'
Type definitions are not included in the package; the library does not ship TypeScript types. Use `any` or declare your own types.
WebsocketHeartbeat (no options object)
WebsocketHeartbeat({ miniprogram: wx, connectSocketParams: { url: 'ws://...' } })
new WebsocketHeartbeat(...) or WebsocketHeartbeat.initialize(...)
The function is not a constructor; it is called directly as a function. Common mistake: using `new` or calling a method on the default export.
onMessage, onOpen, etc.
task.onMessage = (data) => { /* stable */ }
task.socketTask.onMessage(...) // listeners lost on reconnect
Use task hooks (onOpen, onClose, onError, onMessage, onReconnect) for persistent listeners. Use socketTask.onXxx only if you need temporary listeners that are reset after reconnect.

Shows full setup: import, call WebsocketHeartbeat with platform (wx) and connection params, then attach all stable hooks (onOpen, onClose, onMessage, onError, onReconnect) to the returned task object. Also demonstrates raw socketTask usage and error handling.

import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram'; import { getApp } from 'path/to/app'; // or use global wx const wsUrl = process.env.WS_URL ?? 'wss://example.com/socket'; WebsocketHeartbeat({ miniprogram: wx, // or tt, swan, my, uni, etc. connectSocketParams: { url: wsUrl, header: { 'X-App-Version': '1.0.0' }, protocols: [] } }).then(task => { console.log('WebSocket task created, ready to set hooks'); // Stable hooks (survive reconnects) task.onOpen = (event) => { console.log('WebSocket opened', event); // send authentication message, etc. }; task.onClose = (event) => { console.log('WebSocket closed, will auto-reconnect if not manual close'); }; task.onMessage = (data) => { console.log('Message received:', data); // handle incoming data }; task.onError = (error) => { console.error('WebSocket error:', error); }; task.onReconnect = () => { console.log('Attempting reconnect...'); }; // Optional: use raw socketTask (listeners lost on reconnect) task.socketTask.onOpen(event => console.log('raw open')); task.socketTask.onMessage(frame => console.log('raw frame')); // To manually close (prevents auto-reconnect) // task.close(); }).catch(err => { console.error('Failed to create WebSocket task', err); });
Debug
Known issues
breakingThe library is ESM-only; CommonJS require throws an error.
fix
Use import syntax (import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram') or transpile with Babel/esbuild. Do NOT use require().
affects: >=1.0.0
gotchaAlipay mini-program allows only one WebSocket connection at a time. Creating multiple tasks without closing previous ones will cause connection conflicts and infinite reconnect loops.
fix
Always call `task.close()` on the old task before starting a new one. The library does not handle this automatically for Alipay.
affects: >=1.0.0
gotchaDo NOT close the WebSocket from the server side. Server-initiated close will trigger onClose and cause the library to attempt reconnect (because it cannot distinguish manual close from unexpected disconnect).
fix
Server should send a close message instead. Frontend checks that message and calls `task.close()` to stop reconnection.
affects: >=1.0.0
gotchaThe raw socketTask listeners (task.socketTask.onXxx) are lost on every reconnect because a new socketTask is created. Use task hooks for persistent listeners.
fix
Use task.onOpen, task.onMessage, etc. instead of socketTask.onOpen, etc., to keep listeners across reconnects.
affects: >=1.0.0
gotchaThe library does not handle authentication or token refresh automatically. If the connection requires a token, you must update the token in a custom reconnect handler.
fix
Implement your own token refresh logic inside a custom function and call it before initiating a new connection, possibly overriding the default reconnect behavior.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: WebsocketHeartbeat is not a function
Using CommonJS `require()` to import an ESM-only package.
fix
Change to import syntax: `import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram'`
TypeError: Cannot read property 'connectSocket' of undefined
Passing wrong `miniprogram` object (e.g., `null`, `undefined`, or a non-platform object).
fix
Ensure you pass the correct mini-program API object: `wx` for WeChat, `tt` for ByteDance, `swan` for Baidu, `my` for Alipay, or `uni` for Uni-app.
Error: connectSocket fail: url is not valid
Missing or invalid `url` in `connectSocketParams`.
fix
Provide a valid WebSocket URL in `connectSocketParams.url`. Example: `{ url: 'wss://example.com/socket' }`
The WebSocket connection is closed. Reconnect loop continues forever.
Either the server closes the connection (triggering onClose and reconnect) or multiple tasks are created on Alipay without closing previous ones.
fix
For server close: have server send a close message, frontend checks and calls `task.close()`. For Alipay conflicts: ensure only one task exists at a time by calling `task.close()` on the old task before creating a new one.
Upgrade
Version history
1.0.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
18 hits · last 30 days
node
16
OpenAI (training)
1
Resources
websocket-heartbeat-miniprogram — npm install websocket-heartbeat-miniprogram · libregistry