Quickback Docs

Using Realtime

WebSocket connections, authentication, and client-side event handling.

This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.

Connecting

Open a WebSocket connection to the realtime worker:

const ws = new WebSocket("wss://api.yourdomain.com/broadcast/v1/websocket");
// Note: /broadcast/v1 tracks contract.version — use /broadcast/v2 on contract-v2 projects.

Authentication

Quickback uses ticket-based authentication for WebSocket connections. This is a two-step process:

  1. Get a ticket — Call the ws-ticket endpoint with your session auth
  2. Connect with ticket — Pass the ticket as a URL parameter when opening the WebSocket

This approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.

Step 1: Get a WebSocket Ticket

const response = await fetch("/broadcast/v1/ws-ticket", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${sessionToken}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ eventId: "evt_123" }), // optional; used by resource-scoped wsTicket config
});
const { wsTicket, expiresIn } = await response.json();
// expiresIn = 60 (seconds)

The ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.

Step 2: Connect with Ticket

const ws = new WebSocket(
  `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`
);

ws.onopen = () => {
  console.log("Connected and authenticated!");
  // No auth message needed — connection is pre-authenticated
};

If the ticket is invalid or expired, the WebSocket upgrade is rejected with a 401 status.

Handling Messages

CRUD Events

CRUD events use the postgres_changes type:

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);

  if (msg.type === "postgres_changes") {
    const { table, eventType, new: newRecord, old: oldRecord } = msg;

    switch (eventType) {
      case "INSERT":
        addRecord(table, newRecord);
        break;
      case "UPDATE":
        updateRecord(table, newRecord);
        break;
      case "DELETE":
        removeRecord(table, oldRecord.id);
        break;
    }
  }
};

Event payload:

{
  "type": "postgres_changes",
  "table": "applications",
  "schema": "public",
  "eventType": "INSERT",
  "new": { "id": "app_123", "candidateId": "cnd_456", "stage": "interview" },
  "old": null
}

For UPDATE events, both new and old are populated. For DELETE events, only old is populated.

Custom Broadcasts

Custom events use the broadcast type:

if (msg.type === "broadcast") {
  const { event, payload } = msg;

  if (event === "screening-complete") {
    refreshApplication(payload.applicationId);
  } else if (event === "screening:progress") {
    updateProgressBar(payload.percent);
  }
}

Event payload:

{
  "type": "broadcast",
  "event": "screening-complete",
  "payload": {
    "applicationId": "app_123",
    "candidateId": "cnd_456",
    "stage": "interview"
  }
}

Custom namespaces (from defineRealtime()) use the format namespace:event — e.g., screening:started, screening:progress.

Security

Role-Based Filtering

Events are only delivered to subscribers who fall within the broadcast's audience. A broadcasting table's realtime config must declare access: { roles: [...] } — e.g. access: { roles: ["hiring-manager", "recruiter"] } delivers only to those roles. The audience is evaluated at fanout with the same uppercase pseudo-role semantics as REST (PUBLIC = everyone in the room, AUTHENTICATED, USER, SYSADMIN), plus concrete membership/scope roles. This is fail-closed: an empty or omitted audience delivers to no one (and is a compile error for a broadcasting resource). Applies to generated CRUD broadcasts and to live view view_changes deltas alike.

Named rules and gates in requiredRoles

Declared authz.roles and authz.rules gates can appear in realtime.requiredRoles. The compiler lowers them to flat static role names at build time, because the WebSocket ticket handshake has no DB in hand:

  • A named role lowers to its composing static roles; relationship (via:) arms contribute nothing at the handshake (the row-stream firewall enforces that dimension later) and emit a warning.
  • A who-only gate lowers as its who. A gate carrying record: or firewall arms is undecidable at the handshake — it contributes nothing, with a warning.
  • Fail-closed rule: a declared non-empty requiredRoles that lowers to an empty set is a compile error, never a silently-assigned []. The error names which entries lowered to nothing and why. Fix it by referencing a who-only rule, adding a static BA/pseudo-role fallback arm, or dropping the undecidable entries and relying on the row-stream firewall.

