{"id":49722,"library":"websocket-heartbeat-miniprogram","title":"WebSocket Heartbeat for MiniProgram","description":"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.","status":"active","version":"1.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/zimv/websocket-heartbeat-miniprogram","tags":["javascript","zimv","websocket","heartbeat","miniprogram"],"install":[{"cmd":"npm install websocket-heartbeat-miniprogram","lang":"bash","label":"npm"},{"cmd":"yarn add websocket-heartbeat-miniprogram","lang":"bash","label":"yarn"},{"cmd":"pnpm add websocket-heartbeat-miniprogram","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package is ESM-only; CommonJS require will fail. Use default import.","wrong":"const WebsocketHeartbeat = require('websocket-heartbeat-miniprogram')","symbol":"WebsocketHeartbeat","correct":"import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram'"},{"note":"Type definitions are not included in the package; the library does not ship TypeScript types. Use `any` or declare your own types.","wrong":null,"symbol":"WebsocketHeartbeat (type import)","correct":"import type { Task, Options } from 'websocket-heartbeat-miniprogram'"},{"note":"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.","wrong":"new WebsocketHeartbeat(...) or WebsocketHeartbeat.initialize(...)","symbol":"WebsocketHeartbeat (no options object)","correct":"WebsocketHeartbeat({ miniprogram: wx, connectSocketParams: { url: 'ws://...' } })"},{"note":"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.","wrong":"task.socketTask.onMessage(...) // listeners lost on reconnect","symbol":"onMessage, onOpen, etc.","correct":"task.onMessage = (data) => { /* stable */ }"}],"quickstart":{"code":"import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram';\nimport { getApp } from 'path/to/app'; // or use global wx\n\nconst wsUrl = process.env.WS_URL ?? 'wss://example.com/socket';\n\nWebsocketHeartbeat({\n  miniprogram: wx, // or tt, swan, my, uni, etc.\n  connectSocketParams: {\n    url: wsUrl,\n    header: { 'X-App-Version': '1.0.0' },\n    protocols: []\n  }\n}).then(task => {\n  console.log('WebSocket task created, ready to set hooks');\n\n  // Stable hooks (survive reconnects)\n  task.onOpen = (event) => {\n    console.log('WebSocket opened', event);\n    // send authentication message, etc.\n  };\n\n  task.onClose = (event) => {\n    console.log('WebSocket closed, will auto-reconnect if not manual close');\n  };\n\n  task.onMessage = (data) => {\n    console.log('Message received:', data);\n    // handle incoming data\n  };\n\n  task.onError = (error) => {\n    console.error('WebSocket error:', error);\n  };\n\n  task.onReconnect = () => {\n    console.log('Attempting reconnect...');\n  };\n\n  // Optional: use raw socketTask (listeners lost on reconnect)\n  task.socketTask.onOpen(event => console.log('raw open'));\n  task.socketTask.onMessage(frame => console.log('raw frame'));\n\n  // To manually close (prevents auto-reconnect)\n  // task.close();\n}).catch(err => {\n  console.error('Failed to create WebSocket task', err);\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Use import syntax (import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram') or transpile with Babel/esbuild. Do NOT use require().","message":"The library is ESM-only; CommonJS require throws an error.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always call `task.close()` on the old task before starting a new one. The library does not handle this automatically for Alipay.","message":"Alipay 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Server should send a close message instead. Frontend checks that message and calls `task.close()` to stop reconnection.","message":"Do 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).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use task.onOpen, task.onMessage, etc. instead of socketTask.onOpen, etc., to keep listeners across reconnects.","message":"The raw socketTask listeners (task.socketTask.onXxx) are lost on every reconnect because a new socketTask is created. Use task hooks for persistent listeners.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'across':76 'ago':124 'alipay':24,65 'api':38 'app':28 'appear':117 'automat':40 'baidu':25 'cadenc':116 'compat':22 'connect':51 'custom':73 'depend':129 'design':16 'detect':42 'differenti':57 'e.g':64 'ensur':46 'environ':55,138 'esm':91 'esm-on':90 'event':74 'focus':132 'handl':59 'heartbeat':2,7,14,41,142 'hook':75,103 'javascript':139 'key':56 'last':119 'librari':15,88 'lightweight':12 'limit':70 'listen':84 'live':50 'logic':45 'long':49 'long-liv':48 'lose':83 'low':118 'mini':19,34,136 'mini-program':33,135 'minim':128 'miniprogram':4,8,143 'nativ':80 'network':54 'object':100 'onclos':105 'onerror':107 'onmessag':106 'onopen':104 'onreconnect':108 'packag':126 'platform':23,61 'platform-specif':60 'preserv':72 'program':20,35,137 'promis':95 'provid':97 'quirk':63 'raw':113 'reconnect':44,77,86 'releas':115,120 'return':93 'singl':68 'single-socket':67 'socket':69 'sockettask':81,114 'sole':133 'specif':62 'stabl':47,102 'taro':29 'task':99 'uni':27 'uni-app':26 'unlik':78 'unreli':53 'v1.0.3':9 'websocket':1,6,13,37,141 'websocket-heartbeat-miniprogram':5 'wechat':18 'well':110 'wrap':31 'zimv':140","created_at":"2026-06-07T17:03:16.725845+00:00","updated_at":"2026-06-07T17:03:16.725845+00:00","problems":[{"fix":"Change to import syntax: `import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram'`","cause":"Using CommonJS `require()` to import an ESM-only package.","error":"TypeError: WebsocketHeartbeat is not a function"},{"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.","cause":"Passing wrong `miniprogram` object (e.g., `null`, `undefined`, or a non-platform object).","error":"TypeError: Cannot read property 'connectSocket' of undefined"},{"fix":"Provide a valid WebSocket URL in `connectSocketParams.url`. Example: `{ url: 'wss://example.com/socket' }`","cause":"Missing or invalid `url` in `connectSocketParams`.","error":"Error: connectSocket fail: url is not valid"},{"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.","cause":"Either the server closes the connection (triggering onClose and reconnect) or multiple tasks are created on Alipay without closing previous ones.","error":"The WebSocket connection is closed. Reconnect loop continues forever."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":null,"cli_version":null,"type":"library","homepage":"https://github.com/zimv/websocket-heartbeat-miniprogram#readme","github":"https://github.com/zimv/websocket-heartbeat-miniprogram","docs":null,"changelog":null,"pypi":null,"npm":"websocket-heartbeat-miniprogram","openapi_spec":null,"status_page":null,"smithery":null,"categories":["messaging"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-07","next_check":"2026-09-05","install_tag":null}}