Add Real-Time Presence and Live Updates
Who is viewing a record, who is typing, and a banner when someone else saves, over WebSockets on your runtime.
Install
npm i @dapplelight/signet-server @dapplelight/signet-uiCreate the hub
import { createRealtime, sessionAuth } from "@dapplelight/signet-server/realtime"
import { verifySession } from "@dapplelight/signet-server/auth/session"
import { grants } from "@dapplelight/signet-server/http/orgs"
import { orgs, sessionOpts } from "./auth"
export const hub = createRealtime({
// Deny by default: without authorize, every join is refused.
authorize: (who, channel) =>
channel.startsWith("record:") && grants(who.permissions ?? [], "records:read"),
})
export const authenticate = sessionAuth({
verify: (t) => verifySession(t, sessionOpts),
cookieName: "app_session",
orgs,
})Attach it to your runtime
import { bunRealtime } from "@dapplelight/signet-server/realtime/bun"
import { serve } from "bun"
import { app } from "./app"
import { authenticate, hub } from "./realtime"
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,
})import { attachRealtime } from "@dapplelight/signet-server/realtime/node"
import { server } from "./http"
import { authenticate, hub } from "./realtime"
attachRealtime(server, hub, { path: "/realtime", authenticate })import { connectRoom, realtimeRoom } from "@dapplelight/signet-server/realtime/cloudflare"
import { app } from "../server/app"
import { authorize } from "../server/authorize"
import { authenticate } from "../server/realtime"
export const RealtimeRoom = realtimeRoom({ authorize }) // bind as REALTIME
app.get("/realtime", (c) => connectRoom(c.env.REALTIME, c.req.raw, { authenticate }))Publish when a record changes
import { eq } from "drizzle-orm"
import { db } from "../db"
import { docs } from "../db/schema"
import { hub } from "../realtime"
export async function saveDoc(
{ orgId, userId, userName }: { orgId: string; userId: string; userName: string },
id: string,
patch: Partial<typeof docs.$inferInsert>,
) {
await db.update(docs).set(patch).where(eq(docs.id, id))
hub.publish(orgId, `record:docs:${id}`, "updated", { id, by: userId, name: userName })
}Show presence in React
import {
AvatarStack,
EditingBadge,
RecordChangedBanner,
TypingIndicator,
} from "@dapplelight/signet-ui/screens/realtime-screens"
import {
createRealtimeClient,
useChannel,
useRecordChanges,
} from "@dapplelight/signet-ui/hooks/use-channel"
import { orgId } from "./session"
import { useDoc } from "./use-doc"
const live = createRealtimeClient({ url: `/realtime?org=${orgId}` })
export function Doc({ id, me }: { id: string; me: string }) {
const { refetch } = useDoc(id)
const ch = useChannel(live, `record:docs:${id}`)
const { changed, change, dismiss } = useRecordChanges(live, `record:docs:${id}`, { selfId: me })
return (
<>
<RecordChangedBanner changed={changed} by={change?.data?.name} onReload={() => { refetch(); dismiss() }} />
<AvatarStack members={ch.members} selfId={me} />
<EditingBadge members={ch.members} selfId={me} field="title" />
<input
onFocus={() => ch.setEditing("title")}
onBlur={() => ch.setEditing(null)}
onInput={() => ch.setTyping(true)}
/>
<TypingIndicator members={ch.members} selfId={me} />
</>
)
}The org comes from authenticate, never from the client, so tenants cannot see each other's channels. Bun and Node hubs live in one process: run one instance.
Server-authoritative rooms
Give a channel (or a prefix ending in *) a reducer and its value changes only through it. A client sends { type: "action", channel, action, ref? }; the hub runs the reducer and broadcasts an action event { action, by, value, ref } with the usual seq, or answers only the sender with an error. set is refused on these channels.
import { ActionRejected, createRealtime } from "@dapplelight/signet-server/realtime"
type Turn = { holder: string | null; closed: boolean }
export const hub = createRealtime({
authorize: (who, channel) => channel.startsWith("turn:"),
actions: {
"turn:*": {
initial: (): Turn => ({ holder: null, closed: false }),
reduce: (state: Turn, action, who, ctx) => {
if (!who) return { ...state, closed: true } // the deadline below, run by the server
if (state.closed || state.holder === who.userId) throw new ActionRejected("Not now.")
ctx.schedule("close", ctx.now + 15_000, { close: true }) // same name replaces
return { holder: who.userId, closed: false }
},
},
},
})On Cloudflare, realtimeRoom keeps deadlines in Durable Object alarms and reducer values in its storage, so "closes in 15 s" survives eviction and restarts. On Bun and Node they are in-memory timers.
To let users of different orgs meet, set room on the identity in authenticate. connectRoom then routes the socket to that room's object, and roomScope(key) stands in for the org id when publishing.
import { connectRoom, roomPublisher } from "@dapplelight/signet-server/realtime/cloudflare"
import { roomScope } from "@dapplelight/signet-server/realtime"
import { app } from "../server/app"
import { authenticate } from "../server/realtime"
import { mayEnter } from "../server/rooms"
app.get("/rooms/:key/live", (c) =>
connectRoom(c.env.REALTIME, c.req.raw, {
authenticate: async (req) => {
const who = await authenticate(req)
const key = c.req.param("key")
return who && (await mayEnter(who.userId, key)) ? { ...who, room: key } : null
},
}),
)
export const announce = (env: { REALTIME: DurableObjectNamespace }, key: string) =>
roomPublisher(env.REALTIME as never).publish(roomScope(key), "turn:1", "opened")