Migrating from Colyseus
Colyseus and IRT have the same shape: authoritative room code that the framework runs, state synced to clients as binary patches, and a client SDK that joins rooms. Most of a port is mechanical. The differences that take thought are that IRT rooms hibernate and wake, so state lives in synced entities rather than in fields of a class, and that IRT has no matchmaker you program: rooms are found by ID, join code, the public list or quick join.
There is no compatibility layer. IRT doesn’t run Colyseus room classes or
speak the Colyseus client protocol, and isn’t planning to: Colyseus
expects long-running processes that share a matchmaker and a presence
store, which rooms that hibernate and wake in any room host don’t fit.
You rewrite the room against @irtio/room and the client against
@irtio/client. Game logic carries over nearly line for line.
This page describes Colyseus 0.16 with @colyseus/schema 3.
Concept map
| Colyseus | IRT |
|---|---|
class MyRoom extends Room, registered with gameServer.define("name", MyRoom) |
export default defineRoom({...}) in a room module, named in irt.config.ts’s rooms as name: "src/my-room.ts", a room type |
onCreate(options) |
onCreate(room), once in a room’s life. It gets no options; see Create and join options |
onAuth |
Player tokens your backend signs, checked by the router before the room sees the connection, or guests |
onJoin(client, options, auth) |
onJoin(room, conn). Runs on every reconnect too. conn.player is the player, conn.meta the token’s meta claim |
onLeave(client, consented) and allowReconnection |
onLeave(room, conn, { left }), with left as consented. Clients reconnect by themselves and come back as the same conn.player, so key anything that should survive by player |
onDispose |
onHibernate. An empty room saves its room state and wakes on the next connect; rooms.retention decides when it’s deleted |
client.sessionId |
conn.player, stable across reconnects and reloads. conn.id is per connection |
client.userData |
conn.data, not saved |
A Schema class as the room’s state |
defineSchema({ state, private, entities }): a shared state entity, per-player private state, and entity kinds |
MapSchema<Player> keyed by session ID |
Entities of a Player kind with an owner field, or owned by the player |
@view() and StateView |
Interest for what each connection sees, and private state for per-player data |
this.onMessage("type", handler) |
One onMessage(room, conn, message) hook; switch on a type field of your own |
client.send("type", msg), this.broadcast("type", msg, { except }) |
room.send(conn, msg), room.broadcast(msg, { except }) |
| A message and a reply message you match up | Calls: room.calls.name(args) resolves to the handler’s return value |
setSimulationInterval and setPatchRate |
tickRate and onTick(room, dt). Changes go out once per tick. A room with no simulation interval leaves tickRate out and sends its changes as they happen |
this.clock.setTimeout |
Store when something happens in room.state: a tick to check in onTick, or a time for the room’s alarm in a room without ticks. Either survives hibernation |
client.joinOrCreate(name, options) with filterBy and maxClients |
quickJoin with type: name, meta and maxPlayers, then connect with the same type |
client.create, client.joinById |
createRoom, then connect(url) with the room URL it returns, or connect(id) relative to the page’s project URL |
Room listing, LobbyRoom |
listPublic |
setMetadata |
meta given to createRoom, fixed at creation |
this.lock(), maxClients |
maxPlayers, or room.kick(conn) from onJoin |
getStateCallbacks(room) with onAdd, listen, onRemove |
room.entities.onEnter, onChange, onLeave |
room.reconnect(token) |
Automatic |
@colyseus/testing |
@irtio/testing |
A game, ported
A coin chase: players move around a 100 by 100 board, and whoever reaches the coin scores and moves it. Players pick a name when they join, and someone who drops has 20 seconds to come back with their score.
In Colyseus
// src/rooms/CoinRoom.ts (Colyseus 0.16)
import { Client, Room } from "colyseus";
import { MapSchema, Schema, type } from "@colyseus/schema";
export class Player extends Schema {
@type("string") name = "";
@type("number") x = 10;
@type("number") y = 10;
@type("number") score = 0;
}
export class CoinState extends Schema {
@type({ map: Player }) players = new MapSchema<Player>();
@type("number") coinX = 50;
@type("number") coinY = 50;
}
export class CoinRoom extends Room<CoinState> {
maxClients = 8;
state = new CoinState();
onCreate(options: { mode: string }) {
this.setMetadata({ mode: options.mode });
this.onMessage("move", (client, { dx, dy }) => {
const p = this.state.players.get(client.sessionId);
if (!p) return;
p.x = Math.min(100, Math.max(0, p.x + Math.sign(dx) * 2));
p.y = Math.min(100, Math.max(0, p.y + Math.sign(dy) * 2));
if (Math.hypot(p.x - this.state.coinX, p.y - this.state.coinY) < 3) {
p.score += 1;
this.state.coinX = Math.random() * 100;
this.state.coinY = Math.random() * 100;
this.broadcast("collected", { by: client.sessionId });
}
});
}
onJoin(client: Client, options: { name?: string }) {
this.state.players.set(client.sessionId, new Player().assign({ name: options.name ?? "anon" }));
}
async onLeave(client: Client, consented: boolean) {
if (!consented) {
try {
await this.allowReconnection(client, 20);
return;
} catch {}
}
this.state.players.delete(client.sessionId);
}
}
// app.config.ts
gameServer.define("coins", CoinRoom).filterBy(["mode"]);
// client.ts (colyseus.js 0.16)
import { Client, getStateCallbacks } from "colyseus.js";
const client = new Client("wss://coins.example.com");
const room = await client.joinOrCreate<CoinState>("coins", { mode: "classic", name: "Alice" });
const $ = getStateCallbacks(room);
$(room.state).players.onAdd((player, sessionId) => {
$(player).onChange(() => draw(sessionId, player.x, player.y));
});
$(room.state).players.onRemove((_player, sessionId) => erase(sessionId));
room.onMessage("collected", ({ by }) => console.log(by, "scored"));
addEventListener("keydown", (e) => {
if (e.key === "ArrowRight") room.send("move", { dx: 1, dy: 0 });
});
In IRT
The schema module is shared by the room and its clients, in place of
@type decorators that both sides compile:
// schema.ts
import { defineSchema, entity } from "@irtio/room";
export const Player = entity("player", { owner: "string", x: "f32", y: "f32", score: "u16" });
export const Board = entity("board", { coinX: "f32", coinY: "f32" });
export const schema = defineSchema({ state: Board, entities: [Player] });
The room. Names go into presence, which every
room has, rather than onto the player entity. allowReconnection has
no counterpart because the client reconnects by itself, so the room
keeps a player’s entity until their presence entry leaves, 10 seconds
after their last connection dropped, or at once when they leave. The
Colyseus room had no simulation interval, so this one has no
tickRate, and what a message changes goes out as soon as the handler
returns:
// room.ts
import { defineRoom, type RoomEntity } from "@irtio/room";
import { Player, schema } from "./schema.js";
const clamp = (v: number) => Math.min(100, Math.max(0, v));
export default defineRoom({
schema,
onCreate(room) {
room.state.coinX = 50;
room.state.coinY = 50;
},
onJoin(room, conn) {
// A reconnecting player finds the entity it had.
const existing = [...room.entities.all(Player)].find((p) => p.owner === conn.player);
conn.data.player = existing ?? room.entities.create(Player, { owner: conn.player, x: 10, y: 10 });
},
onMessage(room, conn, message) {
const m = message as { type?: unknown; name?: unknown; dx?: unknown; dy?: unknown } | null;
if (m?.type === "name" && typeof m.name === "string") {
room.presence.set(conn.player, { name: m.name.slice(0, 64) });
return;
}
if (m?.type !== "move" || typeof m.dx !== "number" || typeof m.dy !== "number") return;
const p = conn.data.player as RoomEntity<typeof Player>;
p.x = clamp(p.x + Math.sign(m.dx) * 2);
p.y = clamp(p.y + Math.sign(m.dy) * 2);
if (Math.hypot(p.x - room.state.coinX, p.y - room.state.coinY) < 3) {
p.score += 1;
room.state.coinX = Math.random() * 100;
room.state.coinY = Math.random() * 100;
room.broadcast({ type: "collected", by: conn.player });
}
},
onPlayerLeave(room, player) {
for (const p of room.entities.all(Player)) if (p.owner === player) room.entities.delete(p);
},
});
The client. joinOrCreate with filterBy(["mode"]) and maxClients
becomes quickJoin, which needs players.quickJoin on in
irt.config.ts:
// client.ts
import { connect, quickJoin } from "@irtio/client";
import { Player, schema } from "./schema.js";
function draw(owner: string, x: number, y: number) {
console.log("draw", owner, x, y);
}
function erase(owner: string) {
console.log("erase", owner);
}
// The project is the page's <meta name="irt-project" content="https://rooms.irt.io/coins/">.
const { url } = await quickJoin({ meta: { mode: "classic" }, maxPlayers: 8 });
const room = await connect(url, { schema });
room.send({ type: "name", name: "Alice" });
for (const p of room.entities.all(Player)) draw(p.owner, p.x, p.y);
room.entities.onEnter(Player, (p) => draw(p.owner, p.x, p.y));
room.entities.onChange(Player, (p) => draw(p.owner, p.x, p.y));
room.entities.onLeave(Player, (p) => erase(p.owner));
room.addEventListener("message", (e) => console.log("message", e.data));
addEventListener("keydown", (e) => {
if (e.key === "ArrowRight") room.send({ type: "move", dx: 1, dy: 0 });
});
connect resolves with the full state applied, and onEnter doesn’t
replay it, which is why the loop over all(Player) comes first. For
movement that feels instant, replace the move message with a
stepper and prediction once the port works;
the room then declares a tickRate.
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("reaching the coin scores and tells everyone", async () => {
const t = testRoom(room);
const alice = await t.connect({ player: "alice" });
const bob = await t.connect({ player: "bob" });
t.live.state.coinX = 12;
t.live.state.coinY = 10;
alice.send({ type: "move", dx: 1, dy: 0 });
await t.settle();
bob.expectMessage({ type: "collected", by: "alice" });
expect(bob.view(Player).find((p) => p.owner === "alice")).toMatchObject({ x: 12, score: 1 });
});
test("a dropped player keeps their score, and a player who left is removed", async () => {
const t = testRoom(room);
const alice = await t.connect({ player: "alice" });
const bob = await t.connect({ player: "bob" });
t.live.state.coinX = 12;
t.live.state.coinY = 10;
alice.send({ type: "move", dx: 1, dy: 0 });
await t.settle();
alice.drop();
await alice.reconnected();
expect(alice.view(Player)).toEqual(expect.arrayContaining([expect.objectContaining({ owner: "alice", score: 1 })]));
await alice.close();
await t.settle();
expect(bob.view(Player).map((p) => p.owner)).toEqual(["bob"]);
});
What has no direct equivalent
filterBy on any option, and custom matchmaking. quickJoin picks
the fullest public room whose meta has equal values for every top-level
key you pass, or creates one. That covers filterBy on a few fixed
options with sortBy({ clients: -1 }). Anything more, such as skill
ranges, parties, queues or matchMaker.reserveSeatFor, belongs in your
backend: it lists rooms with GET /projects/{p}/rooms, creates them with
POST /projects/{p}/rooms and signs a player token
whose room claim limits the player to the room it chose. The token is
the seat reservation.
Create and join options. Rooms get no options on create or join.
What a player brings, such as a name or a team chosen on your site, goes
in a message or call after joining, or, if the room shouldn’t trust the
client, in the meta claim of a token your backend signs. What a room is
set up with goes in its room ID, which you choose with createRoom({ id }),
or in an onRequest message from your backend before players arrive.
createRoom’s meta is for listPublic and quickJoin to read; the
room itself doesn’t see it.
Several room types. Each gameServer.define becomes a
room type in irt.config.ts’s rooms, with its
own module, schema and migrations. A room’s type is fixed when it’s
created; clients name it with type in connect, createRoom,
quickJoin and listPublic, and a client of the wrong type is closed
with 4015. Unlike Colyseus, a type isn’t chosen by the room ID: a room ID
names one room, whatever its type.
Presence and cross-room messages. Colyseus’s presence store lets
rooms and processes publish to each other. IRT rooms don’t message each
other. A backend sends a message into any room with
POST /projects/{p}/rooms/{id}/messages, which the room answers in
onRequest, and hears about rooms through webhooks.
IRT’s presence is something else: the list of players in one room.
Nested schemas and collections. Entity fields are flat scalars,
strings, bytes and JSON. A MapSchema or ArraySchema of schemas
becomes an entity kind; a small nested value becomes a json field,
which is sent whole when it changes.
Long-lived room objects. A Colyseus room is an object that lives
until it’s disposed, so fields on this are safe. An IRT room
hibernates when it empties and may wake in another room host, so only
entities, room.state, private state and the tick come back. conn.data,
room.data and module variables don’t: see
Where player data lives.
HTTP routes beside rooms. IRT rooms don’t serve HTTP. Express routes that ran in the Colyseus process move to your backend, which reaches rooms through the HTTP API. A game with no routes needs no backend at all; see Games without a backend.
Clients outside TypeScript. @irtio/client runs in browsers and Node.
There are no Unity, Defold or Haxe clients.
Checklist
- Write
schema.ts: eachSchemaclass becomes anentity(...)kind, the root state becomesstate, per-player secrets becomeprivate. Import it from both the room and the client. - Move each
onMessagehandler into the oneonMessagehook, and validate every field: the types in your code are the client’s promise, not the room’s guarantee. - Turn messages that expect a reply message into calls.
- Replace
setSimulationIntervalwithtickRateandonTick, andclocktimers with tick numbers kept inroom.state. A room with no simulation interval leavestickRateout, sends its changes as they happen, and times things with its alarm. - Key players by
conn.player, and inonJoinreuse the entity a player already has; after a crash it’s still there. - Decide what each piece of per-room data is: synced state in entities,
per-player data in private state, a derived cache in
room.datarebuilt inonCreateandonWake. - Replace
joinOrCreate,createandjoinByIdwithquickJoin,createRoom,joinByCodeandconnect, and set the matchingplayers.*settings inirt.config.ts. - Move
onAuthto your backend as signed player tokens, or allow guests. - Write tests with
@irtio/testingfor joining, each message, a dropped connection, a crash (t.host.crash()) and a hibernation (t.hibernate()). The testing guide has a pattern for each. - Run it with
npx irt dev, check rooms in the inspector, thennpx irt deploy.