Realtime, channels and presence

When one person books the last mat, everyone else should see "Full" straight away, without reloading. List a table as live and every change reaches the people who can read that row, re-read as each of them. Declare a channel for what isn't a row change: chat rooms, typing indicators, who's looking at this right now.

When to use it

  • Chats, queues, kitchen boards, live counters and dashboards.
  • Typing indicators, "3 people are viewing this" and online lists.
  • Any screen several people look at while the data changes.

Declare it in app.config.ts

realtime: {
  live: ["message", "class_session"],          // row changes stream, re-read as each user under RLS
  channels: {
    room: { access: ["member"], presence: true, table: "room" },   // one channel per room row: "room:<id>"
    lobby: { access: "public", publish: "signed_in" },
  },
},
  • live: the tables whose changes stream to the browser. A table not listed is still followed, through the slower change topics.
  • access: who may join: "public" (signed-out visitors too), "signed_in" (the default) or a list of roles.
  • publish: who may send: "members" (whoever joined, the default), "signed_in", "none" (server code only) or roles.
  • presence: true: members see who else is on the channel.
  • table: one channel per row of that table, joined with the row's id, and only by people who can read that row.

Channel names are lower-case letters, digits and _, at most 50. An unknown table or role is a check error at its line.

Code

Keep a page's reads current

import { useLive, useQuery } from "@appbricx/ui";

const { rows } = useQuery("class_session", { sort: "starts_at" });
useLive("class_session");   // any change to a class this user may read refetches the page's reads of it

A chat room

The messages are rows of a live table; typing and presence are on the channel.

import { useState } from "react";
import { useAppHandle, useChannel, useLiveRows, usePresence, useTable } from "@appbricx/ui";

export function ChatRoom({ roomId }: { roomId: string }) {
  const app = useAppHandle();
  const { rows } = useLiveRows(app, "message", { room_id: roomId }, { limit: 100 });  // newest first, kept current
  const [typing, setTyping] = useState("");
  const room = useChannel(app, "room", roomId, {
    typing: (_payload, from) => { if (!from?.self) setTyping((from?.name ?? "Someone") + " is typing…"); },
  });
  const here = usePresence(app, "room", roomId);
  const messages = useTable("message");

  const send = (text: string) => messages.create({ room_id: roomId, body: text });
  const onKey = () => void room.send("typing", {});
  // render rows, typing, here.length, and room.error when the join was refused
}

Who receives what

  • Every changed row is re-read as each subscriber, with their role and the table's policies, so a member following bookings only ever receives rows they could read anyway, and hidden columns never leave the server.
  • A row that leaves someone's view (reassigned, or no longer matching the filter) drops out of their list.
  • Channel messages go to everyone on the channel, the sender included, with who sent them (from.name, from.role, from.self). A send outside publish is refused.
  • Nothing starts during the server render. Live updates begin after the page hydrates.

Topics: your own live messages

Server code publishes on an app topic with ctx.topics.publish(name, payload) (in a workflow, step.ctx.topics.publish inside a step.run); subscribers read GET /__appbricx/topics/<name>/subscribe as server-sent events. call_app { "kind": "topic", "name": "…", "input": {…} } publishes one to test it.

Check it

tail { "project_id": "…", "kind": "events", "since": "15m" }   // row changes and topic messages as they happen
screenshot { "project_id": "…", "route": "/rooms/<id>", "as": "member" }

To see a change arrive, keep a page open in the preview, then write the row as another user (edit_rows with as, or call_app as another role).

Gotchas

  • Channel messages aren't stored. Someone who joins later doesn't see earlier ones: keep chat lines as rows.
  • Events are a live signal, not a queue. Work that must happen belongs in a workflow, which is recorded, retried and logged.
  • useLiveRows, useChannel and usePresence take the app handle (useAppHandle()) as their first argument; useLive doesn't.
  • Without a realtime section, useLive still follows tables through the change topics, and channels report that they can't join.

Related