---
title: Build a chat room
description: A chat room that apps join under a name, with the latest messages as a live query, pushes when people join and leave, and whispers to one person.
related:
  - /realtime/subscribe-to-a-query
  - /realtime/open-a-connection
  - /realtime/push-to-connected-apps
---

At the end of this page you have a chat room that apps join under a name. Each app reads the latest messages as a live query, hears who joins and leaves, and can whisper to one person. The room uses a live query, connection hooks, tags and pushes.

Each room is one `Room` luna, keyed by the room's id. Its messages are rows in its own table, so two rooms never wait for each other.

Start from a project set up as in the [Quickstart](/quickstart), with the TypeScript SDK installed.

## The files

- luna/
  - luna.config.ts
  - lunas/
    - room.ts
- app/
  - chat.ts

## The room

```ts luna/luna.config.ts
import { defineConfig } from "luna";

export default defineConfig({ lunas: "./lunas/room.ts" });
```

```ts luna/lunas/room.ts
import { type Caller, defineLuna, t, table } from "luna";

/** The name `onBeforeConnect` gave the caller's connection. */
function nameOf(caller: Caller): string {
  if ("external" in caller) return (caller.external as { name: string }).name;
  throw new Error("only apps send messages");
}

export const Room = defineLuna({
  name: "Room",
  visibility: "public",
  key: { id: t.string() },
  schema: {
    messages: table({ id: t.id(), name: t.string(), text: t.string(), at: t.timestamp() }),
  },
  pushes: {
    joined: t.object({ name: t.string() }),
    left: t.object({ name: t.string() }),
    whispered: t.object({ from: t.string(), text: t.string() }),
  },
  hooks: {
    onBeforeConnect: (ctx, request) => {
      const name = (request.query.name ?? "").trim();
      if (name.length === 0 || name.length > 40) ctx.fail("BadName");
      return { name };
    },
    onConnect: (ctx, conn) => {
      const { name } = conn.auth as { name: string };
      conn.tag(name);
      ctx.broadcast("joined", { name }, { except: conn });
    },
    onDisconnect: (ctx, conn) => {
      const { name } = conn.auth as { name: string };
      ctx.broadcast("left", { name });
    },
  },
  handlers: (h) => ({
    send: h({ args: { text: t.string({ maxLength: 2000 }) } }, (ctx, { text }) => {
      const id = ctx.db.messages.insert({ name: nameOf(ctx.caller), text, at: Date.now() });
      ctx.db.messages.delete({ where: { id: { lte: id - 500 } } });
    }),
    recent: h({ query: true, shared: true }, (ctx) =>
      ctx.db.messages.find({ orderBy: { id: "desc" }, limit: 50 }).reverse(),
    ),
    whisper: h({ args: { to: t.string({ maxLength: 40 }), text: t.string({ maxLength: 2000 }) } }, (ctx, { to, text }) => {
      ctx.broadcast("whispered", { from: nameOf(ctx.caller), text }, { tags: [to] });
    }),
  }),
});
```

- **`visibility: "public"`** lets apps reach the room with the environment's publishable key.
- **`onBeforeConnect`** runs before each request from outside. It takes the `name` query parameter and returns it as the caller's identity, or refuses the connection with `ctx.fail`. Calls made over the connection carry that identity in `ctx.caller.external`, so a name cannot change after joining.
- **`onConnect`** tags the new connection with the person's name and tells everyone else. `except` leaves out the connection that joined.
- **`onDisconnect`** tells the room that someone left. It runs at least once for each connection the app closes, so an app can hear the same `left` twice.
- **`send`** stores a message under the sender's name and deletes messages more than 500 behind it. If the handler fails, the insert and the delete are undone together. Two sends at once take turns, so message ids follow the order they were stored.
- **`recent`** is a query of the last 50 messages, oldest first. Each `send` changes the table, so the query runs again and every app watching it gets the new list. `shared: true` gives every watcher one run, which fits because the answer never depends on who asks.
- **`whisper`** pushes to the connections tagged with one name. Someone with the room open twice gets it in both.

The room sleeps between calls. It keeps a record of each open connection with its data, with the identity and tags, so a push after it wakes still reaches every app.

## The app

The app is a terminal program. It prints new messages and pushes, and sends each line you type. A line such as `@Bob hello` whispers to Bob.

```ts app/chat.ts
import { createClient } from "luna/client";
import type { Room } from "../luna/lunas/room.ts";

const [roomId = "lobby", name = "Ann"] = process.argv.slice(2);

const client = createClient({
  url: process.env.LUNA_URL!,
  key: process.env.LUNA_KEY!,
  params: () => ({ name }),
});
const room = client.luna<typeof Room>("Room", roomId);

let shown = 0;
const recent = room.query("recent");
recent.subscribe(() => {
  for (const m of recent.get().data ?? []) {
    if (m.id <= shown) continue;
    console.log(`${m.name}: ${m.text}`);
    shown = m.id;
  }
});

room.on<{ name: string }>("joined", (p) => console.log(`* ${p.name} joined`));
room.on<{ name: string }>("left", (p) => console.log(`* ${p.name} left`));
room.on<{ from: string; text: string }>("whispered", (p) => console.log(`(${p.from}) ${p.text}`));

process.stdin.setEncoding("utf8");
process.stdin.on("data", (line: string) => {
  const text = line.trim();
  if (!text) return;
  const whisper = /^@(\S+) (.+)$/.exec(text);
  const call = whisper
    ? room.mutate("whisper", { to: whisper[1], text: whisper[2] })
    : room.mutate("send", { text });
  call.catch((e: Error) => console.error(e.message));
});
```

- **`params`** gives each new connection its query parameters. `onBeforeConnect` reads `name` from them, and the client asks again on every reconnect.
- **`client.luna<typeof Room>`** types the room's handlers and results from the luna's own definition, with no generated code.
- **`room.query("recent")`** is the live query. `subscribe` hears each new result, and `get()` returns the latest.
- **`room.on`** hears a push by name. `room.mutate` calls a handler.

## Run it

Run `luna dev` in one terminal. It deploys the room and writes `LUNA_URL` and `LUNA_KEY` to `.env.local`.

```bash
luna dev
```

In two more terminals, join the same room under two names.

```bash
node --env-file=.env.local app/chat.ts lobby Ann
```

```bash
node --env-file=.env.local app/chat.ts lobby Bob
```

Type a line in either terminal to send it. Each terminal prints the message once the query runs again.

## Next steps

- [Subscribe to a query](/realtime/subscribe-to-a-query) explains what makes a live query run again.
- [Open a connection](/realtime/open-a-connection) covers the connection hooks, tags and state.
- [Push to connected apps](/realtime/push-to-connected-apps) covers `conn.push` and `ctx.broadcast`.
