Skip to content

API reference

Creates a new client. Every call returns an independent instance — there is no shared singleton.

import { defineClient } from "durablews";
const client = defineClient({ url: "wss://example.com/socket" });

Typing, three ways: pass a schema (types inferred + runtime validation), pass generics (defineClient<Incoming, Outgoing>(config)), or neither (messages are unknown).

OptionTypeDefault
urlstring | URLrequired
protocolsstring | string[]passed to the underlying WebSocket
codecCodecjsonCodecthe wire seam
reconnectfalse | ReconnectOptionsondurability tuning
queuefalse | QueueOptionson, maxSize: 256queueing
heartbeatHeartbeatOptionsoffheartbeat
schemaStandardSchemaV1typed messages
MemberSignatureNotes
stateConnectionStatelive getter: idle | connecting | open | closing | reconnecting | closed
connect()() => Promise<void>resolves on first open (incl. a successful retry); idempotent; rejects only on terminal failure — details
send(data)(data: TOut) => voidqueues while connecting/reconnecting; throws in idle/closing/closed
close(code?, reason?)never triggers reconnection
on(event, handler)returns unsubscribetyped per event (below)
use(middleware)returns the clientbare function = inbound; { inbound?, outbound? } = per direction — middleware
getState()() => ClientStatefrozen { state, lastError, retryAttempt, queueLength }; referentially stable between changes
subscribe(listener)returns unsubscribefires on any snapshot change
EventPayloadFires when
openthe socket opened (after the queue flushed)
messageTIna message was decoded and (if configured) validated
closeCloseEventthe socket closed, clean or not
errorEvent | Errortransport error, middleware throw, schema failure (SchemaValidationError), heartbeat timeout
statechange{ previous, current }the FSM transitioned
reconnecting{ attempt, delay }a retry was scheduled (once per attempt)
drop{ data: TOut, reason: "overflow" | "close" }a queued message will never be sent
ExportWhat it is
jsonCodecthe default codec (JSON with binary passthrough)
pingpongopt-in inbound middleware: auto-replies to "ping" with "pong", without emitting message
RECONNECT_DEFAULTS / QUEUE_DEFAULTSthe resolved default option values
HEARTBEAT_TIMEOUT_CODE4408 — the close code a heartbeat timeout uses (filter it in shouldReconnect)
SchemaValidationErrorthe error payload for invalid inbound messages; carries the schema’s issues

All public types are exported: WebSocketClient, WebSocketClientConfig, Codec, ConnectionState, ClientState, ClientEventMap, Middleware, MessageContext, OutboundMiddleware, OutboundContext, DirectionalMiddleware, ReconnectOptions, QueueOptions, HeartbeatOptions, DropEvent, ReconnectingEvent, StateChange, StandardSchemaV1.

SubpathExport
durablews/vueuseWebSocket composableVue guide — optional peer vue >= 3.2
durablews/reactuseWebSocket hookReact guide — optional peer react >= 18

Installing durablews without the frameworks never warns; framework code loads only via its subpath.