在线状态、光标与实时协作状态
使用频道和本地乐观合并,同步多用户在线状态与共享状态。
在线状态、光标与实时协作状态 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What Is Presence in Collaborative Apps?
Presence is the real-time awareness of who else is in the same space as you — and what they are doing. Think of Google Docs showing avatars at the top, or Figma rendering other users' cursors on the canvas.
- Presence state: which users are currently connected to a channel
- Cursor state: where each user's mouse or caret is positioned
- Awareness metadata: name, avatar, active selection, scroll position
In Next.js 15 with the App Router, you build real-time collaboration on top of a channel abstraction — typically provided by Supabase Realtime, Ably, Pusher, or a custom WebSocket server. The principles are the same across providers.
The key design goal is low-latency local feedback: your own cursor must move instantly, and remote cursors should follow with minimal delay.
Setting Up a Supabase Realtime Channel
Supabase Realtime channels support Presence natively. A channel is a named pub/sub room where clients can track each other's state. You create a channel once per collaborative session and call channel.subscribe() to join it.
Install the client and create a typed channel in a client component:
'use client'
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
export function useCollabChannel(roomId: string) {
// Each room gets its own channel scoped by ID
const channel = supabase.channel(`room:${roomId}`, {
config: {
presence: { key: crypto.randomUUID() }, // unique key per tab
},
})
return channel
}Tracking Presence with channel.track()
Once subscribed, each client calls channel.track(payload) to broadcast its own presence state to every other subscriber in the channel. Supabase merges all presence payloads into a shared map keyed by the presence key you provided.
channel.track()— upserts your own statechannel.presenceState()— returns the current snapshot of all users- The
presenceevent fires whenever someone joins, leaves, or updates
Below is a React hook that tracks the current user and listens for changes:
'use client'
import { useEffect, useState } from 'react'
import { RealtimeChannel } from '@supabase/supabase-js'
type UserPresence = {
userId: string
name: string
color: string
online_at: string
}
export function usePresence(
channel: RealtimeChannel,
me: Omit<UserPresence, 'online_at'>
) {
const [others, setOthers] = useState<UserPresence[]>([])
useEffect(() => {
channel
.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState<UserPresence>()
const allUsers = Object.values(state).flat()
// Exclude own entry by userId
setOthers(allUsers.filter((u) => u.userId !== me.userId))
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({ ...me, online_at: new Date().toISOString() })
}
})
return () => { channel.unsubscribe() }
}, [channel, me.userId])
return others
}Rendering Online Avatars from Presence State
With the presence list in React state, rendering an avatar stack is straightforward. Assign each user a deterministic color so their avatar and cursor always match. A good strategy is to derive the color from the userId at login time and include it in the presence payload.
Here is a simple avatar bar component that consumes the hook from the previous scene:
'use client'
import { usePresence } from './usePresence'
import { RealtimeChannel } from '@supabase/supabase-js'
type Props = {
channel: RealtimeChannel
me: { userId: string; name: string; color: string }
}
export function AvatarBar({ channel, me }: Props) {
const others = usePresence(channel, me)
return (
<div style={{ display: 'flex', gap: 4 }}>
{/* Always show yourself first */}
<Avatar user={me} label="You" />
{others.map((user) => (
<Avatar key={user.userId} user={user} />
))}
</div>
)
}
function Avatar({
user,
label,
}: {
user: { name: string; color: string }
label?: string
}) {
return (
<div
title={label ?? user.name}
style={{
width: 32,
height: 32,
borderRadius: '50%',
background: user.color,
display: 'grid',
placeItems: 'center',
color: '#fff',
fontSize: 12,
fontWeight: 700,
}}
>
{user.name[0].toUpperCase()}
</div>
)
}Broadcasting Cursor Positions
Cursor position is too high-frequency for presence — calling channel.track() on every mouse move would flood the presence system. Instead, use broadcast, a fire-and-forget message type designed for rapid ephemeral events with no persistence guarantee.
channel.send({ type: 'broadcast', event: 'cursor', payload })— emits to all subscriberschannel.on('broadcast', { event: 'cursor' }, handler)— receives from others- Broadcast does not echo back to the sender
Throttle mouse events with requestAnimationFrame or a time gate before sending:
'use client'
import { useEffect, useRef } from 'react'
import { RealtimeChannel } from '@supabase/supabase-js'
export function useCursorBroadcast(
channel: RealtimeChannel,
userId: string
) {
const lastSent = useRef(0)
useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
const now = Date.now()
// Throttle: send at most every 50 ms (~20 fps)
if (now - lastSent.current < 50) return
lastSent.current = now
channel.send({
type: 'broadcast',
event: 'cursor',
payload: { userId, x: e.clientX, y: e.clientY },
})
}
window.addEventListener('mousemove', handleMouseMove)
return () => window.removeEventListener('mousemove', handleMouseMove)
}, [channel, userId])
}Receiving and Rendering Remote Cursors
On the receiving side, maintain a Map of cursor positions keyed by userId. Each broadcast message upserts that user's latest coordinates. React renders a floating div for each remote cursor, positioned absolutely over the canvas.
Combine this with the presence list so you have the user's name and color alongside the coordinates:
'use client'
import { useEffect, useState } from 'react'
import { RealtimeChannel } from '@supabase/supabase-js'
type CursorPos = { userId: string; x: number; y: number }
export function useRemoteCursors(channel: RealtimeChannel) {
const [cursors, setCursors] = useState<Map<string, CursorPos>>(
new Map()
)
useEffect(() => {
channel.on(
'broadcast',
{ event: 'cursor' },
({ payload }: { payload: CursorPos }) => {
setCursors((prev) => {
const next = new Map(prev)
next.set(payload.userId, payload)
return next
})
}
)
}, [channel])
return cursors
}
// In your canvas component:
// const cursors = useRemoteCursors(channel)
// {Array.from(cursors.values()).map(({ userId, x, y }) => (
// <div key={userId} style={{ position: 'fixed', left: x, top: y,
// pointerEvents: 'none', transform: 'translate(-4px,-4px)' }}>
// ▶
// </div>
// ))}Optimistic Local Merges for Shared State
When multiple users edit shared data (a document, a whiteboard, a form), you must reconcile concurrent changes. The naive approach — round-trip to the server before updating local state — causes visible lag and conflicts.
Optimistic local merge means you apply your own change immediately to local state, broadcast it, and let the server or peers confirm later. The pattern follows three steps:
- Apply locally first — update your own React state instantly (zero latency)
- Broadcast the delta — send only the change (not the full document) over the channel
- Reconcile on receive — when you receive a remote delta, merge it into your local state using a deterministic strategy
A simple conflict rule for text fields: last-write-wins by timestamp. For structured data, a field-level merge is safer.
Broadcasting and Merging State Deltas
Below is a hook that manages a shared Record (e.g., sticky-note positions on a board). Each user can move any note; changes are applied optimistically and broadcast as field-level deltas so concurrent edits to different fields never overwrite each other.
'use client'
import { useCallback, useEffect, useState } from 'react'
import { RealtimeChannel } from '@supabase/supabase-js'
type NoteMap = Record<string, { x: number; y: number; text: string }>
type Delta = { noteId: string; patch: Partial<{ x: number; y: number; text: string }> }
export function useSharedBoard(
channel: RealtimeChannel,
initial: NoteMap
) {
const [board, setBoard] = useState<NoteMap>(initial)
// Apply an incoming delta to local state
const applyDelta = useCallback((delta: Delta) => {
setBoard((prev) => ({
...prev,
[delta.noteId]: { ...prev[delta.noteId], ...delta.patch },
}))
}, [])
// Listen for remote deltas
useEffect(() => {
channel.on(
'broadcast',
{ event: 'board_delta' },
({ payload }: { payload: Delta }) => applyDelta(payload)
)
}, [channel, applyDelta])
// Expose a mutate function that applies locally AND broadcasts
const mutate = useCallback(
(noteId: string, patch: Delta['patch']) => {
applyDelta({ noteId, patch }) // optimistic
channel.send({
type: 'broadcast',
event: 'board_delta',
payload: { noteId, patch },
})
},
[channel, applyDelta]
)
return { board, mutate }
}Persisting State via a Server Action
Broadcast deltas are ephemeral — a user who joins mid-session sees nothing. You need a persistent source of truth. The pattern is:
- On mount, fetch initial state from the server (Server Component or
fetch) - On each local mutation, also call a Server Action to persist the delta to the database
- New joiners load the latest persisted state, then subscribe for live deltas
The Server Action debounces writes to avoid a database call on every keystroke:
// app/actions/board.ts
'use server'
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
export async function persistNotePatch(
roomId: string,
noteId: string,
patch: { x?: number; y?: number; text?: string }
) {
const supabase = await createClient()
const { error } = await supabase
.from('notes')
.update(patch)
.eq('id', noteId)
.eq('room_id', roomId)
if (error) throw new Error(error.message)
// Invalidate the page so a fresh SSR render has up-to-date data
revalidatePath(`/rooms/${roomId}`)
}
// On the client, debounce the call:
// const save = useDebouncedCallback(
// (noteId, patch) => persistNotePatch(roomId, noteId, patch),
// 800
// )
// Call save(noteId, patch) inside mutate() after the broadcast.Handling User Disconnection and Cleanup
When a user navigates away or closes the tab, Supabase Realtime automatically removes their presence entry — no explicit leave message is needed. However, cursor positions stored in your local React state are not automatically cleaned up.
Listen for the leave presence event to remove stale cursors:
'use client'
import { useEffect, useState } from 'react'
import { RealtimeChannel } from '@supabase/supabase-js'
type CursorPos = { userId: string; x: number; y: number }
export function useCleanupOnLeave(
channel: RealtimeChannel,
setCursors: React.Dispatch<React.SetStateAction<Map<string, CursorPos>>>
) {
useEffect(() => {
channel.on(
'presence',
{ event: 'leave' },
({ leftPresences }: { leftPresences: Array<{ userId: string }> }) => {
setCursors((prev) => {
const next = new Map(prev)
for (const p of leftPresences) {
next.delete(p.userId)
}
return next
})
}
)
}, [channel, setCursors])
}Pure TypeScript: Merging Presence Maps
Understanding the merge semantics of presence and delta state is easier with a pure function you can reason about in isolation. This standalone snippet demonstrates a last-write-wins field merge for a presence-keyed state map — the same logic your hooks use internally.
This code is fully self-contained and runnable with the TypeScript compiler:
type PresenceEntry = { userId: string; name: string; updatedAt: number }
type PresenceMap = Record<string, PresenceEntry>
function mergePresence(
current: PresenceMap,
incoming: PresenceEntry
): PresenceMap {
const existing = current[incoming.userId]
// Keep whichever entry has the higher timestamp
if (existing && existing.updatedAt >= incoming.updatedAt) {
return current
}
return { ...current, [incoming.userId]: incoming }
}
function removeUser(map: PresenceMap, userId: string): PresenceMap {
const { [userId]: _, ...rest } = map
return rest
}
// --- demo ---
let state: PresenceMap = {}
state = mergePresence(state, { userId: 'u1', name: 'Alice', updatedAt: 1000 })
state = mergePresence(state, { userId: 'u2', name: 'Bob', updatedAt: 1001 })
// Stale update for Alice — should be ignored
state = mergePresence(state, { userId: 'u1', name: 'Alice-old', updatedAt: 900 })
console.log('Presence map:', JSON.stringify(state, null, 2))
// Alice's name should still be 'Alice', not 'Alice-old'
state = removeUser(state, 'u2')
console.log('After Bob leaves:', Object.keys(state))
// Output: ['u1']Knowledge Check: Cursor Position Updates
In a collaborative canvas app built with Next.js 15 and Supabase Realtime, you need to sync live cursor positions between users. Which channel mechanism is the most appropriate choice, and why?
Lesson Recap: Presence, Cursors, and Live State
In this lesson you built the foundational layer of a real-time collaborative experience in Next.js 15:
- Presence via channel.track() — broadcasts slow-changing metadata (name, color, online status) and maintains a merged map of all connected users; clients auto-removed on disconnect
- Cursor broadcast — high-frequency mouse positions sent with
channel.send({ type: 'broadcast' }), throttled to ~20 fps to avoid flooding; never use presence for this - Optimistic local merges — apply your own change to React state instantly, broadcast the delta, and reconcile remote deltas with a field-level merge to avoid overwriting concurrent edits
- Persistence via Server Actions — debounced writes to the database give new joiners a valid initial state; combine with
revalidatePathfor SSR freshness - Cleanup on leave — listen for the presence
leaveevent to remove stale cursor overlays from local state
The architecture separates concerns cleanly: presence for identity, broadcast for ephemeral position, Server Actions + database for durable truth. This combination scales to dozens of simultaneous collaborators with low perceived latency.
常见问题解答
「在线状态、光标与实时协作状态」课时是免费的吗?
是的 — 「在线状态、光标与实时协作状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
「在线状态、光标与实时协作状态」这节课中我会学到什么?
使用频道和本地乐观合并,同步多用户在线状态与共享状态。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「在线状态、光标与实时协作状态」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 路由处理程序中的服务器发送事件
- 在无服务器环境中集成 WebSocket 服务
- 逐令牌流式传输人工智能响应
- 在线状态、光标与实时协作状态