Import
What it does
WebSocketHelper wraps the native WebSocket API with automatic reconnection, configurable backoff strategies, per-type schema validation, ping/pong heartbeat monitoring, and a typed event system. It handles the full lifecycle — connect, send, validate, reconnect, and graceful disconnect — so you can focus on message handling.
Constructor
WebSocketOptions
BackoffStrategy
Methods
connect()
Opens the WebSocket connection. Returns a Promise that resolves on open or rejects on immediate error.
close()
Closes the connection and permanently stops reconnection. Use this for intentional disconnects.
send(type, data)
Sends a JSON message with the shape { type, data, timestamp }.
on(type, handler)
Subscribes to messages of a given type. Returns an unsubscribe function.
onError(handler)
Subscribes to connection and handler errors. Returns an unsubscribe function.
onReconnect(handler)
Fires just before each reconnect delay begins. Receives the 1-based attempt number and the computed delay. Returns an unsubscribe function.
onMaxRetriesReached(handler)
Fires once when all maxReconnectAttempts are exhausted. No further reconnection will be attempted. Returns an unsubscribe function.
onValidationError(handler)
Fires when a message fails schema validation. The message is dropped — on() handlers are not called. Returns an unsubscribe function.
request(type, data, responseType?)
Sends a message and waits for the matching response type (${type}:response by default). Rejects after messageTimeout ms.
isConnected()
Returns true if the socket is in the OPEN state.
getState()
Returns the raw WebSocket.readyState value (0–3).
Examples
Basic connection with typed messages
Exponential backoff with reconnect events
Schema validation with Zod
Pong detection (forced close on silence)
Graceful shutdown
All on* subscription methods return an unsubscribe function. Store and call it when the component unmounts to avoid memory leaks.
When reconnect is true, the helper reconnects on unexpected closures. Call close() explicitly to stop reconnection and close the connection cleanly. Calling close() also clears any pending pong timeout timer.