# Personal topics

URL: https://docs.folkways.io/docs/js-sdk/personal-topics

Every signed-in user has a topic of their own, $user/{identity}, where your backend can reach them with invites and notices.

Every signed-in user has a personal topic, `$user/{identity}`, for example `$user/user:42`. Your backend posts to
it; only that user reads it. Use it as a **doorbell**: "you were invited to a chat", "your order shipped", "open
this room". [Direct messages](/docs/js-sdk/direct-messages) use it to deliver their invites.

| | Who |
| --- | --- |
| Reads `$user/{identity}` | The user with that identity, with no permission needed. Also service tokens with `subscribe` on it |
| Writes to it | Only connections with a **service** token (`kind: 'service'`) and `publish` on it, e.g. on `$user/>` |
| Can never write to it | Users, whatever their token says |

Personal topics need no topic rule. They are Stream topics, and their messages count like any other messages.

## Receive in the app [#receive-in-the-app]

The SDK subscribes to the user's own `$user/{identity}` as soon as it connects, when the node offers personal
topics (`session.features` includes `user-topics`). Listen with `client.on()`:

```ts
client.on({ topic: `$user/${client.session!.identity}` }, (msg) => {
  if (msg.name === 'notice') showToast(msg.data.text);
  if (msg.name === 'invite') joinRoom(msg.data.topic);
});
```

That subscription starts at the newest event, so it sees what arrives while the app is connected. To also get what
was sent while the user was offline, subscribe yourself **before** `connect()`, from the oldest event kept:

```ts
const client = new Folkways.Realtime({ url, authUrl: '/api/realtime-token' });
// The identity your token endpoint signs for this user, e.g. user:42.
client.topic(`$user/user:${currentUser.id}`).subscribe(handleNotice, { from: 'oldest' });
await client.connect();
```

A personal topic keeps **at most 256 KiB per user, for at most 24 hours**. A user who was away longer, or who was
sent more than that meanwhile, misses the oldest events and gets a [`gap`](/docs/js-sdk/subscribing). So keep the
real list of a user's rooms and notifications in your own database, and use `$user` to say "something changed".

## Send from your backend [#send-from-your-backend]

Write to a personal topic from a connection that uses a **service** token with `publish` on `$user/>`:

```ts
import { Folkways } from '@folkwaysio/realtime';
import { Folkways as Server } from '@folkwaysio/realtime/server';

const rte = new Server.Rest({ url, segment, signingKey });

const notifier = await Folkways.connect({
  url,
  token: async () =>
    (await rte.createToken({ identity: 'backend', kind: 'service', capabilities: [{ topics: '$user/>', ops: ['publish'] }] })).token,
});

await notifier.topic('$user/user:42').publish('notice', { text: 'Your order shipped' });
```

<Callout type="warn" title="rte.publish() doesn't take $ topics yet">
  `rte.publish('$user/…')` throws `InvalidTopic` in the SDK before anything is sent. Until it accepts personal
  topics, publish from a client connection with a service token, as above (Node.js 22 or later, or pass `webSocket`
  from the `ws` package on Node.js 20). Keep that connection open and reuse it.
</Callout>

## The plan limit [#the-plan-limit]

A segment can have a limited number of personal topics **active at once**: by default twice the segment's
connection limit, and at least 1,000. A personal topic is active while someone reads it or it still holds events;
one nobody reads and that holds nothing is released after about a minute. When the limit is reached, subscribing to
one more personal topic, or opening a DM that needs one more, fails with `QuotaExceeded`.

## Full example [#full-example]

The backend sends Carol a notice while she is offline; when her app starts, it reads it. Run it with Node.js 22 or
later and the same variables as [Issue tokens from your backend](/docs/js-sdk/server-tokens).

```js title="personal-topic.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: a service connection that may write to every personal topic.
const notifier = await Folkways.connect({
  url,
  token: async () =>
    (await rte.createToken({ identity: 'backend', kind: 'service', capabilities: [{ topics: '$user/>', ops: ['publish'] }] })).token,
});
await notifier.topic('$user/user:carol').publish('notice', { text: 'Your order shipped' });

// Carol's app starts later. Her token needs no rights for her own personal topic.
const carol = new Folkways.Realtime({ url, token: async () => (await rte.createToken({ identity: 'user:carol' })).token });
const sub = carol.topic('$user/user:carol').subscribe(
  (msg) => console.log(`${msg.name} from ${msg.publisher}:`, msg.data),
  { from: 'oldest' },
);
await carol.connect();
await sub.ready;

// Carol can't write to her own personal topic, or read anyone else's.
await carol.topic('$user/user:carol').publish('notice', { text: 'hi' }).catch((e) => console.log('write:', e.codeName));
carol.topic('$user/user:dave').subscribe().on('error', (e) => console.log('read other:', e.codeName));

await new Promise((r) => setTimeout(r, 500));
await Promise.all([carol.close(), notifier.close()]);
```

```text
notice from backend: { text: 'Your order shipped' }
write: Forbidden
read other: Forbidden
```
