From ee36e46e07186e6a3ebd741fb6d8aed895bc3416 Mon Sep 17 00:00:00 2001 From: Shivay-98 Date: Tue, 30 Jun 2026 13:46:18 +0530 Subject: [PATCH] fix(realtime): prevent INVALID_STATE_ERROR crash in heartbeat Use clearInterval instead of clearTimeout when resetting the heartbeat timer, and guard socket.send() with a readyState check so pings are only sent on an open WebSocket. Fixes #101 Co-authored-by: Cursor --- src/client.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/client.ts b/src/client.ts index fb954ab8..06181928 100644 --- a/src/client.ts +++ b/src/client.ts @@ -420,14 +420,17 @@ class Client { } }, createHeartbeat: () => { - if (this.realtime.heartbeat) { - clearTimeout(this.realtime.heartbeat); + if (this.realtime.heartbeat !== undefined) { + clearInterval(this.realtime.heartbeat); + this.realtime.heartbeat = undefined; } this.realtime.heartbeat = window?.setInterval(() => { - this.realtime.socket?.send(JSONbig.stringify({ - type: 'ping' - })); + if (this.realtime.socket?.readyState === WebSocket.OPEN) { + this.realtime.socket.send(JSONbig.stringify({ + type: 'ping' + })); + } }, 20_000); }, createSocket: () => {