Actions, RPC & file transfers
While state primitives maintain current values,
room.makeAction() handles discrete messages, request/response
RPC with timeouts, and chunked binary transfers with metadata and progress
callbacks.
Sending and receiving messages
Create a named channel (1โ32 UTF-8 bytes) and call send().
Payload types round-trip intact: strings arrive as strings, JSON values
arrive parsed, and binary inputs (Blob, File,
ArrayBuffer, or typed arrays) arrive as a
Uint8Array.
import {joinRoom} from 'trystero'
const room = joinRoom({appId: 'cantina.example.com'}, 'table-4')
const drink = room.makeAction('drink')
// Broadcast to everyone currently in the room
await drink.send({name: 'mezcal', withIce: false})
// Or target a specific userId, peerId, or array of either
await drink.send({name: 'negroni', withIce: true}, {target: friendUserId})
const unsub = drink.onMessage((data, {userId, peerId, roles}) => {
console.log(`${userId} sent ${data.name}`, data.withIce ? 'iced' : 'neat')
}) target accepts a userId (delivered to all of
that user's open tabs), a peerId, or an array of either. All
listener methods return an unsubscribe function.
TypeScript generics
type Stroke = {points: [number, number][]; brushSize: number}
const stroke = room.makeAction<Stroke>('stroke')
// Request actions take both request and response payload types
const checkVersion = room.makeAction<{client: string}, {compatible: boolean}>(
'version',
{kind: 'request'}
)Type parameters provide compile-time checking only; validate untrusted payloads at runtime.
Request / response RPC
Pass {kind: 'request'} to create a channel where
callers await a reply from the target peer.
const rollCheck = room.makeAction('roll-check', {kind: 'request'})
// One active handler per request action; returns a value or Promise
rollCheck.onRequest(({stat}, {userId}) => {
console.log(`${userId} requested a ${stat} check`)
return Math.ceil(Math.random() * 20) + characterSheet[stat]
})
// Queries one user (routed to a single active tab)
const roll = await rollCheck.request(
{stat: 'stealth'},
{target: playerUserId, timeoutMs: 3000}
)-
Because each request expects a single response, only one
onRequesthandler may be registered per action at a time. Call its unsubscribe function before registering a replacement. -
Throwing an
ErrorinsideonRequestrejects the caller'srequest()promise witherr.kind === 'rejected'and preserves the error message.
Fan-out requests with requestMany
requestMany() queries multiple targets concurrently, invokes
onResult as each peer responds, and resolves with a result
array once every target settles. Each entry contains
{userId, peerId, status}, where status
is 'fulfilled' (with value),
'timeout', 'disconnected', or
'rejected' (with error).
const readyCheck = room.makeAction('ready-check', {kind: 'request'})
readyCheck.onRequest(() => isPlayerReady())
const results = await readyCheck.requestMany(null, {
targets: Object.keys(room.getUsers()),
timeoutMs: 5000,
onResult: res => {
if (res.status === 'fulfilled') markCheckmark(res.userId, res.value)
}
})
const readyUsers = results
.filter(r => r.status === 'fulfilled' && r.value === true)
.map(r => r.userId)File transfers, metadata, and progress
Payloads larger than 16 KiB are automatically chunked and paced over the
data channel. Attach JSON-serializable metadata so receivers
can inspect filenames, MIME types, or transfer IDs before the payload
finishes streaming.
const fileDrop = room.makeAction('file')
// Register onReceive before onMessage to inspect size and metadata first
fileDrop.onReceive(({byteLength, metadata, userId}) => {
console.log(`Incoming ${metadata.name} (${byteLength} B) from ${userId}`)
return byteLength <= 100 * 1024 ** 2
})
fileDrop.onReceiveProgress((progress, {userId, metadata}) => {
updateDownloadBar(userId, metadata.id, metadata.name, progress)
})
fileDrop.onMessage((bytes, {metadata}) => {
const url = URL.createObjectURL(new Blob([bytes], {type: metadata.type}))
triggerBrowserDownload(url, metadata.name)
})
await fileDrop.send(selectedFile, {
target: [friendA, friendB],
metadata: {
id: crypto.randomUUID(),
name: selectedFile.name,
type: selectedFile.type
},
onProgress: (progress, {userId}) => updateUploadBar(userId, progress)
})
Binary views larger than 16 KiB (ArrayBuffer or typed
arrays) stream directly from the source buffer without copying. Avoid
mutating that buffer until send() settles.
Approving or rejecting incoming transfers
Chunked transfers begin with an offer header containing
byteLength and metadata. The receiver's
onReceive hook approves or declines the transfer before data
chunks are sent, progress callbacks fire on both ends, and the completed
Uint8Array is passed to onMessage.
-
onReceivecan returntrue,false, or aPromise<boolean>(for example, after prompting the user). Returningfalserejects the sender'ssend()call witherr.kind === 'rejected'. Usecontext.signalto close any open prompt if the sender aborts or disconnects. -
Rooms enforce a default 256 MiB concurrent receive budget
(
maxReceiveBytes). Incoming transfers are reassembled in memory, and transfers exceeding the active budget wait in queue. AdjustmaxReceiveBytesinjoinRoom()if needed.
Cancellation and error handling
Pass an AbortSignal to send(),
request(), or requestMany() to cancel an
in-flight transfer or RPC call.
const controller = new AbortController()
cancelButton.onclick = () => controller.abort()
try {
await fileDrop.send(bigFile, {signal: controller.signal})
} catch (err) {
// err.kind: 'timeout' | 'disconnected' | 'aborted' | 'rejected'
if (err.kind !== 'aborted') showTransferError(err)
}- Broadcast
send(data)resolves once local transmission completes, or immediately when no remote peers are present. - Targeted
send(data, {target})validates targets up front and rejects if any target is not connected. -
ActionError.kindvalues:'timeout'(exceededtimeoutMsor transfer stalled),'disconnected'(target was offline or left mid-transfer),'aborted'(localAbortSignalaborted), or'rejected'(receiver'sonReceivereturnedfalseoronRequestthrew).
A resolved send() indicates the bytes left the local peer.
Use a kind: 'request' action when you need application-level
confirmation from the recipient.
Role-restricted actions
When using roles(), pass
roles: ['admin', 'moderator'] to
makeAction(namespace, {roles}) so only holders of
those roles can send or request on that channel. Verified sender roles are
provided on every handler context.
Framing and transport
- Binary framing. Inline frames carry a 36-byte header
(48 bytes for chunked transfer offers) encoding protocol version, frame
kind, payload type, action name, and metadata length. Payloads up to 16
KiB transmit in a single frame; larger payloads negotiate an offer and
stream chunks paced by
RTCDataChannel.bufferedAmount. - Early-message buffering. If a peer sends inline
messages before the local
onMessagelistener is registered, Trystero buffers up to 32 inline messages per peer for up to 10 seconds and flushes them in order to the first subscriber. - Direct promotion in scaled rooms. With
scale()enabled, inline messages up to 16 KiB route over the multi-hop overlay, while larger chunked transfers promote the target peer to a direct WebRTC connection.