Guides

Connection & config

Every connect() option, transports, reconnects, connection state and errors.

Connect

import { connect } from "tauri-plugin-centrifugo-api";

await connect({
  url: "wss://example.com/connection/websocket",
  token: "<connection JWT>",                    // optional
  name: "my-app",                               // optional, client name
  version: "1.4.0",                             // optional, client version
  channels: ["news", "updates"],                // subscribed with default options
  useProtobuf: false,                           // JSON protocol
  readTimeout: 5000,                            // command timeout, ms
  httpStreamUrl: "https://example.com/connection/http_stream", // optional fallback
  headers: { "X-App": "demo" },                 // optional HTTP headers
  requestToken: false,                          // true: ask the frontend for the token
});

connect() closes the previous client if there is one, builds a new client, subscribes to channels and starts connecting. It resolves at once: the result arrives as connecting → connected events. It rejects only on a bad config (for example an invalid header name or value).

OptionMeaning
urlWebSocket endpoint, usually …/connection/websocket. wss:// for TLS.
tokenConnection JWT. Before it expires the SDK asks for a new one, see Tokens.
requestTokenNo token: ask the frontend with a need_token event instead.
name, versionSent to the server in the connect command.
channelsClient-side subscriptions with default options. For options use addSubscriptionWithOptions.
useProtobuftrue: Protobuf protocol; false: JSON. Payload handling in the plugin is the same.
readTimeoutTimeout of a command (publish, RPC, history, …) in ms. SDK default 5000.
httpStreamUrlHTTP-streaming endpoint, tried together with url on the first connect. Needs Centrifugo v5+ with http_stream enabled.
headersExtra HTTP headers for the WebSocket upgrade and HTTP-stream requests.

Full type: StartConfig.

Reconnects

The SDK keeps the connection alive by itself: it reconnects with backoff after a network error, watches server pings and notices a wake from sleep. Each attempt emits connecting (with the code and reason of the loss) and then connected. Subscriptions are resubscribed after a reconnect (subscribing → subscribed), and recoverable ones get the missed publications.

disconnected comes after disconnect() or when the server closes the connection with a code that forbids reconnecting (for example an invalid token). From that state the SDK does not reconnect; call connect() again.

State

import { isConnected, getConnectionState, helpers } from "tauri-plugin-centrifugo-api";

await isConnected();             // true only in the connected state
await getConnectionState();      // 'connecting' | 'connected' | 'disconnected' | 'closed'
await helpers.waitForConnection(10_000); // polls isConnected() every 100 ms; false on timeout

getConnectionState() returns 'disconnected' also when there is no client (before connect() or after disconnect()).

Disconnect

await disconnect();

Closes the connection and drops the client with all its subscriptions. Calls that need a client (publish, RPC, addSubscription, …) then reject with NotConnected until the next connect().

Errors

Commands reject with the plugin's Error enum serialized by serde: a string for "NotConnected", an object for the others:

try {
  await publish({ channel: "news", data: utils.encodeJson({ a: 1 }) });
} catch (e) {
  // "NotConnected"
  // { CentrifugoError: "..." }  error reply from the server (permission denied, unknown channel, ...)
  // { RequestError: "..." }     timeout, transport or SDK error, invalid header, no pending token request
  // { Base64Error: "..." }      `data` is not valid base64
  // { SerializationError: "..." } `rawJson` data is not valid JSON
  // { Unsupported: "..." }      map publish, track/untrack (see Deprecations)
  console.error(e);
}

Background errors (a failed reconnect, a subscription error) come as the error event instead, see Events.