Skip to main content

Chat Client Reference

This page contains a small, dependency-free JavaScript client for Sitata's real-time socket. It is adapted from the client used in Sitata's own Claims Widget. You can copy it into your project as-is, or use it as a reference when writing a client in another language.

It handles:

  • fetching a socket token and connecting;
  • heartbeats, plus automatic reconnects with back-off and a fresh token;
  • re-joining channels after a reconnect;
  • push replies and timeouts;
  • presence tracking, including who is typing.

If you'd rather use a library, the official phoenix npm package speaks the same protocol. See Messaging.

sitata-socket.js

// Minimal Phoenix Channels client for Sitata's real-time socket.
// Works in browsers and in any JS runtime with a global WebSocket.

const HEARTBEAT_INTERVAL_MS = 30_000;
const RECONNECT_AFTER_MS = [1_000, 2_000, 5_000, 10_000];
const PUSH_TIMEOUT_MS = 10_000;

export class SitataChannel {
constructor(topic, socket) {
this.topic = topic;
this.status = "joining"; // joining | joined | closed | error
this.presences = {};
this._socket = socket;
this._joinRef = null;
this._handlers = new Map();
}

/** Listen for an event. Returns an unsubscribe function. */
on(event, handler) {
if (!this._handlers.has(event)) this._handlers.set(event, new Set());
this._handlers.get(event).add(handler);
return () => this._handlers.get(event)?.delete(handler);
}

/** Push an event. Resolves with the server's reply; rejects on error or timeout. */
push(event, payload = {}) {
return this._socket._push(this.topic, event, payload);
}

leave() {
this._socket._leave(this);
}

// Internal: called by SitataSocket for every message on this topic.
_handle(event, payload, ref) {
if (event === "phx_reply" && ref === this._joinRef) {
this._setStatus(payload.status === "ok" ? "joined" : "error", payload.response);
return;
}
if (event === "phx_error") return this._setStatus("error");
if (event === "phx_close") return this._setStatus("closed");

if (event === "presence_state") {
this.presences = Presence.syncState(this.presences, payload);
return this._emit("presence", this.presences);
}
if (event === "presence_diff") {
this.presences = Presence.syncDiff(this.presences, payload);
return this._emit("presence", this.presences);
}
this._emit(event, payload);
}

_setStatus(status, response) {
this.status = status;
this._emit("status", status, response);
}

_emit(event, ...args) {
this._handlers.get(event)?.forEach((h) => h(...args));
}
}

export class SitataSocket {
/**
* @param {string} socketUrl e.g. "wss://sockets.sitata.com/socket/websocket"
* @param {Function} getToken async () => socket token, e.g. from POST /api/v2/tokens/for_socket
*/
constructor(socketUrl, getToken) {
this._url = socketUrl;
this._getToken = getToken;
this._ws = null;
this._ref = 0;
this._attempts = 0;
this._heartbeat = null;
this._reconnectTimer = null;
this._buffer = [];
this._pending = new Map();
this._channels = new Map();
this._closedByUser = false;
}

async connect() {
this._closedByUser = false;
const token = await this._getToken();
this._ws = new WebSocket(`${this._url}?token=${encodeURIComponent(token)}`);

this._ws.onopen = () => {
this._attempts = 0;
this._heartbeat = setInterval(
() => this._send({ topic: "phoenix", event: "heartbeat", payload: {}, ref: this._nextRef() }),
HEARTBEAT_INTERVAL_MS,
);
this._channels.forEach((channel) => this._join(channel));
this._buffer.splice(0).forEach((msg) => this._send(msg));
};

this._ws.onmessage = ({ data }) => {
const { topic, event, payload, ref } = JSON.parse(data);

if (event === "phx_reply" && this._pending.has(ref)) {
const { resolve, reject, timer } = this._pending.get(ref);
clearTimeout(timer);
this._pending.delete(ref);
payload.status === "ok" ? resolve(payload.response) : reject(payload.response);
}
this._channels.get(topic)?._handle(event, payload ?? {}, ref);
};

this._ws.onclose = () => {
clearInterval(this._heartbeat);
this._channels.forEach((channel) => channel._setStatus("closed"));
if (!this._closedByUser) this._scheduleReconnect();
};

// An error is always followed by a close event, which schedules the reconnect.
this._ws.onerror = () => {};
}

disconnect() {
this._closedByUser = true;
clearTimeout(this._reconnectTimer);
clearInterval(this._heartbeat);
this._ws?.close();
this._channels.clear();
}

/** Join a topic such as `conversation:<id>`. Idempotent per topic. */
channel(topic) {
if (this._channels.has(topic)) return this._channels.get(topic);
const channel = new SitataChannel(topic, this);
this._channels.set(topic, channel);
if (this._ws?.readyState === WebSocket.OPEN) this._join(channel);
return channel;
}

_join(channel) {
channel._joinRef = this._nextRef();
channel.presences = {};
channel._setStatus("joining");
this._send({
topic: channel.topic,
event: "phx_join",
payload: {},
ref: channel._joinRef,
join_ref: channel._joinRef,
});
}

_leave(channel) {
this._send({
topic: channel.topic,
event: "phx_leave",
payload: {},
ref: this._nextRef(),
join_ref: channel._joinRef,
});
this._channels.delete(channel.topic);
}

_push(topic, event, payload) {
const ref = this._nextRef();
const joinRef = this._channels.get(topic)?._joinRef ?? null;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this._pending.delete(ref);
reject({ reason: "timeout" });
}, PUSH_TIMEOUT_MS);
this._pending.set(ref, { resolve, reject, timer });
this._send({ topic, event, payload, ref, join_ref: joinRef });
});
}

