docs / room.direct
api guide

room.direct

A direct line between two people in a room — their browser to yours, a few milliseconds apart. For games where every frame counts: a fighting game, a racer, air hockey.

pubpart of ctx.liveWebRTC, handled for you

A ctx.live room already pushes changes to everyone the moment they happen. But every message goes to Fave1’s server and back — tens of milliseconds nearby, a few hundred across an ocean. That is plenty for a shared list, a cursor or a board game, and too slow for a punch that has to land in the next frame. A direct line skips the server: one browser sends straight to the other.

You’re sendingUseWhy
what everyone must agree onroom.set() — the score, whose turn it is, the board, who wonkept · everyone
where you are right nowroom.cursor() — a pointer, a selection, “typing…”everyone · 25 a second
every frame, to one personroom.direct(sid) — inputs, positions, hitsfast · two people

Most apps never need it. If you can’t say why 50 ms matters for yours, a room is simpler — and a direct line always sits inside one: you meet in the room, keep score in the room, and only the fast part goes on the line.

Calls

room.direct
room.on('direct', (line) => …);                      // take lines others open to you — register first
const line = await room.direct(sid, { lossy: true });   // open one to a person in the room, by their sid

line.send({ f: 1204, keys: 5 });   // JSON up to 1 KB · false if the line isn't open or it's too big
line.on('message', (data) => …);   // also 'open' · 'close' · 'error'
line.close();

line.open;    // connected right now
line.via;     // 'direct' · 'relay' · 'room' — which way it's going
line.rtt;     // round trip in ms, measured every 2 s · null through the room
line.lossy;   // drops late messages instead of waiting
line.sid;  line.id;   // their socket · their app-scoped id

No permission of its own — a line lives inside a room, and rooms use pub. Nothing on a line is stored anywhere, nobody else in the room sees it, and someone who joins later sees nothing of it.

Your first line in 30 lines

Two players, each moving a paddle; each sees the other’s. Everyone listens for lines, and whoever joins calls the people already there — so every pair ends up with exactly one line, however they arrive.

src/index.ts
// A room per match. Put the code in the link you share — that's the invite.
const code = new URL(location.href).searchParams.get('match') ?? 'LOBBY';
const room = await ctx.live.join(`pong:${code}`);
const lines = new Map<string, DirectLine>();

function keep(l: DirectLine) {
  lines.set(l.sid, l);
  l.on('message', (d) => drawPaddle(l.sid, d as { y: number }));
  l.on('close', () => { lines.delete(l.sid); removePaddle(l.sid); });
}

// 1. Take lines others open to you. Do this first — a line nobody listens for is declined.
room.on('direct', keep);

// 2. Call everyone already here. Newcomers will call you.
for (const p of room.peers()) {
  room.direct(p.sid, { lossy: true }).then(keep, () => { /* they left, or don't take lines */ });
}

// 3. Sixty times a second, send where your paddle is. Latest wins, so lossy is right.
const timer = setInterval(() => {
  for (const l of lines.values()) l.send({ y: myPaddleY() });
}, 1000 / 60);   // clearInterval(timer) in onDestroy

Run it in two tabs from fave1 dev and the paddles move together — see Testing it.

Opening a line

One side calls, the other takes it. direct(sid) opens a line to one person, by the sid you get from room.peers() or a peer event. On the other side the line arrives on room.on('direct'), already open. If both call each other at the same moment, each gets the same single line back — no duplicates, no event.

Listening is how your app says yes. A line shows each browser the other’s network address (below), so Fave1 opens one only when both apps want it: the other side has registered room.on('direct'), or has called direct() to you. Otherwise direct() waits 3 s — the other app may have just joined — and rejects with declined. Register the listener right after join(); an app that doesn’t use lines simply never registers one, and nobody can open a line to it. Someone who already has 8 lines in the room declines a ninth the same way.

In a room of strangers, ask first — through the room. Taking a line already connects the two browsers, so “take it, then ask Play?” has shown both addresses before anyone said yes. In a lobby, don’t register room.on('direct') at all. Send the challenge with room.cursor() — it reaches everyone in the room and is never kept — and when the other person says yes, both of you call direct(). Two calls to each other meet as one line, and no line ever opens to someone who didn’t agree.

src/index.ts
// A lobby: no room.on('direct') here, so nobody can open a line to you until you say yes.
const lobby = await ctx.live.join('lobby');
type Ask = { ask?: string; yes?: string };            // what goes in cursor() — a sid, never a name

// Challenge: tell the room who you'd like to play. Only that person acts on it.
function challenge(p: LivePeer) { lobby.cursor({ ask: p.sid }); }

