# Direct messages and group rooms

URL: https://docs.folkways.io/docs/js-sdk/direct-messages

Open a DM or a small group room from your backend with POST /v1/dm/open; the node creates the room and invites every member.

Your backend opens a room for a set of users with one request. The node works out the room's topic, adds the users
to its member list when the rule is members-only, and posts an
`invite` to each member's [personal topic](/docs/js-sdk/personal-topics). Each member's app hears the invite and
subscribes to the room.

```text
 Bob's app          Your backend                       Folkways node                    Alice's app
    │ "message Alice"    │                                  │                                 │
    │ ─────────────────► │  POST /v1/dm/open                │                                 │
    │                    │  { members: [bob, alice] }       │                                 │
    │                    │ ───────────────────────────────► │ adds both to the member list    │
    │                    │                                  │ invite → $user/user:alice ────► │
    │ ◄── { topic } ──── │ ◄──── { topic: "dm/5f0c…" } ──── │ invite → $user/user:bob         │
    │                                                       │      ◄── subscribe dm/5f0c… ─── │
```

## Before you start [#before-you-start]

- **A topic rule for the rooms.** Rooms are named `{prefix}/{id}`, with prefix `dm` unless you choose another, so
  add a rule with pattern `dm/*` and type Stream on the segment's **Topic rules** tab. Set **Who may use it** to
  **Members only** so the node keeps each room's member list for you (below).
- **A service token** for your backend with `publish` on the rooms and on the members' personal topics:

```ts
const { token } = await rte.createToken({
  identity: 'backend',
  kind: 'service',
  capabilities: [
    { topics: 'dm/*', ops: ['publish'] },
    { topics: '$user/>', ops: ['publish'] },
  ],
});
```

## Open a room [#open-a-room]

```http
POST /v1/dm/open
Authorization: Bearer <service token>
Content-Type: application/json

{ "members": ["user:1", "user:2"], "data": { "startedBy": "user:1" } }
```

| Field | Default | Meaning |
| --- | --- | --- |
| `members` | required | 2 to 50 different identities. Each must be one topic level: no `/` |
| `prefix` | `"dm"` | The topic the room goes under, e.g. `"support"` for `support/{id}`. A rule must match the room |
| `data` | `null` | Any JSON, passed on in every invite |

The answer:

```json
{
  "topic": "dm/5f0c8e1d2a9b44c7e1f03a6d",
  "members": ["user:1", "user:2"],
  "invites": [
    { "identity": "user:1", "topic": "$user/user:1", "duplicate": false },
    { "identity": "user:2", "topic": "$user/user:2", "duplicate": false }
  ]
}
```

- **One room per set of members.** The same members always get the same `topic` in a segment, in any order, so
  "open" is also "find". The name is not a secret: it doesn't grant anything by itself.
- **Invites are sent once.** Opening the same room with the same `data` again within 10 minutes sends nobody a
  second invite, and those entries come back `duplicate: true`. If a request fails part-way, send it again: members
  who already have their invite are skipped.
- **All or nothing on rights.** If the token lacks `publish` on the room or on any member's personal topic, the
  answer is `403 Forbidden` and nobody is invited.

