HookContext
@irtio/room 5.0Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe HookContext interface of the Room API is what every hook gets as its last argument: the Room, the project’s secrets as env, and a signal that aborts when the room hibernates or stops.
Every hook of a room definition takes what happened first, such as the connection that opened or the message that arrived, and a context last. Call handlers, write handlers, bot behaviours, and the functions of interest, voice and seesPresence take one too. A hook with more to say gets a context that extends HookContext, so a hook destructures what it needs, { room } or { room, connection }, and a context can gain fields without breaking it.
Instance properties
HookContext.room- The
Roomthe hook runs in. HookContext.env- The project’s secrets by name, as
irt secrets setstores them, in a frozen object; a secret that isn’t set readsundefined. Underirt dev, it’s the shell’s environment without the names IRT reserves. The same secrets are inprocess.envtoo. HookContext.signal- An
AbortSignalthat aborts once the room has hibernated, afteronHibernate()has run, or has stopped. Pass it to outboundfetchcalls and timers so they end with the room. Each start or wake of the room has a new one.
Contexts that extend it
MessageContext- What
onMessage()gets: alsoconnection,unreliableandviewTick. LeaveContext- What
onLeave()gets: alsoleft. TickContext- What
onTick()and a bot’stickget: alsodt, the fixed timestep in seconds. WriteContext- What a write handler gets: also
connection, the writer, andentity, the entity written. CallContext- What a call handler gets: also
connection, the caller, andviewTick.
Examples
Calling an outside service with a secret
The room reports each finished match to the game’s own backend, with a key set with irt secrets set SCORES_KEY .... The request is cancelled if the room hibernates first.
// report.ts
import { defineRoom } from "@irtio/room";
export default defineRoom({
async onMessage(message, { room, env, signal }) {
if (message !== "finished") return;
await fetch("https://scores.example.com/matches", {
method: "POST",
headers: { authorization: `Bearer ${env.SCORES_KEY}` },
body: JSON.stringify({ room: room.id }),
signal,
});
},
});
Typing a hook kept in its own file
RoomOf gives the room’s type, so a hook written apart from defineRoom() is typed against the schema.
// greet.ts
import { type Connection, defineSchema, entity, type HookContext, type RoomOf } from "@irtio/room";
export const schema = defineSchema({ state: entity("hall", { visits: "u32" }) });
export function greet(connection: Connection, { room }: HookContext<RoomOf<typeof schema>>): void {
room.state.visits += 1;
room.send(connection, { visits: room.state.visits });
}
See also
RoomDefinition- Room API on one page, for what room code can rely on
Runtime availability
| Hosted rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
HookContext | 5.0 | 5.0 | 5.0 | 5.0 |