folkwaysDocs
Examples

Chat room

A chat room with messages, read receipts, typing indicators and a list of who's here, all on one Folkways topic.

One topic per room, rooms/{room}, carries everything:

EventPrimitiveWhy
messageStreamEvery message matters, in order, and a reload replays the latest
readKV, one per userOnly each user's latest read position matters
typingSignalStale in seconds; losing one is fine
who's herePresenceKept by Folkways from the connections

1. Define the topic

Describe the room once, in a file your app and your backend share:

topics.ts
TypeScript
import { defineTopic } from '@folkwaysio/realtime';

export type ChatEvents = {
  message: { text: string };
  read: { upTo: string }; // the uid of the last message read
  typing: { on: boolean };
};

export const chatRoom = defineTopic<ChatEvents>()('rooms/{room}', {
  events: {
    message: 'stream',
    read: { delivery: 'kv', keyIsPublisher: true },
    typing: { delivery: 'signal', ttlMs: 4_000 },
  },
  presence: true,
});

2. Add the rule

Print the rule and paste it on the segment's Topic rules tab with Paste JSON:

TypeScript
console.log(JSON.stringify([chatRoom.rule()], null, 2));
JSON
[
  {
    "pattern": "rooms/*",
    "types": ["stream", "kv", "signal"],
    "events": {
      "message": { "delivery": "stream" },
      "read": { "delivery": "kv", "key_is_publisher": true },
      "typing": { "delivery": "signal", "ttl_ms": 4000 }
    },
    "strict_events": true,
    "access": "token",
    "presence": true
  }
]

key_is_publisher stops anyone moving someone else's read receipt; strict_events refuses event names the rule doesn't list.

3. Issue tokens

Your backend gives each signed-in user a token for the rooms they belong to. Here, every room of their team:

server.ts
TypeScript
import express from 'express';
import { Folkways } from '@folkwaysio/realtime/server';
import { requireLogin } from './auth'; // your own login middleware; sets req.user

const folkways = new Folkways.Rest({
  url: process.env.FOLKWAYS_URL!,
  segment: process.env.FOLKWAYS_SEGMENT_ID!,
  signingKey: { kid: process.env.FOLKWAYS_KEY_ID!, privateKey: process.env.FOLKWAYS_PRIVATE_KEY! },
});

const app = express();

app.post('/api/realtime-token', requireLogin, async (req, res) => {
  const { token } = await folkways.createToken({
    identity: `user:${req.user.id}`,
    capabilities: [
      // read and post, mark read, type, and see who's here
      { topics: 'rooms/*', ops: ['subscribe', 'publish', 'set', 'signal', 'presence'] },
    ],
  });
  res.set('Cache-Control', 'no-store').json({ token });
});

app.listen(3000);

To limit users to their team's rooms, put the team in its own level (rooms/{team}/{room}) and grant rooms/team-7/*: wildcards match whole levels only. For rooms only some users may join, make the rule Members only; see private topics.

4. The app

room.ts
TypeScript
import { Folkways, type Message, type TopicMessage } from '@folkwaysio/realtime';
// import { chatRoom } from './topics';

declare function renderMessages(messages: readonly TopicMessage[]): void;
declare function renderReceipts(readers: Map<string, string>): void;
declare function renderTyping(names: string[]): void;
declare function renderHere(people: string[]): void;

const client = new Folkways.Realtime({
  url: 'https://realtime.folkways.net', // from the segment's Connect tab
  authUrl: '/api/realtime-token',
});
const session = await client.connect();
const me = session.identity;

export async function openRoom(roomId: string) {
  const room = chatRoom.open(client, { room: roomId });
  const here = client.topic(`$presence/${room.name}`);

  // Views keep their data while open. Open them before subscribing, so they see the replay.
  const messages = room.messages.open();
  const receipts = room.values('read').open();
  const typing = room.values('typing').open();
  const presence = here.values().open();

  const stops = [
    messages.subscribe(() => renderMessages(messages.getSnapshot())),
    receipts.subscribe(() => {
      const readers = new Map<string, string>();
      for (const [who, entry] of receipts.getSnapshot()) readers.set(who, (entry.data as { upTo: string }).upTo);
      renderReceipts(readers);
    }),
    typing.subscribe(() => {
      renderTyping([...typing.getSnapshot().values()].map((m) => m.publisher).filter((who) => who !== me));
    }),
    presence.subscribe(() => {
      const people = new Set<string>();
      for (const entry of presence.getSnapshot().values()) people.add((entry.data as { identity: string }).identity);
      renderHere([...people]);
    }),
  ];

  // One subscription delivers all three event types; the last 50 messages are replayed first.
  const subscription = room.subscribe({ from: { last: 50 } });
  const presenceSub = here.subscribe();
  await subscription.ready;

  return {
    async send(text: string) {
      const receipt = await room.publish('message', { text });
      if (receipt.uid) await room.publish('read', { upTo: receipt.uid });
    },
    markRead(message: Message) {
      if (message.uid) void room.publish('read', { upTo: message.uid });
    },
    typing() {
      void room.publish('typing', { on: true }); // call on input, at most every 2–3 s
    },
    async close() {
      stops.forEach((stop) => stop());
      [messages, receipts, typing, presence].forEach((view) => view.dispose());
      await Promise.all([subscription.unsubscribe(), presenceSub.unsubscribe()]);
    },
  };
}

Each message in the view has a status: pending while it is being sent, then sent or failed, with a retry() for failed ones. Show pending messages greyed out, and failed ones with a retry button.

5. Try it

Open the app in two browsers, signed in as different users, and join the same room. Messages appear in both, the other user's typing shows for four seconds after each keystroke burst, and both users appear under "here". Reload a page: the last 50 messages come back.

Going further

  • History beyond 50 messages, or older than a day. Store messages in your own database when your backend receives them, and load older pages from there. Folkways keeps a bounded window; see Stream.
  • Direct messages. Open a room per pair or group with folkways.dm.open().
  • React. Bind the same views with useSyncExternalStore; see React.
  • Offline. Keep cursors and unsent messages across reloads with a local store.

On this page