Guides State sync without a server

Syncing state between browsers without a server

Without a central database, every connected browser holds its own replica of room state and must converge on the same latest value—including participants who join long after the person who last updated the state has disconnected.

Requirements for peer-to-peer state

Consider a synced watch party where one viewer presses play at 9:00, closes their laptop at 9:10, and another friend joins at 9:20. Synchronizing that newcomer requires solving three problems: retaining state after its author leaves, ordering concurrent writes without a central clock, and verifying that a record forwarded by a third peer was not tampered with.

room.makeState handles shared room values:

import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'cinema.example.com'}, 'screening-7')

const playback = room.makeState('playback', {
  src: 'https://example.com/night-of-the-living-dead.mp4',
  paused: true,
  positionSec: 0,
  setAt: 0
})

playButton.onclick = () =>
  playback.set(prev => ({
    ...prev,
    paused: false,
    positionSec: video.currentTime,
    setAt: Date.now()
  }))

playback.onChange((next, {userId}) => {
  if (next.src && video.src !== next.src) video.src = next.src
  const elapsed = next.paused ? 0 : (Date.now() - next.setAt) / 1000
  video.currentTime = next.positionSec + elapsed
  next.paused ? video.pause() : video.play()
  showToast(userId + ' updated playback')
})

Storing setAt alongside positionSec records a durable reference point ("playback resumed from position X at timestamp T") rather than a rapidly expiring playhead value, letting late joiners calculate the live position from an older record.

Per-user vs. shared state

makeUserState makeState
Typical data Names, cursors, ready flags, player loadouts Game boards, round timers, media playback
Writers Only the owning userId Any peer, or 'admin' / configured roles when roles() is loaded
Retention Presence-scoped: evicted when the user's last tab leaves Room-scoped: cached and synced by remaining peers after the author leaves

Per-user state assigns each userId a signed slot shared across their open tabs and retained until their last tab disconnects:

import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'oedipa/late-night-poker'}, 'table-3')

const seat = room.makeUserState('seat', {
  name: 'Anon',
  color: '#ff6b6b',
  ready: false
})

seat.set({name: 'Oedipa', color: '#ff6b6b', ready: false})

readyBox.onchange = () => seat.set(prev => ({...prev, ready: readyBox.checked}))

seat.onChange((value, {userId, self, removed}) => {
  if (self) return
  if (removed) removeSeat(userId)
  else renderSeat(userId, value)
})

const everyoneReady = Object.values(seat.getAll()).every(s => s.ready)

Do not store a multi-writer {[userId]: …} map inside makeState. Because makeState replaces the entire value on each write, two users updating their entries simultaneously will overwrite one another. Use makeUserState whenever each user owns an independent entry.

// Avoid: concurrent updates to a shared map overwrite the entire object
const lobby = room.makeState('lobby', {players: {}})
lobby.set(prev => ({
  ...prev,
  players: {...prev.players, [myUserId]: {name, ready: true}}
}))

// Prefer: per-user slots for user-owned entries, shared state for room values
const seat = room.makeUserState('seat', {name: 'Anon', ready: false})
seat.set(prev => ({...prev, ready: true}))

const match = room.makeState('match', {round: 0, dealer: null})

Ordering writes with Hybrid Logical Clocks

Both state primitives resolve concurrent writes using whole-value last-writer-wins. Relying on raw wall clocks alone would let a machine whose clock runs a few seconds fast overwrite newer updates from peers with accurate clocks, and ties within the same millisecond would resolve inconsistently.

Trystero stamps every record with a Hybrid Logical Clock (HLC) tuple [wallMs, counter]. When producing a new write, a peer takes the maximum of its local wall clock, its previous HLC timestamp, and the timestamp of the record being replaced; if the wall-clock millisecond does not advance, counter increments. Every replacement therefore sorts strictly after the record it observed, even across minor clock skew or backward local clock adjustments.

Remaining ties break deterministically across the full tuple ([wallMs, counter], userId, peerId, sig), guaranteeing every peer converges on the exact same winning record regardless of arrival order. To prevent a far-future clock from pinning a slot indefinitely, peers drop incoming records dated more than 10 seconds ahead of local wall time (or up to cert.iat + 10s, capped at 60 seconds, for role-certified writes).

Signed records and safe relaying

Every set() and clear() call canonicalizes its payload and signs it with the author's ECDSA P-256 identity key over appId, roomId, namespace, HLC timestamp, peerId, userId, JSON value (or deletion flag), and any inline role certificate.

Because signatures bind the full context, remaining peers can forward the latest makeState record to newcomers after the original author disconnects without newcomers having to trust the forwarder: any modification, replay from another room, or forged userId fails ECDSA verification.

Calling clear() on makeUserState publishes a signed tombstone so remote listeners fire with removed: true. Each userId is bounded to 32 per-user namespaces and 64 KiB total active payload across the room.

Handshake flush, anti-entropy, and passive backups

Per-user state written immediately after joinRoom() is bundled into the admission handshake so direct peers already hold a new user's profile before onUserJoin fires.

For shared state, reconnects, and multi-hop scale() overlays, peers run cursor-paged anti-entropy reconciliation—exchanging compact record digests and transferring any missing or newer records. Banning a user via roles() purges all records signed by that userId.

If every browser tab leaves a room, in-memory state disappears. To retain shared state across empty intervals, run a passive: true peer in Node, Bun, or Deno declaring the same makeState namespaces; it verifies and caches signed records for future visitors without needing admin permissions.

Local updates, coalescing, and validation

set() updates local snapshots and invokes local onChange handlers synchronously, while coalescing signing and network broadcasts over a 40 ms window per slot. Both primitives return frozen snapshots and unsubscribe functions compatible with React's useSyncExternalStore.

Optional validate and maxBytes settings (default 16 KiB, max 64 KiB) run on both local writes and incoming remote records:

const playback = room.makeState(
  'playback',
  {src: null, paused: true, positionSec: 0, setAt: 0},
  {
    maxBytes: 2048,
    validate: next =>
      typeof next === 'object' &&
      next !== null &&
      (next.src === null ||
        (typeof next.src === 'string' && next.src.startsWith('https://'))) &&
      typeof next.paused === 'boolean' &&
      Number.isFinite(next.positionSec) &&
      next.positionSec >= 0 &&
      Number.isFinite(next.setAt)
  }
)

await playback.set(prev => ({...prev, positionSec: -40})).catch(console.warn)

In multi-writer namespaces, validate invariants on next (and context.userId / context.roles) rather than strict prev -> next step transitions, since concurrent last-writer-wins updates may arrive without having observed one another.

When to layer a CRDT over actions

Whole-value last-writer-wins fits discrete state such as playback status, turn indicators, and round metadata. When concurrent edits to the same object must merge rather than overwrite—collaborative rich text, shared append-only queues, or concurrent counters—use a CRDT library such as Yjs or Automerge and send its binary deltas over makeAction:

import * as Y from 'yjs'
import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'poetry.example.com'}, 'kitchen')
const doc = new Y.Doc()
const poem = doc.getText('poem')

const updates = room.makeAction('y-update')

doc.on('update', (update, origin) => {
  if (origin !== 'remote') updates.send(update)
})

updates.onMessage(update => Y.applyUpdate(doc, update, 'remote'))

room.onUserJoin(({userId}) => {
  updates.send(Y.encodeStateAsUpdate(doc), {target: userId})
})

For larger documents, exchange Yjs state vectors on join instead of full snapshots while keeping ephemeral presence (names, cursor colors) in makeUserState.