Build authoritative real-time multiplayer servers with Colyseus 0.17+. Use when implementing rooms, schema state sync, client message validation, matchmaking, authentication, reconnection handling, or server-side anti-cheat constraints. Keywords: colyseus, room lifecycle, schema, multiplayer, websocket, matchmaking, onJoin, onLeave, onDrop, allowReconnection.
90%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Passed
No findings from the security scan
onCreate, onJoin, onLeave, onDrop).onCreate, onJoin, onLeave, onDrop).allowReconnection restores session — verify the player is not ejected prematurely.npm create colyseus-app@latest serverExpected result: runnable Colyseus project in server/.
cd server && bun install && bun run src/index.tsExpected result: server listening on configured port.
cd server && npm install && npm run startExpected result: room handlers and matchmaker initialized.
pantheon-skill-auditor evaluate specialized/colyseus-multiplayer --jsonExpected result: updated dimension score breakdown.
rumdl check specialized/colyseus-multiplayerExpected result: no rumdl violations.
The following shows lifecycle hooks, Schema state, and reconnection handling together:
import { Room, Client } from "@colyseus/core";
import { Schema, type, MapSchema } from "@colyseus/schema";
class Player extends Schema {
@type("string") sessionId: string = "";
@type("number") x: number = 0;
@type("number") score: number = 0;
}
class GameState extends Schema {
@type({ map: Player }) players = new MapSchema<Player>();
}
export class GameRoom extends Room<GameState> {
maxClients = 4;
onCreate(options: any) {
this.setState(new GameState());
this.onMessage("move", (client, payload: { dx: number; dy: number }) => {
const player = this.state.players.get(client.sessionId);
if (!player) return;
// Server-side validation: cap movement delta
const dx = Math.max(-5, Math.min(5, payload.dx));
const dy = Math.max(-5, Math.min(5, payload.dy));
player.x += dx;
player.y += dy;
});
}
onJoin(client: Client, options: any) {
const player = new Player();
player.sessionId = client.sessionId;
this.state.players.set(client.sessionId, player);
}
async onLeave(client: Client, consented: boolean) {
if (!consented) {
// Hold the slot for up to 20 seconds on transient disconnect
const reconnection = await this.allowReconnection(client, 20);
if (!reconnection) {
this.state.players.delete(client.sessionId);
}
} else {
this.state.players.delete(client.sessionId);
}
}
onDispose() {
console.log("Room disposed");
}
}WHY: Clients are untrusted and can be modified for cheating.
BAD: Apply payload.x and payload.score without server checks.
GOOD: Validate movement delta and compute score on server.
// BAD
this.onMessage("move", (client, payload) => {
player.x = payload.x;
player.score = payload.score;
});
// GOOD
this.onMessage("move", (client, payload: { dx: number }) => {
const player = this.state.players.get(client.sessionId);
if (!player) return;
const dx = Math.max(-5, Math.min(5, payload.dx)); // clamp server-side
player.x += dx;
// score computed exclusively by server logic, never from client
});Consequence: Competitive integrity is lost and leaderboard data is corrupted.
WHY: Only Schema-decorated fields are synchronized to clients.
BAD: Store gameplay-critical values in plain class properties.
GOOD: Keep synchronized values in Schema fields and collections.
// BAD
class Player extends Schema {
hp: number = 100; // plain property — not synced
}
// GOOD
class Player extends Schema {
@type("number") hp: number = 100; // decorated — synced automatically
}Consequence: Clients desync and render stale or inconsistent state.
WHY: Mobile and unstable networks frequently drop short-lived connections.
BAD: Remove player immediately in onLeave for all disconnects.
GOOD: Use allowReconnection with a bounded timeout, falling back to removal only on expiry.
// BAD
async onLeave(client: Client, consented: boolean) {
this.state.players.delete(client.sessionId);
}
// GOOD
async onLeave(client: Client, consented: boolean) {
if (!consented) {
const reconnection = await this.allowReconnection(client, 20);
if (!reconnection) {
this.state.players.delete(client.sessionId);
}
} else {
this.state.players.delete(client.sessionId);
}
}Consequence: Players are ejected from active matches unnecessarily.
WHY: Admin or host-only actions must be authorization-gated.
BAD: Let any client trigger startMatch or kickPlayer.
GOOD: Verify role/ownership before privileged actions.
// BAD
this.onMessage("startMatch", (client) => {
this.startMatch();
});
// GOOD
this.onMessage("startMatch", (client) => {
if (client.sessionId !== this.hostSessionId) return; // guard
this.startMatch();
});Consequence: Match flow can be hijacked by unauthorized clients.
WHY: Malformed or hostile payloads can crash the handler or corrupt shared state.
BAD: Read payload.dx without checking its shape.
GOOD: Parse the payload with a schema validator and return early when it fails.
const parsed = moveSchema.safeParse(payload);
if (!parsed.success) return;Consequence: One bad message can break the room for every player.
WHY: Absolute positions let a modified client teleport; deltas can be clamped and range-checked on the server.
BAD: player.x = payload.x.
GOOD: Accept a delta, clamp it server-side and apply it to the stored position.
Consequence: Players can move anywhere instantly and bypass level geometry.
WHY: Metadata drives room discovery, so values that do not reflect the room's real mode and capacity send players to the wrong rooms.
BAD: this.setMetadata({ mode: "ranked" }) regardless of the options the room was created with.
GOOD: Derive mode, region or skill values from the creation options in onCreate and keep them consistent with runtime state.
Consequence: Players are matched into rooms that do not match their request.
WHY: Unthrottled message types allow one client to flood the room and starve other players.
BAD: Process every move message the moment it arrives.
GOOD: Enforce a cooldown or per-client message budget on spam-prone message types.
Consequence: A single client can degrade latency for the whole room.
WHY: Seats held too long block other players, and a window too short for the mode ejects players unfairly.
BAD: Hold a ranked slot for minutes, or pass no timeout to allowReconnection.
GOOD: Use a bounded grace period for the mode: 20-30 seconds casual, 10-15 seconds ranked, strict for tournaments.
Consequence: Rooms stay half empty, or players lose matches to brief network drops.
| Topic | Reference | When to Use |
|---|---|---|
| Room lifecycle and state | references/room-lifecycle-and-state.md | Schema setup, lifecycle hook order, state synchronisation |
| Message validation and security | references/message-validation-and-security.md | Server-side payload validation and anti-cheat patterns |
| Matchmaking and reconnection | references/matchmaking-and-reconnection.md | allowReconnection, metadata filters and timeout policy |
pantheon-org/tekhne
c8416e9
Also appears in
last in sync Aug 28, 2026
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.