You don’t need a backend.

Connect your users directly via peer-to-peer

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.

Get started
npm i trystero

Everything a room needs

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.

Live cursors in a dozen lines

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.

Getting started →
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)
  }
})

Synced player and room state

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.

Shared & per-user state →
// 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
  )
}

Verified identity, passwords, and room caps

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.

Identity, presence & room access →
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.')
  }
})

Hosts, custom roles, and moderation

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.

Admins, roles & moderation →
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'})

Actions, RPC, and file transfer

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
})

Audio, video, and screen sharing

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.

Audio, video & screen sharing →
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)
)

Scale to dozens of peers

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.

Scaling large rooms →
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))

Node, Bun, and Deno

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.

Running in Node, Bun & Deno →
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: []})

Security model

Identity, state, and signaling encryption rely on Web Crypto primitives verified directly by peers.

Encrypted signaling

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.

Self-certifying identities

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.

Signed state and roles

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.

Guides

Architecture notes and walkthroughs for building peer-to-peer web apps.

Get started