# Presence and online status

URL: https://docs.folkways.io/docs/js-sdk/presence

See who is online across your app and who is in each topic, on every device, from topics the node keeps for you.

The node knows every connection that opens and closes, so it keeps presence for you. You read it like any other
KV topic: subscribe, then read `topic.values()`. Nobody publishes "I'm here" messages, entries can't be faked, and
they disappear the moment a connection closes.

| Topic | What it holds | Needs |
| --- | --- | --- |
| `$online/{identity}` | One entry per live connection of that user, anywhere in the segment. **Empty means offline** | Nothing to set up |
| `$presence/{topic}` | One entry per connection subscribed to `{topic}` or to any topic under it | The topic rule's presence setting (below) |

Both are KV topics written only by the node. Presence entries and their deliveries are not billed as messages.

## What an entry holds [#what-an-entry-holds]

Every entry is a [`Message`](/docs/js-sdk/reference/topics#message) whose `publisher` is the user (checked by the
node) and whose `data` is:

```json
{ "identity": "user:alice", "session": "9f1c…e2", "device": "ios", "since": 1792000000000, "data": { "status": "busy" } }
```

| Field | Meaning |
| --- | --- |
| `identity` | Who is connected |
| `session` | The connection's session id (32 hex digits), the same as `client.session.id` on that device |
| `device` | The client's `device` option, or `null` |
| `since` | When the connection opened, Unix ms |
| `data` | What the user wrote to their own `$online` entry (below), or `null` |

Entries in `$online/{identity}` are keyed by session id; entries in `$presence/{topic}` by `identity#session`. When
a connection closes, its entries arrive as removals (`deleted: true`) with the same key.

## One user, several devices [#one-user-several-devices]

A user signed in on a phone and a laptop has two connections, so two entries. Count entries per identity to show
"Alice (2 devices)", or one avatar per person:

```ts
const online = client.topic('$online/user:alice');
online.subscribe();

const devices = () => [...online.values().values()].filter((e) => !e.deleted).length; // 0 = offline
```

A user's own `$online/{identity}` needs no permission, so an app can always show "you are connected on 3 devices".

## Who is in a topic [#who-is-in-a-topic]

Subscribing to a topic whose rule has presence turned on makes the connection present in that topic **and in every
level above it**: a subscription to `chat/42/typing` shows in `$presence/chat/42/typing`, `$presence/chat/42` and
`$presence/chat`. Unsubscribing or disconnecting removes it at once. Several subscriptions under one level make one
entry there.

<Callout title="Turning presence on for a topic rule">
  `$presence/{topic}` is kept only for topics whose rule has **Keep presence** switched on, on the segment's
  **Topic rules** tab. For other topics it stays empty. `$online/{identity}` needs no setting and works on every
  segment.
</Callout>

## Set your status [#set-your-status]

A connection can attach up to 1,024 bytes of JSON to its own entry, such as a status or a display name. Publish a
KV event to **your own** `$online/{identity}`, keyed by your session id:

```ts
const me = client.session!;
await client.topic(`$online/${me.identity}`).publish('status', { status: 'busy' }, { delivery: 'kv', key: me.id });
```

The value shows as `data` in that connection's `$online` entry and in each of its `$presence` entries. Clear it
with `{ delivery: 'kv', key: me.id, remove: true }`: the entry stays while the connection is open, with `data: null`. Writing without `key: me.id`, writing someone else's entry, or
writing to `$presence/…` is refused with `Forbidden`; data that isn't JSON with `InvalidArgument`.

## Permissions [#permissions]

Reading other people's presence needs the `presence` operation in the token:

```ts
capabilities: [
  { topics: 'chat/>', ops: ['subscribe', 'presence'] }, // who is in each chat topic: $presence/chat/…
  { topics: '$online/>', ops: ['presence'] },            // a friends list: anyone's online status
]
```

`presence` on `chat/>` covers `$presence/chat` and everything under it. Without the right, the subscription fails
with `Forbidden`, the same answer whether or not the user exists or is online. There is no "where is user X"
query.

## Staying out of presence [#staying-out-of-presence]

