存在
Share state between users with Realtime Presence.
使用实时在线状态来跟踪多个用户之间的状态。
🌐 Use Realtime Presence to track state between multiple users.
用法 #
🌐 Usage
你可以使用 Supabase 客户端库来跟踪用户之间的在线状态。
🌐 You can use the Supabase client libraries to track Presence state between users.
Presence 是如何运作的 #
🌐 How Presence works
Presence 让每个连接的客户端发布一小部分状态——称为“presence 负载”——到共享通道。Supabase 会将每个客户端的负载存储在一个唯一的 presence 键下,并保持所有连接客户端的合并视图。
🌐 Presence lets each connected client publish a small piece of state—called a “presence payload”—to a shared channel. Supabase stores each client’s payload under a unique presence key and keeps a merged view of all connected clients.
当任何客户端订阅、断开连接或更新他们的状态信息时,Supabase 会触发以下三种事件之一:
🌐 When any client subscribes, disconnects, or updates their presence payload, Supabase triggers one of three events:
sync— 完整状态已更新join— 一个新客户开始跟踪出勤了leave— 客户端已停止追踪在线状态
Presence 并不是为高频更新设计的
Presence 通过服务器同步状态,并在每次更改时通知所有订阅者。快速调用 track()——例如在每次鼠标移动时共享光标位置——会淹没通道并导致性能问题。
🌐 Presence syncs state through the server and notifies all subscribers on every change. Calling track() rapidly — for example on every mouse move to share cursor positions — will flood the channel and cause performance problems.
对于高频率或一次性更新,改用 Broadcast。Presence 最适合用于变化缓慢的状态,比如在线/离线状态、活动文档或当前页面。
🌐 For high-frequency or fire-and-forget updates, use Broadcast instead. Presence is best suited for slow-changing state such as online/offline status, active document, or current page.
同步事件行为
在 sync 事件期间,即使没有用户加入或离开,你也可能同时收到 join 和 leave 事件。这是预期的行为——Presence 会将本地状态与服务器状态进行同步,这个过程可能会触发这些事件。这反映的是状态的同步,而不是真实的用户动作。
🌐 During a sync event, you may receive join and leave events simultaneously, even though no users are joining or leaving. This is expected behavior—Presence reconciles its local state with the server state, which can trigger these events as part of the synchronization process. This reflects state reconciliation, not real user movement.
presenceState() 返回的完整在线状态看起来是这样的:
🌐 The complete presence state returned by presenceState() looks like this:
{ "client_key_1": [{ "userId": 1, "typing": false }], "client_key_2": [{ "userId": 2, "typing": true }]}初始化客户端 #
🌐 Initialize the client
从项目的 Connect 对话框 获取项目的 URL 和密钥。
🌐 Get the Project URL and key from the project's Connect dialog.
API 密钥的更改
Supabase 会在 2026 年底弃用 anon 和 service_role 密钥。请改用可发布的 (sb_publishable_xxx) 和秘密的 (sb_secret_xxx) 密钥。有关更改的原因,请参见 GitHub 上的公告。
🌐 Supabase is deprecating the anon and service_role keys by the end of 2026. Use the publishable (sb_publishable_xxx) and secret (sb_secret_xxx) keys instead. For the reasoning behind the change, see the announcement on GitHub.
在大多数情况下,你可以从你项目的连接对话框获取密钥。至于获取密钥的所有方式,包括 CLI 和管理 API,请参考查找你的密钥。
🌐 In most cases you can get keys from your project's Connect dialog. For every way to retrieve a key, including the CLI and the Management API, refer to Find your keys.
import { } from '@supabase/supabase-js'const = 'https://<project>.supabase.co'const = '<sb_publishable_... key>'const = (, )同步并跟踪状态 #
🌐 Sync and track state
监听 sync、join 和 leave 事件,这些事件会在任何客户端加入或离开通道,或更改其状态片段时触发:
🌐 Listen to the sync, join, and leave events triggered whenever any client joins or leaves the channel or changes their slice of state:
const = .('room_01') .('presence', { : 'sync' }, () => { const = .() .('sync', ) }) .('presence', { : 'join' }, ({ , }) => { .('join', , ) }) .('presence', { : 'leave' }, ({ , }) => { .('leave', , ) }) .()发送状态 #
🌐 Sending state
你可以使用 track() 向所有订阅者发送状态:
🌐 You can send state to all subscribers using track():
const = .('room_01')const = { : 'user-1', : new ().(),}.(async () => { if ( !== 'SUBSCRIBED') { return } const = await .() .()})一个客户端会接收任何订阅了相同主题(在这个例子中是 room_01)的其他客户端的状态。它也会自动触发自身的 sync 和 join 事件处理器。
🌐 A client will receive state from any other client that is subscribed to the same topic (in this case room_01). It will also automatically trigger its own sync and join event handlers.
停止追踪 #
🌐 Stop tracking
你可以使用 untrack() 方法停止追踪出席情况。这将触发 sync 和 leave 事件处理程序。
🌐 You can stop tracking presence using the untrack() method. This will trigger the sync and leave event handlers.
const = async () => { const = await .() .()}()显示选项 #
🌐 Presence options
你可以在初始化 Supabase 客户端时传入配置选项。
🌐 You can pass configuration options while initializing the Supabase Client.
存在键 #
🌐 Presence key
默认情况下,Presence 会在服务器上生成一个唯一的 UUIDv1 密钥来跟踪客户端通道的状态。如果你愿意,可以在创建通道时提供自定义密钥。这个密钥在客户端之间应该是唯一的。
🌐 By default, Presence will generate a unique UUIDv1 key on the server to track a client channel's state. If you prefer, you can provide a custom key when creating the channel. This key should be unique among clients.
import { } from '@supabase/supabase-js'const = ('SUPABASE_URL', 'SUPABASE_PUBLISHABLE_KEY')const = .('test', { : { : { : 'userId-123', }, },})