Skip to content

websocket

Install the required plugin:

Terminal window
tynd add websocket
import { websocket } from "@tynd/plugin-websocket/client";

WebSocket client with bundled TLS (wss:// works out of the box).

const ws = await websocket.connect("wss://echo.websocket.events");

Returns a handle for sending / receiving / closing the connection.

interface WebSocketHandle {
id: number;
send(data: string | Uint8Array): Promise<void>;
ping(): Promise<void>;
close(code?: number, reason?: string): Promise<void>;
onOpen(handler: () => void): () => void;
onMessage(handler: (msg: WebSocketMessage) => void): () => void;
onClose(handler: (code: number) => void): () => void;
onError(handler: (message: string) => void): () => void;
}
interface WebSocketMessage {
kind: "text" | "binary";
data: string | Uint8Array;
}

All return unsubscribe().

ws.onOpen(() => ws.send("hello"));
ws.onMessage((msg) => {
if (msg.kind === "text") console.log(msg.data); // string
else console.log("binary:", msg.data.byteLength); // Uint8Array
});
ws.onClose((code) => console.log("closed:", code));
ws.onError((message) => console.error(message));

onClose passes the close code. The reason field isn’t exposed on the receive side (not all close frames carry one; the WebSocket client reports code but not reason).

await ws.send("text frame");
await ws.send(new Uint8Array([1, 2, 3])); // binary — auto base64-encoded on IPC
await ws.ping();
await ws.close(1000, "bye"); // code + optional reason sent to the peer

IDs of currently-open connections.

const ids = await websocket.list();
  • wss:// works out of the box (TLS).
  • connect rejects when the handshake doesn’t finish within 5 seconds. It follows up to 3 handshake redirects, each checked against the http policy.
  • Inbound and outbound messages are capped at 8 MiB.
  • Socket events go only to the webview that called connect. A socket opened from the backend reaches app-local webviews only.
  • Sockets belong to the webview that opened them: another webview’s id answers “not found”, list() returns your own sockets (plus backend-opened ones for an app-local webview), and they are closed when that webview reloads, navigates or closes. A remote iframe inside a local page cannot use the page’s sockets, and a connect that finishes after the page navigated or reloaded closes the socket and fails with “the document that requested it is gone”.
  • With a security policy, the URL is checked against its http rules; ws:// and wss:// are matched as http:// and https://, and rules written with ws/wss work. See security.
  • ping sends a WebSocket PING frame — auto-reply with PONG is automatic.
  • No built-in auto-reconnect — call websocket.connect again to re-establish.
  • For the spec WebSocket API, use the global WebSocket.
  • http — for simple request/response.