Skip to content

The SDK is one file, jsflow.js (with worker.js next to it), and its types are in jsflow.d.ts. Everything below is exported from it. The API is stable from 1.0: after that it only grows.

const { join, text } = await import(
'https://cdn.jsflow.com/v1.1.3/jsflow.js'
);
const room = await join({ app: 'pk_…', room: 'lobby' });
room.on('peer', (id, up) => console.log(id, up ? 'joined' : 'left'));
room.on('message', (from, data) => console.log(from, text(data)));
room.broadcast('hello');

See the quick start and the concepts for the ideas behind these calls.

Join a room. Rejects with a JoinError if the service (or the SDK itself) refuses.

Since 1.0.0.

export function join(opts: JoinOptions): Promise<Room>

Example

const room = await join({
app: 'pk_…',
room: 'round-42',
ticket: () =>
fetch('/ticket', { method: 'POST' }).then((r) => r.text()),
});

Decode a message’s bytes as UTF-8 text.

Since 1.0.0.

export function text(data: Uint8Array): string

Example

room.on('message', (from, data) => chat.append(text(data)));

A joined room: the peers this page can reach, and how to talk to them.

Since 1.0.0.

interface Room { … } // members below
property description
readonly id: PeerId My peer id. A page reload or a new join() gets a new one.
readonly room: string The room name given to join().
readonly state: State Where this peer is now; changes are reported by the ‘state’ event.

Subscribe with room.on(event, handler); remove with room.off.

event handler when
peer (id: PeerId, up: boolean) => void A peer became reachable (up true) or unreachable (up false). peers() lists the reachable ones.
path (peer: PeerId, path: 'direct' | 'relay' | 'mesh' | null) => void How I reach peer changed (see path()): for example ‘relay’ to ‘direct’ once ICE settles, ‘mesh’ to ‘direct’ when a link of my own comes up, null when it is no longer reachable. Listening starts the check, and fires once for each peer reachable then.
message (from: PeerId, data: Uint8Array, info: MessageInfo) => void A message from from: its bytes (text() decodes UTF-8) and how it was sent.
state (s: State) => void This peer’s state changed (the new value is also in room.state).
undelivered (peer: PeerId, n: number, why: string) => void Reliable messages to peer that may not have arrived: it stayed unreachable for 30 s, or restarted.
error (e: Error) => void The SDK’s worker could not set up the room after join() resolved: e is an Error whose message says what failed (nothing more is promised). The room will not connect: call leave(), then join() again.
evicted (info: { until: number }) => void The app’s backend removed this peer; every other peer has cut it off. Joining again is refused (code ‘blocked’) until until (unix s).
suspended (info: { reason: 'quota' }) => void The account’s spend cap is reached (the service said so in a signed notice at this peer’s refresh). Links stay up, but new joins to the account’s apps are refused (402 ‘quota’) until an owner raises the cap or the next period starts; the state returns to ‘connected’ after a refresh without the notice.
method description
peers(): PeerId[] The peers I can reach now.
user(peerId: PeerId): string | null A peer’s user id from its join ticket, vouched for by the service; ” if it joined without one; null if not known yet.
path(peer: PeerId): 'direct' | 'relay' | 'mesh' | null How I reach a peer now: ‘direct’ over my own link to it, peer to peer; ‘relay’ over my own link through a TURN relay (either end relayed); ‘mesh’ through other peers (no link of my own to it, said once that has held for a second, so a peer leaving does not flash ‘mesh’); null if it is not reachable. From the link’s selected candidate pair, read only once path() or a ‘path’ listener asks: at once, about 1 s and 5 s after a link comes up, then every 10 s. Changes are reported by the ‘path’ event.
off(ev: string, f: (...a: any[]) => void): this Remove a listener added with on(): the same event name and the same function.
send(to: PeerId, data: Data, o?: { channel?: Channel }): void A datagram to one peer: fast, may be lost, ≤ MAX_DATAGRAM bytes. If a link already holds 256 KB of unsent datagrams (a burst far above a normal rate), new ones on it are dropped rather than sent late, counted as the metric ‘dgDropped’. sendReliable() is never dropped.
broadcast(data: Data, o?: { channel?: Channel }): void A datagram to every peer in the room: may be lost, ≤ MAX_DATAGRAM bytes; dropped on a link that already holds 256 KB of unsent datagrams, as send().
sendReliable(to: PeerId, data: Data, o?: { channel?: Channel }): Promise<boolean> In order per peer, retransmitted until acknowledged, ≤ MAX_RELIABLE bytes. Resolves true when queued, false if that peer’s queue (1 MiB) is full.
ping(to: PeerId): Promise<{ rtt: number; hops: number; clock: number } | null> Round trip to a peer through the mesh (a sealed echo): its RTT in ms, the hops it took, and the peer’s wall clock in ms; null if no answer in 5 s.
leave(): void Leave the room: neighbours route around me at once.

