Supabase Made Easy: Your First Steps to Building with Open Source Firebase Alternative

Realtime Presence: Knowing Who's Online

In modern applications, understanding user presence – knowing who is online and active – is crucial for features like chat indicators, live collaboration, and even showing user activity. Supabase's Realtime subscriptions offer a powerful and straightforward way to implement presence tracking.

The core idea behind Supabase presence is to leverage the realtime connection. When a user connects to Supabase's realtime, they are considered 'present'. When they disconnect, they are no longer present. Supabase provides built-in events and an API to manage and subscribe to these presence changes.

Let's break down how to implement this:

  1. Setting up a Presence Channel:

    To track presence, you'll typically subscribe to a specific channel. This channel acts as a broadcast for presence events related to a particular context, like a specific chat room or a document.

const channel = supabase.channel('presence_channel', {
  config: {
    presence: {
      key: 'user_id'
    }
  }
});

In this code, presence_channel is the name of our channel. The presence: { key: 'user_id' } configuration is vital. It tells Supabase how to uniquely identify each presence entry. In most cases, this will be a user ID.

  1. Subscribing to Presence Events:

    Once the channel is set up, you can subscribe to various presence-related events:

  • 'presence': This event fires whenever the presence status of any user in the channel changes (someone joins or leaves).
  • 'sync': This event fires when the initial list of currently present users is sent after joining the channel.
  • 'join': This event fires specifically when a new user joins the channel.
  • 'leave': This event fires when a user leaves the channel.
チャプターへ戻る