HookContext

Available since @irtio/room 5.0Hosted roomsirt dev@irtio/testingSelf-hosted room host

The 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 Room the hook runs in.
HookContext.env
The project’s secrets by name, as irt secrets set stores them, in a frozen object; a secret that isn’t set reads undefined. Under irt dev, it’s the shell’s environment without the names IRT reserves. The same secrets are in process.env too.
HookContext.signal
An AbortSignal that aborts once the room has hibernated, after onHibernate() has run, or has stopped. Pass it to outbound fetch calls 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: also connection, unreliable and viewTick.
LeaveContext
What onLeave() gets: also left.
TickContext
What onTick() and a bot’s tick get: also dt, the fixed timestep in seconds.
WriteContext
What a write handler gets: also connection, the writer, and entity, the entity written.
CallContext
What a call handler gets: also connection, the caller, and viewTick.

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

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
HookContext5.05.05.05.0