Deny a Player Joining a Room
You can deny a player connection by throwing a ServerError during the onAuth() or onJoin() methods.
When to deny a player connection will depend on your use-case.
Below you can see an example validating the client’s auth token, and retrieving a Hero record linked with the user id. The check lives in the static onAuth. For token-bearing clients, the instance onAuth is skipped entirely (see Room Authentication).
BattleRoom.ts
import { Room, ServerError } from "colyseus";
import { JWT } from "@colyseus/auth";
import { Hero } from "../models/Hero"; // your own database model
const LEVEL_REQUIRED = 10;
export class BattleRoom extends Room {
static async onAuth(token, options, context) {
const userId = (await JWT.verify(token))._id;
const hero = await Hero.findOne({ userId });
if (!hero) {
throw new ServerError(400, "'Hero' not found in the database!");
} else if (hero.level < LEVEL_REQUIRED) {
throw new ServerError(400, "Player does not have the level required for this room.");
}
// becomes `client.auth` / the 3rd argument of onJoin()
return hero;
}
}The client sends its token and receives the error when trying to join the room:
client.js
client.auth.token = "YOUR AUTH TOKEN";
client.joinOrCreate("battle", {}).then(room => {
// ...
}).catch(e => {
console.log(e.message) // "'Hero' not found in the database!"
})A room-specific gate that needs the room instance (the current phase, connected clients) belongs in onJoin() instead. Throwing a ServerError there rejects the join as well. See Room Authentication for the full onAuth semantics.