# RoomDefinition: onMessage() hook

> The onMessage() hook of a room definition runs for each message a connection sends.

The **`onMessage()`** hook of a [room definition](/docs/room/room-definition) runs for each message a connection sends.

## Syntax

```ts
defineRoom({
  onMessage(room, connection, message, info) {},
});
```

### Parameters

`room`
: The [`Room`](/docs/room/room).

`connection`
: The [`Connection`](/docs/room/connection) that sent the message.

`message`
: The message, typed `unknown`: a `Uint8Array` for a binary message, else the decoded JSON. It comes from the client, so check it before trusting it.

`info`
: An object with this property:

  `unreliable`
  : `true` when the client sent the message unreliably.

### Return value

None, or a `Promise`, which the room doesn't wait for.

### Exceptions

If `onMessage` throws, or its promise rejects, the error is logged with the room, player and tick, and the message is dropped. The room keeps running.

## Description

A message is handled as it arrives, between ticks. In a room with ticks, what `onMessage` changes goes out with the next tick's state update; in a room without ticks, once the code yields.

The connection's owner writes that came before the message are applied first, through [`writes`](/docs/room/room-definition/writes), so `onMessage` sees what the player wrote. A reliable message always comes after the writes the client made before it; an unreliable one can overtake them.

A client may send at most 120 messages a second; past that the router closes it with close code 4005. For a request that needs a reply, use a call instead; see [`calls`](/docs/room/room-definition/calls).

## Examples

### A chat line

```ts
// chat.ts
import { defineRoom } from "@irtio/room";

export default defineRoom({
  onMessage(room, connection, message) {
    const m = message as { type?: string; text?: unknown };
    if (m.type !== "chat" || typeof m.text !== "string") return;
    room.broadcast({ type: "chat", from: connection.player, text: m.text.slice(0, 200) });
  },
});
```

## See also

- [`Room.send()`](/docs/room/room/send)
- [`Room.broadcast()`](/docs/room/room/broadcast)
- [Calls](/docs/room/guides/calls)