lobby.on('peer', (ev) => {
  if (ev.type !== 'cursor') return;
  const said = (ev.peer.data ?? {}) as Ask;
  // They challenged you — ask your player before anything connects.
  if (said.ask === lobby.me.sid) {
    ctx.ui.render([
      ctx.ui.text(`${ev.peer.initial} wants to play.`),
      ctx.ui.button('Play', { onClick: () => { lobby.cursor({ yes: ev.peer.sid }); connect(ev.peer); } }),
      ctx.ui.button('Not now', { onClick: () => lobby.cursor({}) }),
    ]);
  }
  // They said yes to you — call them too. The two calls meet as one line.
  if (said.yes === lobby.me.sid) connect(ev.peer);
});

async function connect(p: LivePeer) {
  try {
    startMatch(await lobby.direct(p.sid, { lossy: true }));
    lobby.cursor({});                                 // the challenge is answered — clear it
  } catch (err) {
    const e = err as Fave1Error;
    if (e.code === 'not-found') ctx.ui.toast(`${p.initial} just left.`);
    else if (e.code === 'declined') ctx.ui.toast('They’re in another match.');
    else throw err;
  }
}
for (const p of lobby.peers()) showChallengeButton(p, () => challenge(p));

The answer has to come within 3 s of the first call — the one who said yes calls at once, so in practice it does. The same sid always gives the same line while it is open — calling direct() again just hands it back. One person can have up to 8 lines in a room at once, opened by them or to them.

How it connects

You never set any of this up. Fave1 opens the connection inside its own frame and tries, in order:

viaWhat it isSpeed
'direct'Browser to browser. Most home and mobile networks.fastest
'relay'Through a nearby relay when a firewall blocks the direct path — still not through Fave1’s room.close to direct
'room'Through the room’s server, when neither worked within 8 s, or a browser has WebRTC switched off.like the room

Your code is the same on all three. direct() resolves once the line is open whichever way it went, and send and message work identically. via can change while a line is open: if the connection between the two browsers fails mid-game while both are still in the room, the line moves to the room instead of closing — nothing sent in between is lost. (If your network drops, the room connection goes too; see When something goes wrong.) rtt is measured, never guessed — read both when you need them, they are always current.

src/index.ts
// How many frames ahead to schedule your own input so theirs arrives in time.
function inputDelay(l: DirectLine): number {
  const ms = l.via === 'room' ? 250 : (l.rtt ?? 80);       // your guess until rtt arrives; through the room, assume slow
  const oneWay = ms / 2;
  return Math.min(8, Math.max(2, Math.ceil(oneWay / (1000 / 60)) + 1));
}

// Tell the player — a quiet badge, not an error.
function connectionLabel(l: DirectLine): string {
  if (l.via === 'room') return 'Slow connection';
  return `${l.rtt ?? '…'} ms`;
}

Lossy or reliable

{ lossy: true }

Latest wins

A late message is dropped instead of holding up the ones behind it. For anything you send again next frame anyway: positions, aim, a ball’s state.

default

Every message, in order

Nothing is lost, nothing overtakes. A lost packet is resent, and what follows waits for it — a short stall on a bad network. For chat, moves in a turn, “I’m ready”.

The side that opens the line chooses; the other side reads line.lossy. A line has one mode — for the occasional message that must arrive on a lossy line, put it in the room (room.set) instead, or repeat it in the next few messages. Through the room every message arrives in order, whatever you chose.

Fighting games: send inputs, not positions

In a fighting game, positions aren’t enough: both screens must agree on exactly who hit whom on which frame. The way every online fighting game does it is lockstep — both browsers run the same game from the same inputs. Each frame needs both players’ input for that frame; you send yours a few frames early so it is there in time, you send the last few again in every message, and while you wait you send them again — so a dropped message, or a line moving to the room, never stalls the game.

src/index.ts
const room = await ctx.live.join(`fight:${code}`);
room.on('direct', (l) => start(l));
const other = room.peers()[0];
if (other) start(await room.direct(other.sid, { lossy: true }));

function start(line: DirectLine) {
  const DELAY = 3;                                   // frames ahead — see inputDelay() above
  const p1 = (room.me.sid ?? '') < line.sid;         // both sides agree who is player 1
  const mine = new Map<number, number>();
  const theirs = new Map<number, number>();
  const sent: { f: number; k: number }[] = [];
  let f = 0, waited = 0;

  // The first DELAY frames have no input on either side.
  for (let i = 0; i < DELAY; i++) { mine.set(i, 0); theirs.set(i, 0); }

  line.on('message', (d) => {
    for (const e of d as { f: number; k: number }[]) if (e.f >= f && !theirs.has(e.f)) theirs.set(e.f, e.k);
  });

  function tick() {
    if (!line.open) return;
    if (theirs.has(f)) {                             // both inputs for frame f are here — step it
      const next = f + DELAY;
      const k = readKeys();                          // a small number: one bit per button
      mine.set(next, k);
      sent.push({ f: next, k });
      if (sent.length > 8) sent.shift();
      line.send(sent);                               // the last 8 — any one message covers the gaps

      const a = mine.get(f) ?? 0, b = theirs.get(f) ?? 0;
      step(p1 ? a : b, p1 ? b : a);                  // same order on both screens
      mine.delete(f); theirs.delete(f);
      f++;
      waited = 0;
    } else if (++waited % 6 === 0) {
      line.send(sent);                               // still waiting? say your last 8 again — theirs may be waiting on yours
    }
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);
}

