SkillByAIOpen interactive version →

Lesson 14 / 25

Realtime Channels

Postgres changes, broadcast and presence.

Three realtime features

Clients join a channel and listen for three kinds of events. Postgres Changes streams inserts, updates and deletes from tables added to the supabase_realtime publication, and respects RLS for what each user receives. Broadcast sends low-latency messages between clients (cursors, typing indicators) without touching tables. Presence keeps a shared state of who is connected. Call subscribe() to start and removeChannel() to clean up.

Listening and broadcasting

supabase-js v2 channels.

const channel = supabase
  .channel('project-1')
  .on(
    'postgres_changes',
    { event: 'INSERT', schema: 'public', table: 'tasks', filter: 'project_id=eq.1' },
    (payload) => console.log('new task', payload.new)
  )
  .on('broadcast', { event: 'cursor' }, ({ payload }) => console.log(payload))
  .on('presence', { event: 'sync' }, () => console.log(channel.presenceState()))
  .subscribe(async (status) => {
    if (status === 'SUBSCRIBED') {
      await channel.track({ user: 'asha', online_at: new Date().toISOString() })
      await channel.send({ type: 'broadcast', event: 'cursor', payload: { x: 10, y: 20 } })
    }
  })

// when the component unmounts
// supabase.removeChannel(channel)

A radio station with three programmes

Postgres Changes is the news bulletin about the database, Broadcast is listeners calling each other, and Presence is the attendance list of who is tuned in.

Quick check: Which feature shares cursor positions between clients without writing to a table?

  • pg_cron
  • Postgres Changes
  • Storage
  • Broadcast
Answer

Broadcast — Broadcast is ephemeral messaging.