DocsRealtime

Realtime

Get every create, update and delete in a collection as it happens.

Sluurp sends each change to the clients subscribed to its collection. Each event goes through the subscriber’s own rules, so nobody hears about a row they couldn’t fetch. To subscribe, open an EventSource on /api/realtime:

app.ts
const events = new EventSource("/api/realtime?subscribe=messages,notices");
events.addEventListener("record", (e) => {
  const { action, collection, record } = JSON.parse(e.data);
  // action: "create", "update" or "delete"
});

Features include:

  • Server-sent events, with nothing to install in the browser
  • A WebSocket with presence and messages that aren’t stored
  • Writes over the same socket, under the same rules as over HTTP
  • One query for any number of subscribers who see the same rows

Server-sent events

To subscribe to some collections, list them in subscribe. To subscribe to every collection the caller can read, leave subscribe out.

The first event is connected, and it lists the subscriptions. After that, each change arrives as a record event.

EventSource can’t send headers, so a signed-in page passes its token in the URL:

app.ts
const events = new EventSource(`/api/realtime?subscribe=messages&token=${token}`);

WebSocket

To use a WebSocket instead, call sluurp.socket() in the browser client. It connects to /api/ws and adds presence and messages that aren’t stored:

app.ts
const socket = sluurp.socket({ subscribe: ["messages"] });
socket.on("record", ({ action, record }) => show(record));

socket.join("room:4b");                         // presence
socket.emit("room:4b", "typing", { by: me });  // broadcast, not stored
socket.send("messages", { body: "Hello" });     // a write, same rules as over HTTP

The socket reconnects on its own and joins its topics again.

Performance

Sluurp groups subscribers before it reads anything. A rule that doesn’t mention the caller gives everyone the same result, so it runs once for all of them: ten thousand anonymous subscribers cost one query.

A rule like author = @request.auth.id runs once per user, and connections from the same user share it.

When to use Sync instead

Most screens don’t need raw events. They need a list that stays up to date. Sync keeps a filtered collection current in the browser from the same events, and live views do the same for HTML rendered on the server.

View as Markdown