Home

Presence

Share state between users with Realtime Presence.

Let's explore how to implement Realtime Presence to track state between multiple users.

Usage#

You can use the Supabase client libraries to track Presence state between users.

Initialize the client#

Go to your Supabase project's API Settings and grab the URL and anon public API key.


_10
import { createClient } from '@supabase/supabase-js'
_10
_10
const SUPABASE_URL = 'https://<project>.supabase.co'
_10
const SUPABASE_KEY = '<your-anon-key>'
_10
_10
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)

Sync and track state#

Listen to the sync, join, and leave events triggered whenever any client joins or leaves the channel or changes their slice of state:


_14
const roomOne = supabase.channel('room_01')
_14
_14
roomOne
_14
.on('presence', { event: 'sync' }, () => {
_14
const newState = roomOne.presenceState()
_14
console.log('sync', newState)
_14
})
_14
.on('presence', { event: 'join' }, ({ key, newPresences }) => {
_14
console.log('join', key, newPresences)
_14
})
_14
.on('presence', { event: 'leave' }, ({ key, leftPresences }) => {
_14
console.log('leave', key, leftPresences)
_14
})
_14
.subscribe()

Sending state#

You can send state to all subscribers using track():


_13
const roomOne = supabase.channel('room_01')
_13
_13
const userStatus = {
_13
user: 'user-1',
_13
online_at: new Date().toISOString(),
_13
}
_13
_13
roomOne.subscribe(async (status) => {
_13
if (status !== 'SUBSCRIBED') { return }
_13
_13
const presenceTrackStatus = await roomOne.track(userStatus)
_13
console.log(presenceTrackStatus)
_13
})

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#

You can stop tracking presence using the untrack() method. This will trigger the sync and leave event handlers.


_10
const untrackPresence = async () => {
_10
const presenceUntrackStatus = await roomOne.untrack()
_10
console.log(presenceUntrackStatus)
_10
}
_10
_10
untrackPresence()

Presence options#

You can pass configuration options while initializing the Supabase Client.

Presence Key#

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.


_10
import { createClient } from '@supabase/supabase-js'
_10
_10
const channelC = supabase.channel('test', {
_10
config: {
_10
presence: {
_10
key: 'userId-123',
_10
},
_10
},
_10
})