Anonymous connections and HTTP requests never show in presence. To keep a signed-in connection out too (a support
agent's console, a backend worker), add `"presence": false` to its token's claims. `rte.createToken()` has no
option for it yet, so sign that token with your own JWT library (see
[What a token contains](/docs/js-sdk/authentication#what-a-token-contains)). The connection still subscribes and
publishes normally.

## Full example [#full-example]

Alice connects from two devices and sets a status; Bob sees her in `chat/lobby` and online. Run it with Node.js 22
or later (on Node.js 20, pass `webSocket` from the `ws` package) and the same variables as
[Issue tokens from your backend](/docs/js-sdk/server-tokens). The `chat/>` rule needs **Keep presence** on for the
room part; the online part works on any segment.

```js title="presence.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 },
});

// In your app, these tokens come from your token endpoint.
const tokenFor = (identity, capabilities) => async () => (await rte.createToken({ identity, capabilities })).token;
const member = [{ topics: 'chat/>', ops: ['subscribe', 'publish'] }];
const watcher = [
  { topics: 'chat/>', ops: ['subscribe', 'presence'] }, // who is in each chat room
  { topics: '$online/>', ops: ['presence'] },            // who is online, segment-wide
];

// Alice, on her phone and her laptop.
const phone = await Folkways.connect({ url, device: 'ios', token: tokenFor('user:alice', member) });
const laptop = await Folkways.connect({ url, device: 'web', token: tokenFor('user:alice', member) });
phone.topic('chat/lobby').subscribe();
laptop.topic('chat/lobby').subscribe();

// Alice sets a status on her phone's entry.
const me = phone.session;
await phone.topic(`$online/${me.identity}`).publish('status', { status: 'busy' }, { delivery: 'kv', key: me.id });

// Bob reads presence.
const bob = await Folkways.connect({ url, token: tokenFor('user:bob', watcher) });
const room = bob.topic('$presence/chat/lobby');
const alice = bob.topic('$online/user:alice');
room.subscribe({ from: 'oldest' });
alice.subscribe({ from: 'oldest' });

const show = () => {
  const people = new Map(); // identity -> connections in the room
  for (const entry of room.values().values()) {
    if (entry.deleted) continue;
    people.set(entry.data.identity, (people.get(entry.data.identity) ?? 0) + 1);
  }
  const devices = [...alice.values().values()].filter((e) => !e.deleted).map((e) => `${e.data.device}:${JSON.stringify(e.data.data)}`);
  console.log('in chat/lobby:', Object.fromEntries(people), '| alice online on', devices.length, 'device(s):', devices.join(', ') || '-');
};
room.values().subscribe(show);
alice.values().subscribe(show);

await new Promise((r) => setTimeout(r, 1000));
console.log('-- laptop closes');
await laptop.close();
await new Promise((r) => setTimeout(r, 1000));
console.log('-- phone closes');
await phone.close();
await new Promise((r) => setTimeout(r, 1000));
await bob.close();
```

It prints, among the updates:

```text
in chat/lobby: { 'user:alice': 2 } | alice online on 2 device(s): web:null, ios:{"status":"busy"}
-- laptop closes
in chat/lobby: { 'user:alice': 1 } | alice online on 1 device(s): ios:{"status":"busy"}
-- phone closes
in chat/lobby: {} | alice online on 0 device(s): -
```

In React, read the same views with `useSyncExternalStore`, as the
[React example](https://github.com/Folkways/folkways-js/tree/main/apps/react-example) does for its "Who's here" list
and "Your connections" count. See [Using it with React](/docs/js-sdk/react).

## Good to know [#good-to-know]

- **Online is segment-wide.** A user is online while they have at least one connection anywhere in the segment.
  A connection that drops without closing cleanly is removed when the node notices: at once when the socket
  closes, and at the idle timeout (90 seconds) at worst.
- **A user whose identity contains `/`** (or a character outside the topic name characters) never shows in
  presence and has no `$online` topic.
- **Private topics** (rules set to **Members only**) don't show presence to client tokens: `$presence/{topic}` is
  closed to them wherever a members-only rule could match, so it never reveals who is in a private room. Service
  tokens can still read it. See [Private topics](/docs/js-sdk/private-topics).
