Trystero turns any static site into a live multiplayer app. Import the library, join a room by name, and browsers discover each other instantly.
No accounts, no API keys, no infra. Perfect for coding agents.
npm i trystero Rooms include verified user identities, synced per-user and shared state, host permissions, RPC, chunked file transfers, and live audio and video. Ship a multiplayer game or collaborative tool from GitHub Pages, Neocities, or a single HTML file.
The cursors moving across this page belong to other visitors connected through Trystero.
Open this in two browsers and move your pointer. You can also skip a
bundler and import directly from https://esm.run/trystero
in a module script.
import {joinRoom} from 'trystero'
const room = joinRoom({appId: 'pixel-party.example.com'}, 'studio-49')
const cursor = room.makeUserState('cursor', {x: 0, y: 0})
window.addEventListener('pointermove', e =>
cursor.set({x: e.clientX, y: e.clientY})
)
cursor.onChange((pos, {userId, self, removed}) => {
if (self) {
return
}
if (removed) {
removeCursor(userId)
} else {
drawCursor(userId, pos)
}
})Multiplayer apps usually track two kinds of state: per-user values each participant owns (names, cursors, ready flags) and shared room values for the group (a game board, round timer, or playback queue).
Writes apply locally right away, coalesce rapid updates on the wire, carry the author's signature, and sync to late joiners even after the original writer leaves.
Both primitives match React's useSyncExternalStore
contract directly.
// Per-user state: each user signs and updates their own slot
const profile = room.makeUserState('profile', {
name: 'Anon',
ready: false
})
profile.set({name: 'Oedipa', ready: true})
console.log(profile.getAll()) // {[userId]: {name, ready}}
// Shared room state, synced to late joiners
const track = room.makeState('track', {
url: 'beat.mp3',
paused: true
})
track.onChange((next, {userId}) => {
syncAudioPlayer(next)
console.log(`Updated by ${userId}`)
})
await track.set(prev => ({...prev, paused: false}))import {useSyncExternalStore} from 'react'
function Lobby() {
const players = useSyncExternalStore(
profile.onChange,
profile.getAll
)
const nowPlaying = useSyncExternalStore(
track.onChange,
track.get
)
}
Every participant gets a persistent userId derived
from an ECDSA keypair and verified during the WebRTC handshake,
with no login flow or auth server. Refreshing or opening another
tab keeps the same identity, and identity config
supports ephemeral per-tab keys or keys imported from your app.
Combine password and maxUsers for
private, seat-limited rooms such as a two-player match or four-seat
lobby.
const room = joinRoom(
{
appId: 'chess.example.com',
password: 'knight-takes-f7-secret',
maxUsers: 2
},
'table-7'
)
const {userId} = await room.getSelf()
room.onUserJoin(({userId}) => addPlayer(userId))
room.onUserLeave(({userId}) => removePlayer(userId))
room.onError(err => {
if (
err.code === 'room-full' &&
Object.keys(room.getPeers()).length === 0
) {
showBanner('Match already has two players.')
}
})Plain peer-to-peer rooms treat every participant equally, which breaks down when any client can open DevTools and overwrite game state.
The optional roles() plugin adds verified room admins,
custom roles like 'dj' or 'moderator',
role-gated state and actions, and peer bans. Peers verify every
write against the author's signature and role certificate, dropping
unauthorized edits on arrival.
import {joinRoom, roles} from 'trystero'
const room = joinRoom(
{appId: 'oedipa/friday-trivia', use: [roles({selfAsAdmin: true})]},
'quiz-night'
)
// Invite guests with roomId ("quiz-night~<adminUserId>")
const {roomId} = await room.getSelf()
// With roles() loaded, makeState defaults to admin-only writes
const game = room.makeState('game', {
round: 1,
prompt: 'Ready?'
})
await game.set({round: 2, prompt: 'Moons of Mars?'})
await room.grantRole(friendId, 'cohost')
await room.ban(spammerId, {reason: 'spoiling answers'})
Create named channels with room.makeAction() for
ephemeral events, request/response calls, and binary transfers.
Send strings, JSON, Blobs, Files, or
typed arrays; Trystero handles framing, chunking, backpressure,
metadata, and transfer progress.
Large files use the same channel API as small messages and stream directly between peers without intermediate storage.
Actions, RPC & file transfers →const drop = room.makeAction('file-drop')
drop.onReceive(({byteLength}) => byteLength <= 100 * 1024 ** 2)
drop.onReceiveProgress((pct, {metadata}) =>
showDownloadBar(metadata.name, pct)
)
drop.onMessage((bytes, {metadata}) =>
saveFile(bytes, metadata.name)
)
await drop.send(file, {
metadata: {name: file.name},
onProgress: pct => showUploadBar(pct)
})
// Request/response RPC
const roll = room.makeAction('roll', {kind: 'request'})
roll.onRequest(() => Math.ceil(Math.random() * 20))
const d20 = await roll.request(null, {
target: friendId,
timeoutMs: 2000
})
Send microphone audio, webcam video, screen captures,
canvas.captureStream(), or Web Audio output to the
room or to specific users. Tag streams with metadata
to distinguish camera feeds from screen shares, and swap tracks
mid-call with replaceTrack.
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: true
})
await room.addStream(stream, {metadata: {type: 'webcam'}})
room.onUserJoin(({userId}) =>
room.addStream(stream, {
target: userId,
metadata: {type: 'webcam'}
})
)
room.onPeerStream((remoteStream, {userId, metadata}) =>
attachVideo(userId, remoteStream, metadata.type)
)
Standard WebRTC rooms connect every browser directly to every
other, which suits small groups and low-latency matches. For larger
cooperative sessions, add the experimental scale()
plugin.
Small rooms stay in a direct mesh. Past
maxDirectPeers + 1 peers, browsers form a multi-hop
gossip overlay for messages and state while promoting media streams
and large binary transfers to direct links on demand.
import {joinRoom, scale} from 'trystero'
const room = joinRoom(
{appId: 'canvas.example.com', use: [scale()]},
'plaza'
)
const pixel = room.makeAction('pixel')
pixel.onMessage(({x, y, color}) => paint(x, y, color))
Trystero also runs in server and CLI runtimes with a WebRTC
polyfill. Run a game bot, bridge local hardware, or keep a
passive: true peer online to cache signed room state
while browser tabs are closed.
import {joinRoom} from 'trystero'
import {RTCPeerConnection} from 'werift'
const room = joinRoom(
{
appId: 'oedipa/synth-jam',
rtcPolyfill: RTCPeerConnection,
passive: true
},
'room-1'
)
room.makeState('pattern', {bpm: 120, steps: []})Identity, state, and signaling encryption rely on Web Crypto primitives verified directly by peers.
Handshakes are encrypted with AES-256-GCM before reaching any
relay. Default rooms derive the key from appId and
roomId; setting password derives it via
PBKDF2-SHA256 so outsiders cannot decrypt offers or join.
Every userId and peerId derives from an
ECDSA P-256 public key bound to the WebRTC DTLS certificate
fingerprint (RFC 8827), preventing peer spoofing and relay
man-in-the-middle attacks.
State updates and role certificates carry ECDSA signatures and Hybrid Logical Clock timestamps, so any peer or late joiner can verify authorship and ordering independently.
Architecture notes and walkthroughs for building peer-to-peer web apps.
Lobby, host authority, shared state, and RPC from a static page.
How public-relay signaling works, and where TURN still fits.
Deriving persistent user IDs from public keys and DTLS fingerprints.
What relays see, what WebRTC encrypts, and what passwords add.
Signed records, Hybrid Logical Clocks, and when to use a CRDT.
Growing a room past a full mesh with bounded connections per peer.