Per-Role Masking

Field values are masked according to the subscriber's role. For example, with this masking config:

masking: {
  ssn: { type: "ssn", show: { roles: ["owner"] } },
}
  • Owner sees: { ssn: "123-45-6789" }
  • Recruiter sees: { ssn: "*****6789" }

Masking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency. A type: 'custom' mask function can't run inside the Broadcaster — those columns broadcast as [REDACTED] (fail closed).

User-Specific Events

Events can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.

Scope Isolation

Each WebSocket connection is attached to exactly one resolved scope: scopeKey, organizationId, or userId. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.

Reconnection

WebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:

async function connect() {
  // Get a fresh ticket each time
  const res = await fetch("/broadcast/v1/ws-ticket", {
    method: "POST",
    headers: { Authorization: `Bearer ${sessionToken}` },
    body: JSON.stringify({ eventId: "evt_123" }),
  });
  const { wsTicket } = await res.json();

  const ws = new WebSocket(
    `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`
  );

  ws.onclose = () => {
    // Reconnect after delay
    setTimeout(connect, 2000);
  };

  ws.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    handleMessage(msg);
  };

  return ws;
}

Environment

No additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses BETTER_AUTH_SECRET for WebSocket ticket signing.

The compiler generates the required wrangler.toml bindings automatically:

[[durable_objects.bindings]]
name = "BROADCASTER"
class_name = "Broadcaster"

[[migrations]]
tag = "v1"
new_classes = ["Broadcaster"]

CloudEvents envelopes (contract v2)

On contract: { version: "v2" } the WebSocket endpoint moves to /broadcast/v2 and every data frame is wrapped in a CloudEvents 1.0 envelope at the Durable Object's send boundary. Control frames (pong, error, reauth_ok) stay raw on both versions, and pinned-v1 projects keep the raw frames byte-identically.

v1 frameCloudEvents typedataextensions
broadcast (named invalidation)the wire name verbatimpayload minus version/reasonqbframe: "broadcast", qbversion, qbreason
postgres_changes<project>.<table>.<insert|update|delete>{ table, schema, eventType, new, old }qbframe: "postgres_changes"
view_changes<project>.view.<viewName>.changed{ view, rootId, delta }qbframe: "view_changes", qbseq (the per-surface monotonic seq — your reconnect/gap-detection contract)

Discriminate frames on the qbframe extension, never on payload keys — named-invalidation payloads are author-supplied maps, so a broadcast whose payload happens to carry view/delta or table/eventType keys must not be mistaken for a system frame.

A changeset's afterCommit broadcast rides the same broadcast frame (the referenced typed event's wireName verbatim), so clients handle it exactly like any named invalidation — one CloudEvent per aggregate write, carrying the mapped payload (e.g. { eventId, reservationId, occupantIds }). Its optional root-row frame arrives as a normal postgres_changes frame on the table's room.

{ "specversion": "1.0",
  "id": "evt_9f2…",
  "source": "/broadcast/v2/websocket",
  "type": "event.mobile-bundle.changed",
  "time": "2026-07-20T12:00:00Z",
  "datacontenttype": "application/json",
  "qbframe": "broadcast",
  "qbversion": 1, "qbreason": "document.created",
  "data": { "eventId": "…", "documentId": "…" } }

The bundled CMS unwraps envelopes automatically. The full channel/message catalog ships as GET /asyncapi.json (AsyncAPI 3.0), served under the same auth gating as /openapi.json. The catalog itself is not v2-only — any project with realtime or webhooks serves it, on either contract version; what the pinned contract shapes is the message payload schemas it documents (raw frames on v1, the CloudEvents envelopes above on v2).

Cloudflare Only

Realtime requires Cloudflare Durable Objects and is only available with the Cloudflare runtime.

See Also

On this page