RoomMessageEvent: data property

Available since @irtio/client 5.0BrowsersNode

The data read-only property of the RoomMessageEvent interface is the message the room sent.

Value

One of the following:

Uint8Array
A binary message, which the room sent as a Uint8Array.
Any other value
A JSON message, parsed. Its type is unknown, since the room’s messages aren’t declared in the schema.

Description

The room’s room.send() and room.broadcast() send a Uint8Array as a binary message and any other value as JSON, so data has the shape the room sent, after a round trip through JSON. A message is at most 64 KB.

For a request that needs a typed reply, use a call instead; see Calls.

Examples

Narrowing a message by its type

The room sends each message with a type. A type guard checks the shape before the game uses it.

// goal.ts
import { connect } from "@irtio/client";

interface Goal {
  type: "goal";
  team: "red" | "blue";
  scorer: string;
}

function isGoal(data: unknown): data is Goal {
  return typeof data === "object" && data !== null && (data as { type?: unknown }).type === "goal";
}

const room = await connect("https://rooms.irt.io/my-game/final");
room.addEventListener("message", ({ data }) => {
  if (isGoal(data)) console.log(`${data.scorer} scores for ${data.team}`);
});

See also

Runtime availability

BrowsersNode
data5.05.0