Skip to Content
Server

Realtime

Presence, live updates and shared state per channel, on Bun, Node or Cloudflare.

Usage

import { createRealtime, sessionAuth } from "@dapplelight/signet-server/realtime"
import { bunRealtime } from "@dapplelight/signet-server/realtime/bun"
import { verifySession } from "@dapplelight/signet-server/auth/session"
import { grants } from "@dapplelight/signet-server/http/orgs"
import { serve } from "bun"
import { app } from "./app"
import { orgs, sessionOpts } from "./auth"

const hub = createRealtime({
  // Deny by default: without authorize, every join is refused.
  authorize: (who, channel) => channel.startsWith("record:") && grants(who.permissions ?? [], "records:read"),
})

const authenticate = sessionAuth({
  verify: (token) => verifySession(token, sessionOpts),
  cookieName: "app_session",
  orgs, // signet-db's createOrgs: needs membership(orgId, userId)
})

const live = bunRealtime(hub, { authenticate })
serve({
  fetch: (req, srv) => (new URL(req.url).pathname === "/realtime" ? live.upgrade(req, srv) : app.fetch(req)),
  websocket: live.websocket,
})

// After a write:
export async function afterWrite(orgId: string, userId: string) {
  await hub.publish(orgId, "record:invoices:1042", "updated", { id: "1042", by: userId })
}

The org comes from authenticate, never the client. Channels live under it: two orgs' record:invoices:1042 are different channels. The React side is signet-ui's use-channel hook.

API

realtime (hub)

ExportWhat it does
createRealtime(options)The hub: connect, publish, presence, state, disconnect, sweep, size.
sessionAuth(options)authenticate from a session cookie plus org membership.
admit(request, { authenticate, origins? })Check Origin and identity for an upgrade: the identity, or a 401 or 403 Response.
realtimeOutbox(publisher)send(message) that publishes outbox rows. The row id becomes the event id.
REALTIME_TOPIC"realtime", the outbox topic.
CLOSEClose codes: unsupported 1003, policy 1008, tooBig 1009, slow 1013, timeout 4000, expired 4001, kicked 4003.
RealtimeIdentity, RealtimeSocket, RealtimeLimits, RealtimeOptions, PresenceMember, StateEntry, RealtimeEvent, RealtimePublisher, RealtimeConnection, RealtimeHub, AdmitOptions, RealtimeMembersTypes.
createRealtime optionTypeDefault
authorize(who, channel) => booleanrefuse allMay who join channel?
limits.maxMessageBytesnumber16 KiBCloses 1009.
limits.messagesPerSecondnumber20Burst is twice this. Closes 1008.
limits.maxChannelsnumber20Per connection.
limits.maxStateKeysnumber100Per channel.
limits.maxBufferedBytesnumber1 MiBA slow consumer is closed 1013 and resumes on reconnect.
limits.historynumber100Events kept per channel for resume.
heartbeatMsnumber15 sHow often clients ping.
timeoutMsnumber45 sA silent connection is closed.
typingMsnumber6 sA typing flag clears itself.
idleMsnumber5 minAn empty channel, with history and state, is dropped.

Identity: { userId, orgId, name?, avatar?, permissions?, expiresAt? }. A session's exp closes its sockets.

sessionAuth optionTypeDefault
verify(token) => { sub?, exp? } | nullrequired
cookieNamestringrequired
orgs{ membership(orgId, userId) }requiredA non-member is refused.
org(request) => string?org=, then the signet_org cookie
profile(userId) => { name?, avatar? }noneFor presence.

Wire protocol

JSON text frames.

DirectionMessage
Client to server{ type: "join", channel, since?: { epoch, seq } }
{ type: "leave", channel }
{ type: "presence", channel, typing?, editing? }
{ type: "set", channel, key, value, base? }
{ type: "ping" }
Server to clientwelcome, joined, event, presence, state, conflict, pong, error

A rejoin with since gets exactly what was missed, or reset when the gap is older than the history. Shared state is last writer wins; a writer whose base was older gets conflict. State lives in memory: persist what matters in your database.

realtime/bun

ExportWhat it does
bunRealtime(hub, options)upgrade(request, server) and websocket for Bun.serve.
BunSocket, BunServerStructural types.

Options: authenticate, origins?, maxMessageBytes? (16 KiB), maxBufferedBytes? (1 MiB).

realtime/node

ExportWhat it does
attachRealtime(server, hub, options)Serve the hub on an http.Server's upgrade event. Returns a detach function.
NodeRealtimeOptionsauthenticate, origins?, path? ("/realtime"), maxMessageBytes?.

A small RFC 6455 server with no dependency: text frames, fragmentation, ping and pong, close. No compression.

realtime/cloudflare

ExportWhat it does
realtimeRoom(options)Durable Object class holding one org's hub. Export it from the worker entry.
connectRoom(namespace, request, { authenticate, origins? })Authenticate in the worker, then hand the socket to the org's object.
roomPublisher(namespace)A RealtimePublisher for a worker, cron or realtimeOutbox.
RealtimeNamespace, WorkerSocketStructural types.

Examples

Node

import { attachRealtime } from "@dapplelight/signet-server/realtime/node"
import { authenticate, hub, server } from "./realtime"

attachRealtime(server, hub, { path: "/realtime", authenticate })

Cloudflare, one Durable Object per org

import {
  connectRoom,
  type RealtimeNamespace,
  realtimeRoom,
  roomPublisher,
} from "@dapplelight/signet-server/realtime/cloudflare"
import { app } from "./app"
import { authenticate } from "./auth"

export const RealtimeRoom = realtimeRoom({ authorize: (who, channel) => channel.startsWith("record:") })

app.get("/realtime", (c) => connectRoom(c.env.REALTIME, c.req.raw, { authenticate }))

export async function afterWrite(env: { REALTIME: RealtimeNamespace }, orgId: string) {
  await roomPublisher(env.REALTIME).publish(orgId, "record:invoices:1042", "updated", { id: "1042" })
}
// wrangler.jsonc
"durable_objects": { "bindings": [{ "name": "REALTIME", "class_name": "RealtimeRoom" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["RealtimeRoom"] }]

Publish in the same write as the data

import { REALTIME_TOPIC, realtimeOutbox } from "@dapplelight/signet-server/realtime"
import { eq } from "drizzle-orm"
import { drainOutbox, enqueue } from "@dapplelight/signet-db"
import { db } from "./db"
import { hub } from "./realtime"
import { queue } from "./queue"
import { invoices } from "./schema"

export async function updateInvoice(orgId: string, userId: string, id: string, patch: { status: string }) {
  await db.batch([
    (tx) => tx.update(invoices).set(patch).where(eq(invoices.id, id)),
    enqueue(db, REALTIME_TOPIC, { orgId, channel: `record:invoices:${id}`, event: "updated", data: { id, by: userId } }),
  ])
  const live = realtimeOutbox(hub) // or realtimeOutbox(roomPublisher(env.REALTIME))
  await drainOutbox(db, { send: (m) => (m.topic === REALTIME_TOPIC ? live.send(m) : queue.send(m)) })
}

Remove a member's sockets

import { hub } from "./realtime"

export function removeMember(orgId: string, userId: string) {
  hub.disconnect(orgId, userId) // omit userId to close every connection in the org
}