Realtime

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.

How Presence works#

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.

When any client subscribes, disconnects, or updates their presence payload, Supabase triggers one of three events:

  • sync — the full presence state has been updated
  • join — a new client has started tracking presence
  • leave — a client has stopped tracking presence

The complete presence state returned by presenceState() looks like this:

1
{
2
"client_key_1": [{ "userId": 1, "typing": false }],
3
"client_key_2": [{ "userId": 2, "typing": true }]
4
}

Initialize the client#

Get the Project URL and key from the project's Connect dialog.

1
import { } from '@supabase/supabase-js'
2
3
const = 'https://<project>.supabase.co'
4
const = '<sb_publishable_... or anon key>'
5
6
const = (, )

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:

1
const = .('room_01')
2
3
4
.('presence', { : 'sync' }, () => {
5
const = .()
6
.('sync', )
7
})
8
.('presence', { : 'join' }, ({ , }) => {
9
.('join', , )
10
})
11
.('presence', { : 'leave' }, ({ , }) => {
12
.('leave', , )
13
})
14
.()

Sending state#

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

1
const = .('room_01')
2
3
const = {
4
: 'user-1',
5
: new ().(),
6
}
7
8
.(async () => {
9
if ( !== 'SUBSCRIBED') { return }
10
11
const = await .()
12
.()
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.

1
const = async () => {
2
const = await .()
3
.()
4
}
5
6
()

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.

1
import { } from '@supabase/supabase-js'
2
const = ('SUPABASE_URL', 'SUPABASE_PUBLISHABLE_KEY')
3
4
const = .('test', {
5
: {
6
: {
7
: 'userId-123',
8
},
9
},
10
})