The full list of answers and errors is in the [REST reference](/docs/js-sdk/reference/rest#post-v1dmopen).

## Give members access [#give-members-access]

Being invited grants nothing by itself. How members get into the room depends on the `dm/*` rule:

- **Members only (recommended).** `/v1/dm/open` puts the members on the room's [member list](/docs/js-sdk/private-topics)
  before it sends any invite. Every user's token needs only the same ceiling,
  `{ topics: 'dm/*', ops: ['subscribe', 'publish'] }`, and someone who isn't a member is refused, whatever their
  token says. Opening the room again keeps existing entries, so it never undoes a block you set with
  `/v1/members/set`. Remove someone from a room with `/v1/members/remove`.
- **Token access.** Each member's token must list the room itself, e.g.
  `{ topics: 'dm/5f0c8e1d2a9b44c7e1f03a6d', ops: ['subscribe', 'publish'] }`. Keep each user's rooms in your
  database and put them in the token; when an invite arrives the app calls `client.updateToken()` to get a token
  with the new room. Don't grant `dm/*` with token access: anyone could then read every DM.

An invite is an `invite` event on `$user/{identity}`, published by your backend's identity, with:

```json
{ "type": "dm", "topic": "dm/5f0c8e1d2a9b44c7e1f03a6d", "members": ["user:1", "user:2"], "data": { "startedBy": "user:1" } }
```

## Full example [#full-example]

The backend opens a DM between Bob and Alice; Alice's app hears the invite, joins the room and says hi. Run it with
Node.js 22 or later and the same variables as [Issue tokens from your backend](/docs/js-sdk/server-tokens), on a
segment with a **Members only** rule for `dm/*`.

```js title="dm.mjs"
import { Folkways } from '@folkwaysio/realtime';
import { Folkways as Server } from '@folkwaysio/realtime/server';

const url = process.env.RTE_URL;
const rte = new Server.Rest({
  url,
  segment: process.env.RTE_SEGMENT_ID,
  signingKey: { kid: process.env.RTE_KEY_ID, privateKey: process.env.RTE_PRIVATE_KEY },
});

// ---- backend ----

// The token endpoint: every user gets the same ceiling. The rooms' member lists decide which DMs they can use.
const tokenFor = (identity) => async () =>
  (await rte.createToken({ identity, capabilities: [{ topics: 'dm/*', ops: ['subscribe', 'publish'] }] })).token;

// Open (or find) the DM room for some users. The node adds them to its member list and invites each one.
async function openDm(members, data) {
  const { token } = await rte.createToken({
    identity: 'backend',
    kind: 'service',
    capabilities: [
      { topics: 'dm/*', ops: ['publish'] },
      { topics: '$user/>', ops: ['publish'] },
    ],
    ttlMs: 60_000,
  });
  const res = await fetch(`${url}/v1/dm/open`, {
    method: 'POST',
    headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
    body: JSON.stringify({ members, data }),
  });
  const body = await res.json();
  if (!res.ok) throw new Error(`dm/open: HTTP ${res.status} ${body.error}: ${body.message}`);
  return body;
}

// ---- Alice's app ----

const alice = await Folkways.connect({ url, token: tokenFor('user:alice') });

// The SDK follows $user/{identity} on its own; listen for invites on it.
alice.on({ topic: `$user/${alice.session.identity}`, event: 'invite' }, async (invite) => {
  const { topic, members, data } = invite.data;
  console.log('alice got an invite to', topic, 'with', members.join(' and '), data);
  const room = alice.topic(topic);
  const sub = room.subscribe((msg) => console.log(`${topic} ${msg.publisher}: ${msg.data.text}`));
  await sub.ready;
  await room.publish('message', { text: 'hi Bob' });
});

// ---- the backend opens the DM, e.g. when Bob taps "Message Alice" ----

const opened = await openDm(['user:bob', 'user:alice'], { startedBy: 'user:bob' });
console.log('backend opened', JSON.stringify(opened));

await new Promise((r) => setTimeout(r, 1500));
await alice.close();
```

It prints something like this (the room id differs per segment, and the invite can arrive before the backend's
call returns):

```text
backend opened {"topic":"dm/d99096e1d30ee2d5f054a0b0","members":["user:alice","user:bob"],"invites":[…]}
alice got an invite to dm/d99096e1d30ee2d5f054a0b0 with user:alice and user:bob { startedBy: 'user:bob' }
dm/d99096e1d30ee2d5f054a0b0 user:alice: hi Bob
```

Run it twice within 10 minutes and the invites come back `duplicate: true`, so Alice gets no new invite.

## Limits [#limits]

- **Rate.** Each request takes one unit per member from the segment's service budget, which refills at the
  segment's per-connection publish rate and holds 64. Over it, the answer is `429 RateLimited` with
  `retry_after_ms` and a `Retry-After` header, and nothing was sent.
- **Quota.** Each new invite counts as a message. A request that wouldn't fit the plan, the segment's monthly cap
  or the [personal topic limit](/docs/js-sdk/personal-topics#the-plan-limit) is refused whole with
  `429 QuotaExceeded`.
- **Members-only rooms** need the member list to be stored before any invite goes out. If it can't be, the answer is
  `503 Unavailable`, nobody is invited, and the request can be sent again.
- The endpoint is for backends only: it has no CORS, and browsers must never hold service tokens.
