Docs Getting started

Getting started

Install Trystero, join a room by name, and connect browsers directly without deploying a backend, creating API keys, or setting up accounts.

Install

npm i trystero

You can also import directly from an ESM CDN in a static HTML file:

<script type="module">
  import {joinRoom} from 'https://esm.run/trystero'
</script>

TypeScript projects require TypeScript 5.0 or newer. Server and CLI usage requires Node 22 or newer (see Node, Bun & Deno).

Join a room

Choose a globally unique, stable appId for your application—such as a domain you control ('notes.example.com') or 'username/app-name' ('oedipa/notes')—so rooms do not collide on shared public relays. Peers must use the same appId, room name, and signaling strategy to discover one another.

import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'notes.example.com'}, 'project-49')

const {userId, peerId} = await room.getSelf()
console.log(`user ${userId} on tab ${peerId}`)

room.onUserJoin(({userId}) => console.log(userId, 'joined'))
room.onUserLeave(({userId}) => console.log(userId, 'left'))
room.onError(err => console.error(err.code, err.message))

joinRoom() returns synchronously and negotiates connections in the background. Each participant receives a persistent, verified userId, while each open tab gets a separate peerId. Use userId for most application logic: onUserJoin fires when a user's first tab connects and does not repeat if they open another tab.

Local testing: tabs in the same browser profile share a userId, so opening a second tab will not trigger onUserJoin. Use an incognito window or pass identity: 'none' to test multiple users on one machine.

Per-user state

Use makeUserState for values owned by individual participants such as display names, cursors, or ready flags. Each user can only modify their own slot. Initial values set right after joinRoom() are available on remote peers before onUserJoin fires, and a user's entry is evicted once their last tab leaves.

const profile = room.makeUserState('profile', {name: 'Anon', color: '#c8a87c'})
profile.set({name: 'Oedipa', color: '#e7abc5'})

renderRoster(profile.getAll())
profile.onChange(() => renderRoster(profile.getAll()))

Shared room state

Use makeState for values shared across the room such as a game board, round timer, or document metadata. Writes apply locally right away, coalesce bursts on the wire, and sync to late joiners even if the last writer has disconnected. Concurrent writes resolve last-writer-wins.

const doc = room.makeState('doc', {title: 'Untitled', body: ''})

doc.onChange(next => editor.render(next))
editor.onInput(body => doc.set(prev => ({...prev, body})))

Avoid storing a {[userId]: …} map inside makeState; concurrent updates from two users will overwrite one another. Use makeUserState and getAll() instead (see Shared & per-user state).

Actions

Create named channels with makeAction for transient events, RPC calls, and binary transfers. Strings, JSON values, Blobs, Files, and typed arrays are supported, with automatic chunking and backpressure for large payloads.

const ping = room.makeAction('ping')

ping.onMessage((data, {userId}) => {
  console.log(`${userId} sent`, data)
})

await ping.send({at: Date.now()})
await ping.send('direct note', {target: someUserId})

Pass {kind: 'request'} for request/response RPC, or attach metadata and onProgress callbacks when sending files. See Actions, RPC & file transfers.

Cleanup

Every on* listener returns an unsubscribe function and accepts {once, signal, replay} options. Call await room.leave() on teardown. Calling joinRoom() twice for the same (appId, roomId) without leaving first throws an error, surfacing accidental duplicate mounts early.

const unsubscribe = room.onUserJoin(({userId}) => greet(userId))

unsubscribe()
await room.leave()

Next steps

The default entrypoint discovers peers over public Nostr relays. You can switch signaling strategies by changing the import path, restrict access with a password or user cap, add a verified room admin, or configure TURN for restrictive networks.