# RoomDefinition: onRequest() hook

> The onRequest() hook of a room definition answers a message sent to the room through the server API.

The **`onRequest()`** hook of a [room definition](/docs/room/room-definition) answers a message your backend sends to the room through the server API, with `POST /projects/{p}/rooms/{id}/messages`.

## Syntax

```ts
defineRoom({
  onRequest(room, message) {},
});
```

### Parameters

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

`message`
: The `message` of the API call's body, typed `unknown`.

### Return value

The reply, or a `Promise` of it. The API call answers with it as JSON once the promise resolves. A return value of `undefined` replies `null`.

### Exceptions

If `onRequest` throws, or its promise rejects, the API call answers `422 room_error`:

- For a `CallRejected`, an expected refusal, the message is `onRequest rejected: ` and the error's message, and the room doesn't log it.
- For any other error, the message is `onRequest threw: ` and the error's message, and the room logs it.

The room keeps running either way.

## Description

The message comes from your backend with its API key, not from a player, so `onRequest` is where a backend grants an item, ends a match or reads something only the room knows. A message wakes a hibernated room.

`onRequest` runs between ticks, as the message arrives. In it, `room.tick` is the number of the last tick run. What it changes is room state as usual. A room that calls `room.requestHibernate()` from `onRequest` still sends its reply, and what `onRequest` wrote is in the room state it saves.

A room without `onRequest` answers every server API message with `422 room_error`.

## Examples

### Granting an item from a backend

`room.private()` with a player ID works whether or not the player is connected, so a purchase made on the web reaches the player's inventory.

```ts
// grants.ts
import { CallRejected, defineRoom, defineSchema, entity } from "@irtio/room";

const Inventory = entity("inventory", { lanterns: "u16" });

export default defineRoom({
  schema: defineSchema({ private: Inventory }),
  onRequest(room, message) {
    const m = message as { type?: string; player?: unknown };
    if (m.type !== "grant" || typeof m.player !== "string") throw new CallRejected("unknown request");
    const inventory = room.private(m.player, { create: true });
    inventory.lanterns += 1;
    return { lanterns: inventory.lanterns };
  },
});
```

## See also

- [Server API](/docs/http)
- [`calls`](/docs/room/room-definition/calls), for requests from players
