Examples Watch party

Watch party with synced playback

Synchronize a <video> element across browsers using a single shared playback record, a per-user viewer roster, and an action channel for transient reactions. Late joiners seek straight to the current timestamp.

Playback, presence, and reactions

makeState('playback') stores the media URL, playback position, play/pause flag, and write timestamp. makeUserState('viewer') tracks active viewers, and makeAction('reaction') broadcasts one-off emoji reactions.

import {joinRoom} from 'trystero'

// Invite link: https://example.com/party#movie-night:k9Qf2xTq
const [partyId, password] = (location.hash.slice(1) || 'couch').split(':')
const room = joinRoom({appId: 'example.com/party', password}, partyId)
const video = document.querySelector('video')

const playback = room.makeState(
  'playback',
  {src: '', positionSec: 0, paused: true, updatedAt: 0},
  {
    validate: next =>
      typeof next.src === 'string' &&
      typeof next.paused === 'boolean' &&
      Number.isFinite(next.positionSec) &&
      next.positionSec >= 0
  }
)
const viewer = room.makeUserState('viewer', {name: 'Guest', emoji: '๐Ÿฟ'})
const reaction = room.makeAction('reaction')

const {peerId: thisTab} = await room.getSelf()

const expectedPosition = ({positionSec, paused, updatedAt}) =>
  paused ? positionSec : positionSec + (Date.now() - updatedAt) / 1000

const drift = state => Math.abs(video.currentTime - expectedPosition(state))

const applyPlayback = state => {
  if (!state.src) return
  if (video.src !== state.src) video.src = state.src
  if (drift(state) > 1) video.currentTime = expectedPosition(state)
  if (state.paused) video.pause()
  else video.play().catch(() => showTapToJoin(() => applyPlayback(playback.get())))
}

playback.onChange((next, {peerId}) => {
  // Compare peerId rather than userId so a second tab of yours still syncs
  if (peerId !== thisTab) applyPlayback(next)
}, {replay: true})

for (const type of ['play', 'pause', 'seeked']) {
  video.addEventListener(type, () => {
    const state = playback.get()
    if (!video.currentSrc) return
    if (video.paused === state.paused && drift(state) <= 1) return
    playback.set(prev => ({
      ...prev,
      positionSec: video.currentTime,
      paused: video.paused,
      updatedAt: Date.now()
    }))
  })
}

urlForm.onsubmit = e => {
  e.preventDefault()
  playback.set({
    src: urlInput.value,
    positionSec: 0,
    paused: true,
    updatedAt: Date.now()
  })
}

viewer.onChange(() => renderViewers(viewer.getAll()))
viewer.set({name: nameInput.value || 'Guest', emoji: '๐Ÿฟ'})

reaction.onMessage((emoji, {userId}) => floatEmoji(emoji, userId))
reactionBar.onclick = e => {
  const {emoji} = e.target.dataset
  if (!emoji) return
  reaction.send(emoji)
  floatEmoji(emoji, 'you')
}

room.onError(err => {
  if (err.code === 'decrypt-failed') showBanner('Invalid invite password')
})

Drift compensation and echo suppression

Because a raw timestamp grows stale while video is playing, expectedPosition adds Date.now() - updatedAt whenever paused is false. Incoming updates only seek when local playback drifts by more than one second, preventing oscillation over normal network jitter.

DOM media events (play, pause, seeked) fire for both user input and programmatic updates. Checking whether the element already matches playback.get() within the one-second tolerance prevents remote updates from echoing back out as new writes. Filtering onChange by peerId !== thisTab skips the current tab's own writes while still keeping a second tab on the same browser in sync.

If browser autoplay rules block an unmuted video.play() call on initial join, the catch handler surfaces a user-gesture button that re-applies the latest state and seeks to the live position.

Late joiners and passive backups

makeState is room-scoped: connected peers cache the latest signed playback record and forward it to newcomers even if the participant who started playback has disconnected.

If every browser tab closes, in-memory room state ends with the session. To preserve state across empty rooms, run a passive: true peer in Node, Bun, or Deno declaring makeState('playback'); see Running in Node, Bun & Deno.

Passwords and write permissions

Placing the room secret after : in the URL hash keeps it out of HTTP requests while feeding password into joinRoom(). Trystero derives the signaling key with PBKDF2-SHA256 (600,000 iterations), and wrong keys surface as 'decrypt-failed' on room.onError.

In an open room without roles(), any viewer can control playback and concurrent scrubs converge via last-writer-wins. To restrict playback controls to a host, load roles() so playback defaults to admin-only writes (see the trivia host example).