Docs Shared & per-user state

Shared & per-user state

Actions send transient events, while state primitives keep current values synchronized across everyone in the room, including participants who join later. Trystero provides per-user state and shared room state directly on room.

Choosing between the two primitives

Primitive Typical data Write access Lifecycle
room.makeUserState(ns, init?, cfg?) Display names, avatars, cursors, ready flags, loadouts Only that userId, for their own slot Presence-scoped: retained while the user is online, evicted once their last tab leaves
room.makeState(ns, init?, cfg?) Game boards, timers, watch-party playback, step sequencers Any room member, or specific roles when roles() is loaded Room-scoped: cached and synced to newcomers by remaining peers after the writer leaves

Use makeUserState whenever each participant owns an entry. Storing a {[userId]: …} map in makeState causes concurrent updates from two users to clobber one another.

// Avoid: concurrent writes from two players overwrite one another
const players = room.makeState('players', {})
players.set(prev => ({...prev, [myId]: {ready: true}}))

// Prefer: each player writes their own slot, and getAll() returns the map
const player = room.makeUserState('player', {ready: false})
player.set({ready: true})
const everyone = player.getAll()

Per-user state: makeUserState

Each participant gets a signed JSON slot keyed by userId (initialValue defaults to null). Other peers cannot overwrite or clear your slot, even when relaying state to late joiners or forwarding across multiple hops.

import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'oedipa/dungeon-crawl'}, 'tavern-1')

const player = room.makeUserState('player', {
  name: 'Stranger',
  hp: 100,
  ready: false
})

// Set right after joining so remote peers see it in onUserJoin
player.set({name: 'Oedipa', hp: 100, ready: true})

room.onUserJoin(({userId}) => {
  console.log(`${player.get(userId).name} joined`)
})

// Still readable inside onUserLeave, then evicted right after
room.onUserLeave(({userId}) => {
  console.log(`${player.get(userId).name} left`)
})

player.onChange((value, {userId, prev, self, removed}) => {
  if (removed) console.log(`${prev.name} (${userId}) removed`)
  else console.log(`${userId}:`, value, self ? '(local)' : '')
})

// Frozen {[userId]: value} snapshot of published entries
console.log(player.getAll())

Methods

  • get(id?): reads a slot by userId or peerId, or the local user's slot with no argument. Returns initialValue if that user has not published or has left.
  • getAll(): returns a frozen, reference-stable {[userId]: value} map of active published entries, including the local user once set() has been called.
  • has(id?): returns whether that user currently has a published value, distinguishing set(null) from an unpublished slot when initialValue is null.
  • set(valueOrUpdater): accepts a JSON value or functional updater. Updates local get() and getAll() synchronously while coalescing rapid writes on the wire.
  • clear(): removes the local slot, resets has(), and broadcasts a signed tombstone so peers receive removed: true.
  • getMeta(id?): returns metadata for the latest record: {prev, peerId, userId, roles, timestamp, self, online, removed}.

Multi-tab behavior

Slots are keyed by userId rather than tab ID. Opening a second tab in the same browser does not overwrite state published from the first, updates sync across all of your open tabs, and your entry remains active until your last tab disconnects.

Shared room state: makeState

makeState synchronizes a single JSON value across the room and can be called synchronously right after joinRoom().

const playback = room.makeState('playback', {
  trackUrl: 'https://example.com/synthwave.mp3',
  positionSec: 0,
  paused: true
})

playback.onChange((next, {prev, userId}) => {
  console.log(`${userId} updated playback from`, prev, 'to', next)
  syncMediaElement(next)
})

await playback.set(prev => ({...prev, paused: false}))
console.log(playback.get(), playback.getMeta())

When a new participant joins later—even after the person who last wrote the state has left—remaining peers verify and sync the latest signed record to the newcomer.

To keep shared state alive when all browser tabs close, run a passive: true peer in Node, Bun, or Deno with the same makeState namespaces declared. It caches and serves signed records without requiring admin privileges.

React integration

