Migrating from Playroom Kit

A Playroom Kit game has no server code. Every player’s browser writes its own state, and one player, the host, runs the logic everyone else trusts. On IRT that logic moves into a room: room code you write in TypeScript, which runs on IRT’s machines, owns the game state and checks everything clients send. Players still write some values straight from the client, such as their position or cursor, but only the fields you declare writable on entities they own, and the room checks each write.

There is no compatibility layer: IRT doesn’t implement insertCoin, myPlayer or RPC, and Playroom code doesn’t run on it unchanged. The port is mostly moving the code inside if (isHost()) into a room module and replacing state keys with typed entities.

Concept map

Playroom Kit IRT
insertCoin(options) connect(roomUrl, { schema }), after finding a room with createRoom, joinByCode, listPublic or quickJoin, which return room URLs. A page declares its project with <meta name="irt-project">. IRT draws no lobby screen, though the UI kit has one
The code the lobby screen shows createRoom({ joinCode: true }) returns a 6-character code; joinByCode turns it into a room URL
skipLobby and a random room quickJoin
maxPlayersPerRoom maxPlayers on createRoom or quickJoin
The host player, isHost() None. The room runs the logic, so the host’s branches become room code
setState(key, value) and getState(key) Fields of room.state, which only the room writes and every client reads
player.setState(key, value) A writable field of an entity the player owns: entity.x = 5 on the client, checked by its kind’s write handler in the room
State only one player should see Private state: room.private(conn) in the room, room.private on the client
myPlayer(), me() room.player for the ID, room.entities.mine(kind) for the entities it owns
onPlayerJoin(cb) and player.onQuit(cb) room.presence.onJoin and onLeave on the client; onJoin and onLeave hooks in the room
player.getProfile() Presence gives each player a name the room sets and a status the player sets. Colors and avatars are yours
RPC.register and RPC.call(name, data, RPC.Mode.HOST) with a reply Calls: a handler in the room, await room.calls.name(args) on the client
RPC.call with RPC.Mode.ALL or OTHERS room.send(msg) to the room, which forwards it with room.broadcast(msg, { except })
waitForState(key) connect resolves with the full state applied; room.entities.onChange for later changes
React hooks such as usePlayersList and useMultiplayerState Connect in an effect and read the client; see React
Playroom’s hosted relay IRT hosts the rooms, and can host the site too, at <project>.irt-serve.com

A game, ported

A coin chase: players move around a 100 by 100 board, and whoever reaches the coin scores and moves it. Players can wave at each other and set a display name.

In Playroom Kit

Each client moves its own player. The host checks pickups and moves the coin:

// main.js
import { getState, insertCoin, isHost, myPlayer, onPlayerJoin, RPC, setState } from "playroomkit";

await insertCoin({ maxPlayersPerRoom: 8 });

const players = [];
onPlayerJoin((player) => {
  players.push(player);
  player.onQuit(() => players.splice(players.indexOf(player), 1));
});

RPC.register("wave", async (data, caller) => showWave(caller.id));

if (isHost()) setState("coin", { x: 50, y: 50 }, true);

function frame() {
  const me = myPlayer();
  const pos = me.getState("pos") ?? { x: 10, y: 10 };
  if (keys.has("ArrowRight")) pos.x = Math.min(100, pos.x + 1);
  me.setState("pos", pos);

  if (isHost()) {
    const coin = getState("coin");
    for (const p of players) {
      const at = p.getState("pos");
      if (at && Math.hypot(at.x - coin.x, at.y - coin.y) < 3) {
        p.setState("score", (p.getState("score") ?? 0) + 1, true);
        setState("coin", { x: Math.random() * 100, y: Math.random() * 100 }, true);
      }
    }
  }
  for (const p of players) draw(p.id, p.getState("pos"), p.getProfile().name);
  requestAnimationFrame(frame);
}
frame();

document.querySelector("#wave").onclick = () => RPC.call("wave", {}, RPC.Mode.OTHERS);

Any client can write any of these keys, so a modified client can teleport or award itself points, and the game is only as fair as the host’s browser.

In IRT

The schema, shared by room and client. The player’s position stays client-written, as writable fields of an entity the player owns; the score stays the room’s:

// schema.ts
import { defineCalls, defineSchema, entity } from "@irtio/room";

export const Player = entity("player", { x: "f32", y: "f32", score: "u16" }, { writable: ["x", "y"] });
export const Board = entity("board", { coinX: "f32", coinY: "f32" });