Example

const room = await join({ app: 'pk_…', room: 'lobby' });
room.on('message', (from, data) => console.log(from, text(data)));
room.broadcast('hello');

What join() needs.

Since 1.0.0.

interface JoinOptions { … } // members below
property description
app: string The app’s publishable key (“pk_…”), from the dashboard. The page’s origin must be one the app allows.
room: string Room name, [A-Za-z0-9_-], 1–64 characters. Rooms are the app’s own.
server?: string Base URL of the signalling service (default SERVER). Given, it wins over region and a ticket’s region.
region?: Region The region an app is pinned to: the first request goes straight to that region’s signalling, so it never reaches another region (for a region-pinned app, set in the dashboard). A join ticket’s region claim does the same and wins if the two differ. Not needed without a pin: the service picks a nearby region.
iceServers?: RTCIceServer[] Overrides the ICE servers (STUN/TURN) the service hands out.
iceTransportPolicy?: RTCIceTransportPolicy Passed to every RTCPeerConnection. ‘relay’: all traffic goes through the relay (TURN), so peers never see each other’s IP addresses, at the cost of a little latency and relay bandwidth. Default ‘all’ (direct when possible).
onMetric?: (name: string, value: number, detail?: Readonly<Record<string, unknown>>) => void Diagnostic measurements for your own telemetry: value a number (1 for an event), detail its data. Metric names are diagnostic and may change in any minor release.
bye?: boolean Send BYE when the page is hidden (default: phones and desktop Safari, whose pages freeze).
worker?: string The URL of the SDK’s worker script, for a self-hosted copy of the SDK (default: worker.js next to this module).
ticket?: string | (() => Promise<string> | string) A join ticket from your backend (an HS256 JWT signed with the app’s secret key): a string, or a function the SDK calls for a fresh one at every join. Required when the app requires tickets; its user id becomes room.user(peerId) for everyone.

Example

const opts: JoinOptions = {
app: 'pk_…',
room: 'round-42',
ticket: () =>
fetch('/ticket', { method: 'POST' }).then((r) => r.text()),
};

Data in: bytes, or a string sent as UTF-8. Data out is always a Uint8Array.

Since 1.0.0.

export type Data = Uint8Array | ArrayBuffer | string

Example

const d: Data = JSON.stringify({ x: 1, y: 2 });

A peer’s id in the room: an integer the service assigns at each join.

Since 1.0.0.

export type PeerId = number

Example

room.on('peer', (id: PeerId, up) => {
console.log(id, up ? 'joined' : 'left');
});

Channels 0–13 are the app’s (default 0); a message arrives with its channel.

Since 1.0.0.

export type Channel = number

Example

room.broadcast(stroke, { channel: 1 });

Where this peer is. ‘away’: its page is hidden (phones, desktop Safari) and it holds no slot; ‘superseded’: a newer tab with the same id took over; ‘evicted’: the app’s backend removed it; ‘suspended’: the account’s spend cap is reached (links kept, joins refused); ‘left’: leave() was called.

Since 1.0.0.

type State = … // 7 values, listed below
value meaning
joining join() is connecting: the service admitted this peer, its first links are forming.
connected In the room: linked to the mesh and reachable by the other peers.
away The page is hidden (phones, desktop Safari): this peer said goodbye, holds no slot and accrues no time; it rejoins when the page is visible again.
superseded A newer tab or page with the same id took over; this one has stopped for good.
evicted The app’s backend removed this peer (see the ‘evicted’ event); it has stopped for good.
suspended The account’s spend cap is reached: links stay up, but new joins to the account’s apps are refused (‘quota’) until an owner raises the cap or the next period starts (see the ‘suspended’ event).
left leave() was called.

