API reference@evolu/commonWebSocket › WebSocket

Defined in: packages/common/src/WebSocket.ts:66

WebSocket with auto-reconnect.

The API mirrors native WebSocket but retries connections indefinitely by default. This design accounts for the fact that browser and React Native online/offline detection APIs are unreliable — they may report online status incorrectly, so the only reliable approach is to keep attempting reconnection.

Created via createWebSocket which returns a Task.

Disposing the WebSocket closes the connection.

How Binary Messages Work

The Server Chooses the Message Type:

  • Text (0x1) → Sent as UTF-8 encoded text (always received as a string in the browser).
  • Binary (0x2) → Sent as raw binary data (received as a Blob or ArrayBuffer, depending on binaryType).

The Client's binaryType Controls How Binary Data is Processed:

  • If the server sends a text frame (0x1), the browser always delivers event.data as a string, regardless of binaryType.
  • If the server sends a binary frame (0x2), the browser delivers event.data as:
    • A Blob (default: "blob")
    • An ArrayBuffer ("arraybuffer")

Example

const ws = await run(
  createWebSocket("wss://example.com", {
    onMessage: (data) => console.log("Received:", data),
    onOpen: () => console.log("Connected"),
    onClose: () => console.log("Disconnected"),
  }),
);
if (ws.ok) {
  ws.value.send("Hello");
  // Later: await ws.value[Symbol.asyncDispose]();
}

Extends

Methods

[asyncDispose]()

asyncDispose: PromiseLike<void>;

Defined in: node_modules/.bun/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.disposable.d.ts:40

Inherited from

AsyncDisposable.[asyncDispose]

Properties

getReadyState

readonly getReadyState: () => WebSocketReadyState;

Defined in: packages/common/src/WebSocket.ts:75

isOpen

readonly isOpen: () => boolean;

Defined in: packages/common/src/WebSocket.ts:78

Returns true if the WebSocket is open and ready to send data.

send

send: (
  data: string | Blob | ArrayBufferLike | ArrayBufferView<ArrayBufferLike>,
) => Result<void, WebSocketSendError>;

Defined in: packages/common/src/WebSocket.ts:71

Send data through the WebSocket connection. Returns Result with an error if the data couldn't be sent.