# Topics and typed events

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

Topic handles, sets of topics, event maps for TypeScript, and defineTopic to share one definition and export it as a topic rule.

## Topic handles [#topic-handles]

`client.topic(name)` returns a handle for one topic. It is a lightweight address: creating one costs nothing and
keeps no data, so make one wherever you need it. Compare handles by `name`, not by identity.

```ts
const room = client.topic('rooms/42');
room.subscribe((msg) => render(msg));
await room.publish('message', { text: 'hi' });
```

The SDK checks the name's syntax and throws `InvalidTopic` for a bad one. Whether the topic may be used is decided by
the service, from the topic rule and the token; see [Topics](/docs/concepts/topics).

## Many topics at once [#many-topics-at-once]

Pass an array to get a **topic set**: one handle that subscribes to, and publishes to, every topic in it.

```ts
const inbox = client.topic(['rooms/1', 'rooms/2', 'rooms/3']);
const sub = inbox.subscribe((msg) => notify(msg.topic, msg), { types: ['stream'] });
const { ok, failed } = await sub.ready; // which topics subscribed, and which failed with what
inbox.add('rooms/4');
inbox.remove('rooms/1');
```

One topic failing doesn't end the others. Subscriptions are always to concrete topics: there are no wildcard
subscriptions.

## Event maps [#event-maps]

Give `client.topic()` a map from event names to data types. TypeScript then checks what you publish and narrows
`msg.data` by `msg.name`:

```ts
type ChatEvents = {
  message: { text: string };
  edited: { uid: string; text: string };
};

const room = client.topic<ChatEvents>('chat/lobby');

await room.publish('message', { text: 'hi' }); // ✓
// room.publish('message', { body: 'hi' });     // ✗ type error

room.subscribe((msg) => {
  if (msg.name === 'message') addMessage(msg.data.text);
  if (msg.name === 'edited') editMessage(msg.data.uid, msg.data.text);
});
```

Types aren't sent anywhere; they only help your code. Validate what you receive at run time too; see
[Schemas](/docs/realtime-api/payloads/schemas).

## Define topics and export rules [#define-topics-and-export-rules]

`defineTopic` describes a topic once: its name pattern, its events and each event's type. Share the file between your
web app, mobile app and backend so event names and types can't drift apart.

```ts title="topics.ts"
import { defineTopic } from '@folkwaysio/realtime';

type RideEvents = {
  location: { lat: number; lng: number };
  status: { state: 'waiting' | 'on-the-way' | 'arrived' };
};

export const ride = defineTopic<RideEvents>()('rides/{ride}', {
  events: {
    location: { delivery: 'kv', ttlMs: 30_000 },
    status: 'kv',
  },
});
```

Open it with the pattern's parameters. `publish()` then fills in each event's type and lifetime for you:

```ts
const trip = ride.open(client, { ride: '42' }); // the topic rides/42

await trip.publish('location', { lat: 59.43, lng: 24.75 }); // sent as KV, expires after 30 s
// trip.publish('pickup', …)                                // ✗ not in the definition
```

| Member | Returns |
| --- | --- |
| `pattern` | The pattern as written, e.g. `rides/{ride}` |
| `topic(params)` | The concrete name: `ride.topic({ ride: '42' })` is `'rides/42'` |
| `open(client, params)` | A typed topic handle |
| `rule()` | The topic rule, as JSON, to paste in the Console |
| `memberOps()` | The ops its events need: what to give members of a private topic |

Each `{param}` must be one topic level; a value with `/` throws `InvalidTopic`.

| Event option | Meaning |
| --- | --- |
| `delivery` | `'stream'`, `'kv'` or `'signal'`. A plain string is short for `{ delivery }` |
| `ttlMs` | KV and signals: the default lifetime |
| `keyIsPublisher` | KV: nobody but your backend may write another user's key |

| Topic option | Meaning |
| --- | --- |
| `access` | `'token'` (default) or `'members'` for a [private topic](/docs/js-sdk/private-topics) |
| `presence` | `true` to keep [presence](/docs/primitives/presence) for the topic |

### Export the rule [#export-the-rule]

```ts
console.log(JSON.stringify([ride.rule()], null, 2));
```

Paste the output on the segment's **Topic rules** tab with **Paste JSON**. The rule lists exactly the definition's
events, with `strict_events: true`, so publishing an event with another type, or an unknown name, fails with
`ClassMismatch`. See [Topic rules](/docs/console/topic-rules#paste-rules-as-json).