Example

room.on('state', (s: State) => {
if (s === 'suspended') showBanner('Paused: the app is over its plan');
});

How a message was sent.

Since 1.0.0.

interface MessageInfo { … } // members below
property description
channel: Channel The channel it was sent on (0–13; 0 unless the sender chose another).
broadcast: boolean true: sent with broadcast(); false: send() or sendReliable().
reliable: boolean true: sent with sendReliable() (in order, retransmitted).

Example

room.on('message', (from, data, info: MessageInfo) => {
if (info.reliable) apply(text(data));
});

A refused join. status is the HTTP status (0 when the SDK refuses itself: ‘unsupported_browser’, no Web Crypto X25519/Ed25519, Chrome/Edge 137+, Safari 17+, Firefox 130+; ‘worker_failed’, the SDK’s worker did not start twice). code is one of ErrorCode, e.g. ‘unknown_app’, ‘origin’, ‘room_full’, ‘rate’, ‘wire’ (the room runs another wire version), ‘sdk_unsupported’, ‘ticket_required’, ‘blocked’, ‘quota’. A network failure rejects with a TypeError instead.

Since 1.0.0.

class JoinError extends Error { … } // members below
property description
readonly name: 'JoinError' Always ‘JoinError’, so it survives a structured clone or a log line where instanceof does not.
readonly status: number The HTTP status; 0 for a refusal the SDK makes itself.
readonly code: ErrorCode Why: one of ErrorCode. Each code and what to do about it: https://jsflow.com/docs/reference/errors/
readonly body: { err: string; message?: string; [k: string]: unknown } | null The service’s answer: { err, message, …details }, or null if it was not JSON.
readonly docs: string This code’s entry on the errors page, what it means and what to do about it: https://jsflow.com/docs/reference/errors/#. Log it with the error, or link it from a developer-facing message.

Example

try {
await join(opts);
} catch (e) {
if (e instanceof JoinError && e.code === 'ticket_expired') {
return join({ ...opts, ticket: await fresh() });
}
throw e;
}

Every code a JoinError (or a service answer the SDK passes on) can carry, the same words as the account API’s. Each code and what to do about it: https://jsflow.com/docs/reference/errors/

Since 1.0.0.

type ErrorCode = … // 40 values, listed below

bad_blob, bad_id, bad_inc, bad_json, bad_kind, bad_path, bad_pool_token, bad_pub, bad_request, bad_room, bad_session_key, blocked, draining, internal, method_not_allowed, not_found, not_yours, origin, pool_full, quota, rate, room_full, sdk_unsupported, server_full, superseded, suspended, ticket_expired, ticket_invalid, ticket_required, too_large, too_many_rooms, too_many_streams, unauthorized, unknown, unknown_app, unsupported_browser, want_not_allowed, wire, worker_failed, wrong_home

Example

if (e instanceof JoinError && e.code === 'room_full') showFull();

Each code’s meaning is on the error codes page.

The signalling service join() uses unless given another.

Since 1.0.0.

export const SERVER: string

Example

// uses SERVER
const room = await join({ app: 'pk_…', room: 'lobby' });

This SDK’s version, sent in every join; the service may refuse an old one (JoinError code ‘sdk_unsupported’).

Since 1.0.0.

export const SDK_VERSION: string

Example

console.log(`jsflow ${SDK_VERSION}`);

The wire version this SDK speaks. A room runs one: a peer of the other gets JoinError code ‘wire’.

Since 1.0.0.

export const WIRE: 2

Example

// a room per wire version during an upgrade
const roomName = `game-${id}-w${WIRE}`;

Bytes of app data per send() / broadcast() (1099 in 0.1.x).

Since 1.0.0.

export const MAX_DATAGRAM: 1052

Example

if (bytes.length > MAX_DATAGRAM) await room.sendReliable(to, bytes);
else room.send(to, bytes);

Bytes per sendReliable() message.

Since 1.0.0.

export const MAX_RELIABLE: 65536

Example

if (file.byteLength > MAX_RELIABLE) throw new Error('send it in parts');