export const schema = defineSchema({
  state: Board,
  entities: [Player],
  calls: defineCalls<{ rename(args: { name: string }): string }>({
    rename(raw) {
      const name = (raw as { name?: unknown } | null)?.name;
      if (typeof name !== "string" || name.trim() === "") throw new Error("name must be a non-empty string");
      return { name };
    },
  }),
});

The room holds what the host did, and checks each position a client writes: at most 3 units a tick, and on the board. Players move all the time and the room checks pickups each tick, so it declares a tickRate. A game whose state changes only on messages and calls, such as a card game, leaves tickRate out, and its changes go out as they happen.

// room.ts
import { defineRoom, type RoomEntity } from "@irtio/room";
import { Board, Player, schema } from "./schema.js";

const MAX_STEP = 3;

function toward(from: number, to: unknown): number {
  if (typeof to !== "number" || !Number.isFinite(to)) return from;
  const step = Math.min(MAX_STEP, Math.max(-MAX_STEP, to - from));
  return Math.min(100, Math.max(0, from + step));
}

export default defineRoom({
  tickRate: 20,
  schema,
  onCreate(room) {
    room.state.coinX = 50;
    room.state.coinY = 50;
  },
  onJoin(room, conn) {
    if ([...room.entities.ownedBy(conn.player, Player)].length > 0) return;
    room.entities.create(Player, { x: 10, y: 10 }, { owner: conn.player });
  },
  writes: {
    player: (room, conn, p, write) => ({ x: toward(p.x, write.x ?? p.x), y: toward(p.y, write.y ?? p.y) }),
  },
  onTick(room) {
    const board: RoomEntity<typeof Board> = room.state;
    for (const p of room.entities.all(Player)) {
      if (Math.hypot(p.x - board.coinX, p.y - board.coinY) >= 3) continue;
      p.score += 1;
      board.coinX = Math.random() * 100;
      board.coinY = Math.random() * 100;
    }
  },
  onMessage(room, conn, message) {
    if ((message as { type?: unknown } | null)?.type === "wave") {
      room.broadcast({ type: "wave", from: conn.player }, { except: conn });
    }
  },
  calls: {
    rename({ name }, { room, connection }) {
      const trimmed = name.trim().slice(0, 64);
      room.presence.set(connection.player, { name: trimmed });
      return trimmed;
    },
  },
});

Players who leave keep their entity and score for when they come back. To remove them, delete it in onLeave, which also runs for a dropped network, or in onPlayerLeave, which runs once the player’s presence ends, as the Colyseus guide does.

The client keeps its frame loop. It writes its own position and reads everyone else’s from the room:

// client.ts
import { connect, createRoom, joinByCode } from "@irtio/client";
import { Player, schema } from "./schema.js";

const keys = new Set<string>();
addEventListener("keydown", (e) => keys.add(e.key));
addEventListener("keyup", (e) => keys.delete(e.key));

// The join code goes in the page's URL, as Playroom does with #r=. The project is the
// page's <meta name="irt-project" content="https://rooms.irt.io/coins/">.
async function roomUrl(): Promise<string> {
  const code = new URLSearchParams(location.hash.slice(1)).get("r");
  if (code) return joinByCode(code);
  const { url, joinCode } = await createRoom({ joinCode: true, maxPlayers: 8 });
  location.hash = `r=${joinCode}`;
  return url;
}

const room = await connect(await roomUrl(), { schema });
await room.calls.rename({ name: "Alice" });
room.addEventListener("message", (e) => console.log("wave from", (e.data as { from: string }).from));
document.querySelector("#wave")?.addEventListener("click", () => room.send({ type: "wave" }));

const others = room.interpolate(Player, ["x", "y"]);

function frame() {
  for (const me of room.entities.mine(Player)) {
    if (keys.has("ArrowRight")) me.x = Math.min(100, me.x + 1);
  }
  for (const p of room.entities.all(Player)) {
    const owner = room.entities.ownerOf(p);
    if (!owner) continue;
    const at = owner === room.player ? p : others.get(p);
    console.log(room.presence.get(owner)?.name ?? owner, at.x, at.y, p.score);
  }
  requestAnimationFrame(frame);
}
frame();

Owner writes show on the writing client at once and go to the room at most once per tick. Remote players are drawn through interpolate, a little behind, so they move smoothly between ticks. Games where movement must be fair, such as shooters, should go further and send inputs to a stepper the room runs, rather than positions.

