();
client.connection.bind("message", (event) => {
if (event.channel !== "chat:room-1" || !isMutableMessageEvent(event)) return;
const info = getMutableMessageInfo(event)!;
const current = messages.get(info.messageSerial) ?? null;
if (current?.versionSerial && current.versionSerial === info.versionSerial) return;
const next = reduceMutableMessageEvent(current, event);
messages.set(info.messageSerial, next);
console.log(next.messageSerial, next.action, next.data);
});
```
The reducer tracks one logical message and throws if it receives a different `messageSerial`, so
keep one state per serial as shown.
`client.connection` emits every decoded frame before `message_id` deduplication runs. Compare
`versionSerial` before applying a frame, as above, so that a repeated append is not applied twice.
Configure a backend proxy for REST reads. The endpoint receives a JSON `POST` of the form
`{ channel, messageSerial?, params?, action }` and must sign the upstream Sockudo HTTP request with
the app secret:
```ts title="versions.ts"
const client = new Sockudo("app-key", {
wsHost: "127.0.0.1",
wsPort: 6001,
forceTLS: false,
protocolVersion: 2,
versionedMessages: {
endpoint: "/sockudo/versioned",
},
});
const channel = client.subscribe("chat:room-1");
const latest = await channel.getMessage("42");
const versions = await channel.getMessageVersions("42", {
limit: 20,
direction: "oldest_first",
});
```
The proxy must authenticate the caller and authorize access to the channel. A helper called
without `versionedMessages.endpoint` throws.
### Annotations
Annotations attach reactions, labels, or counters to a message serial. The same proxy powers
`channel.publishAnnotation(messageSerial, { type, name, data, ... })`,
`channel.deleteAnnotation(messageSerial, annotationSerial)`, and
`channel.listAnnotations(messageSerial, { type, limit })`.
By default a subscriber receives only `message.summary` projections. Subscribe with
`annotationSubscribe: true` to also receive raw `annotation.create` and `annotation.delete`
events:
```ts title="annotations.ts"
const chat = client.subscribe("chat:room-1", { annotationSubscribe: true });
chat.bind("annotation.create", (annotation) => console.log(annotation.type, annotation.name));
chat.bind("message.summary", (summary) => console.log(summary));
```
## Framework integrations
### React
Create the client once, outside render functions, and provide it to the tree. `useChannel`
subscribes on mount, unsubscribes on unmount, and returns a state snapshot (`subscribed`,
`subscriptionPending`, `members`, `lastEventName`, `lastEventData`, and more).
```tsx title="App.tsx"
const client = new Sockudo("app-key", {
wsHost: "127.0.0.1",
wsPort: 6001,
forceTLS: false,
});
function Orders() {
const { subscribed, lastEventName, lastEventData } = useChannel("orders", {
onEvent: (eventName, data) => console.log(eventName, data),
});
return {JSON.stringify({ subscribed, lastEventName, lastEventData }, null, 2)};
}
export function App() {
return (
);
}
```
React exports: `SockudoProvider`, `useSockudo`, `useSockudoEvent`, `useChannel`, and
`usePresenceChannel`. Hook options include `enabled`, `filter`, `delta`, `events`, `onEvent`,
`onSubscriptionSucceeded`, `onSubscriptionError`, `onMemberAdded`, and `onMemberRemoved`.
### Vue
The Vue composables return the same state as refs, plus a `stop()` function:
```ts title="main.ts"
const client = new Sockudo("app-key", {
wsHost: "127.0.0.1",
wsPort: 6001,
forceTLS: false,
});
const Orders = defineComponent({
setup() {
const { subscribed, lastEventData } = useChannel("orders", {
onEvent: (eventName, data) => console.log(eventName, data),
});
return () => h("pre", JSON.stringify({ subscribed: subscribed.value, last: lastEventData.value }));
},
});
createApp(Orders).use(createSockudoPlugin(client)).mount("#app");
```
Vue exports: `createSockudoPlugin`, `provideSockudo`, `useSockudo`, `useSockudoEvent`,
`useChannel`, and `usePresenceChannel`.
## Connection lifecycle and reconnection
`client.connection` reports one of these states:
| State | Meaning |
| --- | --- |
| `initialized` | The client was created and has not started connecting. |
| `connecting` | The first connection attempt is in progress. |
| `reconnecting` | A retry after an unexpected disconnect is in progress. |
| `connected` | The socket is open; `client.connection.socket_id` is set. |
| `unavailable` | No connection within `unavailableTimeout`, or the network is down. Retries continue. |
| `disconnected` | Closed by `disconnect()`, by a refusing close code, or after `maxReconnectAttempts`. |
| `failed` | The runtime cannot open any supported transport, or a token provider failed before connecting. |
Each state is emitted as its own event and as `state_change` with `{ previous, current }`. Before a
delayed retry the manager also emits `connecting_in` with the delay in seconds.
```ts title="lifecycle.ts"
client.connection.bind("state_change", ({ previous, current }) => {
console.log(`connection: ${previous} -> ${current}`);
});
client.connection.bind("connecting_in", (seconds) => {
console.log(`retrying in ${seconds}s`);
});
```
Unexpected disconnects emit `reconnecting` and use quadratic backoff (0s, 1s, 4s, 9s) capped at
120 seconds. Configure `maxReconnectAttempts` (default `6`, `null` for unlimited) and
`maxReconnectGapInSeconds`. `reconnectJitter` (0 to 1) randomizes that fraction of each backoff
delay. Protocol retry close codes, such as `4200` during a server shutdown, reconnect immediately
unless `retryJitterMs` is set, in which case each client waits a random 0 to `retryJitterMs`
milliseconds first. TLS-upgrade retries remain immediate.
```ts title="reconnect.ts"
const client = new Sockudo("app-key", {
wsHost: "realtime.example.com",
maxReconnectAttempts: 10,
maxReconnectGapInSeconds: 60,
reconnectJitter: 0.5,
retryJitterMs: 2000,
});
client.connection.bind("reconnecting", () => console.log("reconnecting"));
```
The attempt counter resets after a successful connection and on explicit `connect()` or
`disconnect()` calls. Close codes map to these actions:
| Close code | Action |
| --- | --- |
| `4000` | Reconnect immediately over TLS. |
| `4001` to `4099` | Refused: the client disconnects and does not retry. |
| `4100` to `4199` | Reconnect with backoff. |
| `4200` to `4299` | Reconnect immediately (subject to `retryJitterMs`). |
| `4300` and above | Refused: the client disconnects and does not retry. |
Without jitter, every client dropped by the same event retries on the same schedule. In large
deployments set `reconnectJitter` (for example `0.5`) and `retryJitterMs` (for example `2000`) so
a rolling restart does not land all clients on the remaining nodes at once.
Heartbeats are automatic. Protocol V2 prefers native WebSocket ping/pong frames; browser-like
runtimes that cannot send native pings may use lightweight `sockudo:ping` / `sockudo:pong`
fallback messages, which carry no `message_id`, `serial`, or `stream_id`.
## Error handling
Errors surface on three channels. Bind all of them in production:
```ts title="errors.ts"
// Transport and server errors: { type: "SockudoError" | "WebSocketError" | ..., data | error }
client.connection.bind("error", (error) => {
console.error("Sockudo connection error", error);
});
// Capability-token failures (TokenAuthError, TokenExpiredError, TokenRevokedError)
client.bind("error", (error) => {
if (error instanceof TokenRevokedError) signOut();
});
// Per-channel auth failures: { type: "AuthError", error, status }
channel.bind("sockudo:subscription_error", (error) => {
if (error.status === 401 || error.status === 403) showAccessDenied();
});
```
| Error | Where | Typical cause |
| --- | --- | --- |
| `SockudoError` | `client.connection` `error` | Server `sockudo:error` frame or a close code; `data.code` carries the code. |
| `WebSocketError` | `client.connection` `error` | Transport failure while connecting. |
| `MessageParseError` | `client.connection` `error` | A frame could not be decoded. |
| `AuthError` | channel `subscription_error` | The auth endpoint returned non-`200` or invalid JSON. |
| `TokenExpiredError`, `TokenRevokedError` | `client` `error` | Capability token expired without a provider (`40142`) or revoked (`40160`). |
| `BadEventName` | thrown by `trigger()` | Client event name does not start with `client-`. |
- Treat auth `401` and `403` as an application-permission problem, not a reconnect loop.
- On `sockudo:resume_failed`, clear derived state and fetch an authoritative snapshot before
applying new events.
- Make handlers idempotent and validate unknown payloads at the application boundary.
## Platform notes
### Browser and Node.js
- Reuse one client per browser tab, worker, or Node process.
- Create the client outside React render functions and Vue component setup.
- Use the runtime-specific entrypoint so bundlers do not pull in incompatible browser or Node
transports. The Node build requires Node.js 22 or newer.
- Unbind handlers, unsubscribe unused channels, and disconnect during application shutdown.
- Never expose the app secret, push credentials, or encryption master key in a browser or mobile
bundle.
### React Native and NativeScript
- React Native resolves through the root `react-native` field or the explicit
`@sockudo/client/react-native` subpath.
- Import `@sockudo/client/nativescript` to load the `@valor/nativescript-websockets` polyfill
before the SDK.
### Push proxy helpers
Browser push registration should flow through your backend. Keep app secrets and provider
credentials server-side.
```ts title="push-device.ts"
await fetch("/sockudo/push/devices", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
device_id: "browser-device-1",
platform: "webpush",
provider_token: pushSubscription,
}),
});
```
`SockudoPushRegistration` is available from the root package for authenticated application
proxies. It covers device registration, channel push subscriptions, publish, scheduling, and
status, and includes typed direct and broadcast Apple Live Activity recipients and payloads:
```ts title="live-activity.ts"
const push = new SockudoPushRegistration({
endpoint: "/sockudo/push",
headers: async () => ({ Authorization: `Bearer ${await sessionToken()}` }),
});
await push.publishLiveActivity({
publishId: "ride-184-update-42",
recipients: [{
type: "recipient",
recipient: {
transportType: "apnsLiveActivity",
activityToken: currentActivityToken,
},
}],
liveActivity: {
event: "update",
timestamp: 1725000042,
contentState: { status: "arriving", etaMinutes: 1 },
priority: "conservePower",
},
});
```
React Native and NativeScript must obtain rotating ActivityKit tokens through the application's
native iOS bridge because the attributes type belongs to the app's Widget Extension. Upload every
rotation immediately. Use `apnsLiveActivityBroadcast` only with a server-created channel and its
immutable storage policy. See [Apple Live Activities](/docs/server/apple-live-activities).
The proxy must authenticate the caller and authorize the exact activity or channel. Use a server
SDK for unrestricted administrative publishing; never expose the app secret, APNs provider key, or
a blanket `push-admin` capability to client code.
## Next steps
- [Protocol V2](/docs/clients/protocol-v2): Wire metadata, recovery contract, and client history.
- [Filters and delta compression](/docs/clients/filters-delta): Tag filters, compound predicates, and delta tuning.
- [Presence history](/docs/clients/presence-history): Current members, transition history, and snapshots.
- [Authentication](/docs/getting-started/authentication): Channel auth, user auth, and capability tokens end to end.
- [Node.js server SDK](/docs/server-sdks/node): Publish events and sign auth responses from your backend.
- [History and recovery](/docs/server/history-recovery): Server-side recovery tiers, rewind, and durable history.