Three rules make it hold: the game must be deterministic — same inputs, same result on every device, so no Math.random() (seed your own generator from the room) and no frame-time physics; inputs are small — 8 of them fit easily in 1 KB; and results go in the room — when the match ends, both sides write the winner with room.set, so a spectator or a latecomer sees it. Waiting for the other input costs a frame when the network hiccups; games that can’t afford that predict the other player’s input and rewind when the real one arrives (“rollback”) — the same loop, with a snapshot of your game state per frame.

When something goes wrong

What happenedWhat you seeDo
the connection between you failedNothing closes — via becomes 'room' and messages keep coming, slowershow a badge
they closed itclose with 'closed'back to the lobby
they left the roomclose with 'left', and a peer leave“They left” · win by forfeit
your network droppedclose with 'lost' — your room connection went too; the room reconnects by itself and fires opencall again on open
your app closedclose with 'gone'nothing

After a 'lost' you come back into the room with a new sid; the others keep theirs and see you leave and join again (their line to you closes with 'left'). Find your opponent again by their id, which never changes, and call them — they take it as they did the first time:

src/index.ts
const room = await ctx.live.join(`fight:${code}`);

// Their id is stable across reconnects; their sid is not.
let opponentId = '';
room.on('direct', (l) => { opponentId = l.id; play(l); });

room.on('open', () => {                             // the room came back after a drop
  const again = room.peers().find((p) => p.id === opponentId);
  if (again) room.direct(again.sid, { lossy: true }).then(play, () => showWaiting());
});

What the other side sees

A line connects two browsers, so each can see the other’s network (IP) address — as on any video call. Fave1 opens the connection inside its own frame: neither the page you’re on nor your app’s code sees the addresses or the relay credentials, and the room’s server never sees what you send on a direct line.

That is why a line needs both apps to want it. Where people already chose each other — an invite link, a private match code — listening with room.on('direct') is fine. Where strangers meet, ask through the room first and let both sides call (Opening a line), so no line opens to someone who didn’t say yes. People see the first letter of the other’s name and their avatar, never a name, the same as everywhere else in a room.

Limits and errors

1 KB

Per message

As JSON. Over it, send() returns false and an error event says too-large.

8

Lines at once

Per person, per room — the ones you opened and the ones opened to you. A ninth is declined. Every pair needs its own line, so a full mesh tops out at 9 players.

120 / s

Through the room

Only on a 'room' line, added up across all your lines going through the room — 60 Hz to one person fits twice. A direct line has no limit but the network’s.

8 s · 20 s

Opening

8 s to go direct before falling back to the room; direct() gives up after 20 s with timeout.

direct() rejectsWhyDo
declinedTheir app doesn’t take lines — no room.on('direct') and no direct() back within 3 s — or they already have 8say so
not-foundNobody with that sid is in the room — they left, or the room reconnectedrefresh peers()
invalidNot a sid, or your ownfix it
quotaYou already have 8 lines in this room, counting the ones opened to youclose one
unreachableThe room is closed — before join() finished, after leave(), or while it reconnectswait for open
timeoutNot open after 20 s — rare, the room fallback normally lands at 8 stry again
error eventOn an open lineDo
too-largeA message over 1 KB — it wasn’t senttrim it
rateOver 120 a second through the room (all your room lines together), or the other side isn’t keeping up (256 KB waiting) — it wasn’t sentsend less
invalidCouldn’t be turned into JSON (a loop, a BigInt). A function or a symbol reports too-largefix it

Testing it

  • Two tabs, no setup. With fave1 dev, open the same site in two tabs and open your app in both. They meet in a sandbox room in this browser, and lines open between them through it — via says 'room', and everything else behaves for real: declined, left, close.
  • A real connection. Switch Data to My account and open your build signed in on two browsers — the same account in two browsers is two people in a room. Lines go 'direct' now. Two devices on different networks — your phone on mobile data — show you real round trips.
  • The fallback. Open one side in Firefox with media.peerconnection.enabled set to false in about:config. That side has no WebRTC, so the line opens through the room — check your game still plays.

Questions

QuestionAnswer
More than two players?Every pair needs a line, and one person can hold 8 — so up to 9 players all connected to each other. Past that, use the room.
Spectators?They don’t need lines. Have a player write the game state to the room a few times a second with room.set; watchers draw from change.
Can a player cheat?Each browser runs its own code, and nobody referees a line. Use it for fun; a result that matters goes in the room, where both players write it, and a board in ctx.pub is for bragging, not prizes.
Phones?iPhone Safari and Android Chrome both connect. Mobile networks often need the relay; it’s automatic.
Does it cost me anything?No. Fave1 runs the room, the relay and the fallback.
Can I use my own WebRTC or WebSocket?No — no connections to servers you run (Beyond ctx). Lines and rooms are the way.