Both state primitives match React's useSyncExternalStore interface: onChange returns an unsubscribe function, get and getAll return frozen reference-stable snapshots, and set() updates the local snapshot synchronously so controlled inputs stay responsive.

import {joinRoom} from 'trystero'
import {useSyncExternalStore} from 'react'

const room = joinRoom({appId: 'jam-board.example.com'}, 'studio-1')
const color = room.makeUserState('color', '#ff6b6b')
const title = room.makeState('title', 'Untitled Jam')

export default function Studio() {
  const myColor = useSyncExternalStore(color.onChange, () => color.get())
  const everyone = useSyncExternalStore(color.onChange, color.getAll)
  const boardTitle = useSyncExternalStore(title.onChange, title.get)

  return (
    <main>
      <input value={boardTitle} onChange={e => title.set(e.target.value)} />
      <input
        type="color"
        value={myColor}
        onChange={e => color.set(e.target.value)}
      />
      <ul>
        {Object.entries(everyone).map(([userId, hex]) => (
          <li key={userId} style={{color: hex}}>{userId}</li>
        ))}
      </ul>
    </main>
  )
}

In SSR frameworks (Next.js, Remix, Astro), guard module-scope joinRoom() calls with typeof window !== 'undefined' or initialize the room lazily on the client.

Validation and size limits

Both primitives accept an optional config third argument:

  • validate(next, context): synchronous predicate run on both local and incoming remote writes. Returning false rejects local set() calls and drops invalid remote records.
  • maxBytes: maximum UTF-8 JSON byte length per entry. Defaults to 16 KiB and can be raised up to 64 KiB.
  • roles: restricts which roles may write when roles() is loaded.
const score = room.makeUserState('score', 0, {
  maxBytes: 1024,
  validate: next =>
    typeof next === 'number' && Number.isInteger(next) && next >= 0
})

When multiple users can write to the same makeState namespace concurrently, validate the shape and invariants of next (along with context.roles and context.userId) rather than strict step-by-step transitions from context.prev, since concurrent writes settle last-writer-wins.

Open vs. role-gated state

Without roles(), any peer in the room can update makeState. Writes still carry verified userId signatures and converge via deterministic last-writer-wins, which suits cooperative tools and password-protected sessions among friends.

Loading roles() changes the default on makeState to roles: ['admin'] so shared game or room state is protected against console edits by default. You can grant write access to custom roles ({roles: ['admin', 'dj']}), reopen a specific namespace to everyone ({roles: '*'}), or restrict a makeUserState namespace to specific roles ({roles: ['admin', 'player']}).

For concurrent character-level text editing or fine-grained merges, send Yjs or Automerge updates over actions.

Replaying current state to new listeners

onChange normally fires only on subsequent updates. Pass {replay: true} to invoke the listener immediately with any existing written record upon subscribing. Listeners also accept {once: true} and an AbortSignal via signal.

// Calls the handler immediately if a written value is present, then on changes
const unsub = playback.onChange((value, meta) => renderPlayer(value, meta), {
  replay: true
})

Protocol details

  • Signed records. Every write or clear() tombstone is canonicalized and signed with the author's ECDSA P-256 key, covering appId, roomId, namespace, Hybrid Logical Clock timestamp, peerId, userId, the value, and any inline role certificate.
  • 40 ms write coalescing. set() updates local state and fires local onChange listeners synchronously, while coalescing signing and wire broadcasts over a 40 ms per-slot window.
  • Deterministic ordering. Concurrent records are ordered by ([wallMs, counter], userId, peerId, sig). Records with timestamps more than 10 seconds ahead of a receiver's local clock are dropped so a skewed or manipulated clock cannot pin future state.
  • Per-user quotas. Each userId can publish up to 32 makeUserState namespaces totaling at most 64 KiB.
  • Anti-entropy reconciliation. Peers reconcile state via cursor-paged digest comparison so newcomers and reconnected subgraphs converge across direct and multi-hop topologies. Calling room.ban(userId) purges all state authored by that user.