Live cursors and presence
Cursors are Broadcast frames, throttled to 12 per second because a connection may send 20 frames per second in total. Online and typing are Presence: one entry per user, removed by the server when the socket closes, and a late joiner receives the current state at once. A single channel_access policy decides who may join, send and be listed.
Tested with 3 simulated clients plus a late joiner: every client saw all the others online, cursors reached everyone but the sender, 200 moves in about one second produced at most 12 frames per second, typing cleared itself, and a user who left disappeared from the others. Broadcast is not stored: use a table with postgres_changes for anything that must not be lost. One project, one environment: a correctness check, not a performance guarantee.
Shared canvas
3 online
- You
- Ana
- Bo
Cursors are Broadcast frames (throttled to 12 per second); online and typing are Presence. No table. Ana and Bo are simulated here.
'use client'import { useEffect, useRef, useState } from 'react'import { createBrowserClient } from '@potalab/base/next'import { joinRoom, type Me, type Peer } from '@/lib/cursor-room'
export function Cursors({ roomId, user }: { roomId: string; user: Me }) { const canvas = useRef<HTMLDivElement>(null) const room = useRef<ReturnType<typeof joinRoom> | null>(null) const [peers, setPeers] = useState<Peer[]>([]) const [pos, setPos] = useState<Record<string, { x: number; y: number }>>({})
useEffect(() => { const base = createBrowserClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY!, }) const r = joinRoom(base, roomId, user, { onCursor: (id, x, y) => setPos((p) => ({ ...p, [id]: { x, y } })), onPeers: (list) => { setPeers(list) // someone who left takes their cursor with them setPos((p) => Object.fromEntries(Object.entries(p).filter(([id]) => list.some((x) => x.id === id)))) }, }) room.current = r return () => void r.leave() }, [roomId, user.id])
const others = peers.filter((p) => p.id !== user.id) const typing = others.filter((p) => p.typing).map((p) => p.name) return ( <div> <p> {peers.length} online{typing.length > 0 && `, ${typing.join(', ')} typing...`} </p> <div ref={canvas} style={{ position: 'relative', height: 320, border: '1px solid #ccc' }} onMouseMove={(e) => { const b = canvas.current!.getBoundingClientRect() room.current?.moveCursor((e.clientX - b.left) / b.width, (e.clientY - b.top) / b.height) }} > {others.map( (p) => pos[p.id] && ( <span key={p.id} style={{ position: 'absolute', left: `${pos[p.id]!.x * 100}%`, top: `${pos[p.id]!.y * 100}%`, color: p.color }} > {p.name} </span> ), )} </div> <input placeholder="Type here" onChange={() => room.current?.setTyping(true)} /> </div> )}import type { createBrowserClient } from '@potalab/base/next'
type Client = ReturnType<typeof createBrowserClient>export type Me = { id: string; name: string; color: string }export type Peer = Me & { typing: boolean; presence_ref: string }
// The server accepts 20 frames/s per connection (all messages); more are rejected and 10 violations close the socket.const CURSOR_HZ = 12
export function joinRoom( base: Client, roomId: string, me: Me, hooks: { onCursor?: (id: string, x: number, y: number) => void; onPeers?: (peers: Peer[]) => void },) { let lastSent = 0 let timer: ReturnType<typeof setTimeout> | null = null let pending: { x: number; y: number } | null = null let typingTimer: ReturnType<typeof setTimeout> | undefined let meta = { name: me.name, color: me.color, typing: false }
const ch = base .channel(`cursors:${roomId}`, { // self:false: I do not receive my own cursor. presence key = user id: one entry per person, one meta per tab config: { broadcast: { self: false, ack: false }, presence: { key: me.id } }, }) .on('broadcast', { event: 'cursor' }, ({ payload }) => hooks.onCursor?.(payload.id, payload.x, payload.y)) .on('presence', { event: 'sync' }, () => { const state = ch.presenceState() hooks.onPeers?.(Object.entries(state).map(([id, metas]) => ({ ...metas[metas.length - 1], id }) as Peer)) }) .subscribe(async (status) => { if (status === 'SUBSCRIBED') await ch.track(meta) // tracked again by the SDK after a reconnect })
const flush = () => { timer = null if (!pending) return const p = pending pending = null lastSent = Date.now() void ch.send({ type: 'broadcast', event: 'cursor', payload: { id: me.id, x: p.x, y: p.y } }) }
return { /** x and y are fractions (0..1) of the canvas. Throttled; the last position always goes out. */ moveCursor(x: number, y: number) { pending = { x, y } if (!timer) timer = setTimeout(flush, Math.max(0, 1000 / CURSOR_HZ - (Date.now() - lastSent))) }, /** The typing flag lives in presence, so a late joiner sees it. Resets itself after 2 s. */ setTyping(on = true) { if (meta.typing !== on) { meta = { ...meta, typing: on } void ch.track(meta) } clearTimeout(typingTimer) if (on) typingTimer = setTimeout(() => this.setTyping(false), 2000) }, async leave() { clearTimeout(timer ?? undefined) clearTimeout(typingTimer) await ch.untrack() return base.removeChannel(ch) }, }}// app/canvas/page.tsx (Server Component)import { redirect } from 'next/navigation'import { baseServer } from '@/lib/base-server'import { Cursors } from './Cursors'
const COLORS = ['#e11d48', '#16a34a', '#2563eb', '#d97706', '#7c3aed']
export default async function CanvasPage() { const base = await baseServer() const { data: { user } } = await base.auth.getUser() if (!user) redirect('/login')
// One stable colour per person, derived from the id const color = COLORS[parseInt(user.id.slice(0, 4), 16) % COLORS.length]! const name = user.email?.split('@')[0] ?? 'guest'
return ( <main> <h1>Shared canvas</h1> <Cursors roomId="main" user={{ id: user.id, name, color }} /> </main> )}// lib/base-server.ts// One client PER REQUEST: it holds the signed-in user's session.import { cookies } from 'next/headers'import { createServerClient } from '@potalab/base/next'
export async function baseServer() { const store = await cookies() return createServerClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY!, // pb_pub_... cookies: { getAll: () => store.getAll(), setAll: (list) => list.forEach((c) => store.set(c.name, c.value, c.options)), }, })}-- collab-cursors: who may join / send / track on the private channel "cursors:<room id>".-- Broadcast and presence need NO table; only this policy (rows of realtime.channel_access: channel, action).-- Here every signed-in user may do all three. Narrow it with a membership table, as in realtime-chat.
drop policy if exists cursors_channel on realtime.channel_access;create policy cursors_channel on realtime.channel_access for select to authenticated using (channel like 'cursors:%');
-- Receive only (read-only viewers): replace the policy above with-- using (channel like 'cursors:%' and action = 'join');-- action = 'broadcast' lets a client send cursors, action = 'presence' lets it track.Snippet for illustration, written for the Next.js App Router with @potalab/base/next,@potalab/base/react and @potalab/base. Set NEXT_PUBLIC_POTALAB_BASE_URL andNEXT_PUBLIC_POTALAB_BASE_KEY, adapt names and redirect URLs, and review policies before production.
Next: Todo app with RLS →