_send(msg) {
if (this._ws?.readyState === WebSocket.OPEN) this._ws.send(JSON.stringify(msg));
else this._buffer.push(msg);
}

_scheduleReconnect() {
const delay = RECONNECT_AFTER_MS[Math.min(this._attempts++, RECONNECT_AFTER_MS.length - 1)];
// Reconnect with a fresh token: socket tokens expire after 7 days.
this._reconnectTimer = setTimeout(() => this.connect().catch(() => this._scheduleReconnect()), delay);
}

_nextRef() {
return String(++this._ref);
}
}

/** Mirrors the Phoenix Presence JS helpers. */
export const Presence = {
syncState(current, next) {
const joins = {};
const leaves = {};
for (const [key, entry] of Object.entries(current)) if (!next[key]) leaves[key] = entry;
for (const [key, entry] of Object.entries(next)) if (!current[key]) joins[key] = entry;
return Presence.syncDiff({ ...current }, { joins, leaves });
},

syncDiff(state, { joins, leaves }) {
const result = { ...state };
for (const [key, added] of Object.entries(joins)) {
result[key] = result[key] ? { metas: [...result[key].metas, ...added.metas] } : added;
}
for (const [key, removed] of Object.entries(leaves)) {
if (!result[key]) continue;
const metas = result[key].metas.filter((m) => !removed.metas.some((r) => r.phx_ref === m.phx_ref));
if (metas.length) result[key] = { metas };
else delete result[key];
}
return result;
},

/** User ids currently typing, excluding `selfId`. */
typing(presences, selfId) {
return Object.entries(presences)
.filter(([id, { metas }]) => id !== selfId && metas.some((m) => m.typing === true))
.map(([id]) => id);
},
};

Putting It Together

A complete traveller chat session, from creating the issue to sending messages:

import { SitataSocket, Presence } from "./sitata-socket.js";

const API_BASE = "https://www.sitata.com/api/v2";
const SOCKET_URL = "wss://sockets.sitata.com/socket/websocket";

// The traveller's token and your company id (see "Authentication").
const headers = {
Authorization: `TKN ${travellerToken}`,
Organization: COMPANY_ID,
"Content-Type": "application/json",
};

async function api(method, path, body) {
const res = await fetch(`${API_BASE}${path}`, { method, headers, body: body && JSON.stringify(body) });
if (!res.ok) throw new Error(`${method} ${path} failed: ${res.status}`);
return res.json();
}

// 1. Open an issue. Its conversation is created automatically.
const issue = await api("POST", "/issues", {
issue: { type: 10, description: "Lost my passport", lat: 41.3874, lng: 2.1686 },
});

// 2. Load the conversation, including full history.
const conversation = await api("GET", `/issues/${issue.id}/conversation`);
const messages = new Map(conversation.messages.map((m) => [m.client_id, m]));
render();

// 3. Connect and join.
const socket = new SitataSocket(SOCKET_URL, async () => (await api("POST", "/tokens/for_socket")).token);
await socket.connect();

const channel = socket.channel(`conversation:${issue.conversation_id}`);

channel.on("new:message", ({ message }) => {
messages.set(message.client_id, message);
render();
if (message.user_id !== me.id) {
channel.push("read:message", { client_id: message.client_id, user_id: me.id });
}
});

channel.on("read:message", ({ client_id }) => {
const m = messages.get(client_id);
if (m) m.status = 2;
render();
});

channel.on("presence", (presences) => showTyping(Presence.typing(presences, me.id)));

channel.on("status", async (status) => {
if (status === "joined") {
// After a reconnect, re-fetch the latest page to pick up anything missed while offline.
const latest = await api("GET", `/conversations/${issue.conversation_id}/messages?page_size=50`);
latest.forEach((m) => messages.set(m.client_id, m));
render();
channel.push("mark_read:conversation", {});
}
});

// 4. Send.
async function send(body) {
const message = { type: 0, status: 0, body, client_id: crypto.randomUUID(), user_id: me.id };
messages.set(message.client_id, message);
render();
try {
await channel.push("create:message", message);
} catch {
message.status = 3; // failed: offer a retry
render();
}
}

// 5. Typing indicator: true on the first keystroke, false after 3 s idle.
let typingTimer = null;
function onKeystroke() {
if (!typingTimer) channel.push("user:typing", { typing: true });
clearTimeout(typingTimer);
typingTimer = setTimeout(() => {
channel.push("user:typing", { typing: false });
typingTimer = null;
}, 3_000);
}

// 6. Clean up when the chat is closed or the traveller signs out.
function closeChat() {
channel.leave();
socket.disconnect();
}

Messages are keyed by client_id because the optimistic copy you insert when sending has no server id yet. The server's echo has the same client_id, so it replaces the optimistic copy instead of appearing twice.