Its tests

// room.test.ts
import { testRoom } from "@irtio/testing";
import { expect, test } from "vitest";
import room from "./room.js";
import { Player } from "./schema.js";

test("a player moves itself, and the room limits how far", async () => {
  const t = testRoom(room);
  const alice = await t.connect({ player: "alice" });
  const bob = await t.connect({ player: "bob" });
  const [me] = alice.mine(Player);

  me!.x = 12;
  await t.host.tick(2);
  expect(bob.view(Player).find((p) => p.id === me!.id)).toMatchObject({ x: 12 });

  me!.x = 90;
  await t.host.tick(2);
  alice.expectCorrected(me!.id, "x");
  expect(me!.x).toBe(15);
});

test("the room scores a pickup, renames and forwards waves", async () => {
  const t = testRoom(room);
  const alice = await t.connect({ player: "alice" });
  const bob = await t.connect({ player: "bob" });
  t.live.state.coinX = 10;
  t.live.state.coinY = 10;
  await t.host.tick();
  expect(alice.mine(Player)[0]).toMatchObject({ score: 1 });

  const renamed = alice.client.calls.rename({ name: "  Alice " });
  await expect(alice.client.calls.rename({ name: "" })).rejects.toThrow("non-empty");
  await t.host.tick();
  await expect(renamed).resolves.toBe("Alice");
  expect(bob.client.presence.get("alice")?.name).toBe("Alice");

  alice.send({ type: "wave" });
  await t.host.tick();
  bob.expectMessage({ type: "wave", from: "alice" });
  expect(alice.messages).toEqual([]);
});

What has no direct equivalent

The host player. Playroom picks one player’s browser to run the logic and moves the job when that player leaves. IRT has no host player: the room is the authority, it keeps running while players come and go, and it saves its state when everyone has left. Code under isHost() moves to onTick, onMessage and call handlers, and code for host changes goes away. If the game has a player in charge, such as a party leader who picks the map, keep their ID in room.state, pass it on in onLeave, and check it in the calls that need it.

Client-authoritative state. In Playroom any client can write any player’s state and the shared state. In IRT a client can write only the writable fields of entities it owns, and its private state, and the room’s write handlers have the last word. Everything else is the room’s, and clients ask for changes with messages and calls. If you really want a client to decide something, such as a value nobody else can check, make the field writable and give its kind no write handler.

Physics on the host. A Playroom game that simulates on the host and shares the results should run the simulation in the room instead. Use @irtio/physics as the room’s stepper, and clients predict their own body with the same code.

The lobby screen and profiles. IRT shows no UI and has no player profiles. Build your own menu with createRoom, joinByCode, listPublic and quickJoin (see Games without a backend), and keep names in presence and colors or avatars in an entity or in private state. Playroom’s stream mode and platform integrations have no counterpart.

Unreliable state. IRT sends entity changes reliably, as deltas, once per tick or, in a room without ticks, as they happen. For values that are fine to lose, send room.send(msg, { unreliable: true }) and forward them with room.broadcast(msg, { unreliable: true }).

State that outlives the room. An IRT room’s state is kept when it hibernates, for as long as rooms.retention says, but data that belongs to a player across rooms, such as unlocks, needs your own backend and player tokens.

Checklist

  1. Create a project with npx @irtio/cli init and write schema.ts: a kind per kind of thing, the global keys as state, per-player keys as fields of a player kind, secrets as private. Import it from room and client.
  2. Move every isHost() branch into the room module, and delete host migration code.
  3. For each player.setState the player should keep writing, make the field writable, give the player the entity in onJoin, and check values in the kind’s handler in writes. Move the rest into room code driven by messages, calls or a stepper.
  4. Turn RPCs to the host that return a value into calls, and RPCs to everyone into a message the room forwards.
  5. Replace insertCoin with your own room menu and connect; set players.guests, players.createRooms and players.quickJoin in irt.config.ts to match.
  6. Replace onPlayerJoin and getProfile with room.presence.
  7. Write tests with @irtio/testing for moving, for each rule the host used to check, for a write the room must correct (expectCorrected), a dropped connection and a hibernation. The testing guide has a pattern for each.
  8. Run it with npx irt dev, check rooms in the inspector, then npx irt deploy, which serves the site from <project>.irt-serve.com with the room code it was built against.