Connection
import { RealtimeClient } from '@supabase/realtime-js'
Import the Realtime client library
const client = new RealtimeClient('https://your-project.supabase.co/realtime/v1', { apikey: 'your-anon-key' })
Create a new Realtime client
client.connect()
Connect to the Realtime server
Channel Operations
const channel = client.channel('room-1')
Create a new channel
channel.subscribe()
Subscribe to a channel
channel.unsubscribe()
Unsubscribe from a channel
Event Listening
channel.on('INSERT', { event: '*' }, (payload) => { console.log(payload) })
Listen for all INSERT events
channel.on('UPDATE', { event: 'table-name' }, (payload) => { console.log(payload) })
Listen for UPDATE events on a specific table
channel.on('DELETE', { event: 'table-name:id=eq.1' }, (payload) => { console.log(payload) })
Listen for DELETE events with filter
Presence
channel.track({ user: 1, online_at: new Date().toISOString() })
Track presence state for current client
channel.untrack()
Remove presence state for current client
channel.on('presence', { event: 'sync' }, () => { const state = channel.presenceState() })
Listen for presence sync events
Broadcast
channel.send({ type: 'broadcast', event: 'custom-event', payload: { message: 'hello' } })
Send a broadcast message to all clients in the channel
Error Handling
client.onError((e) => console.log('Error:', e))
Listen for connection errors
channel.on('error', (error) => console.log('Channel error:', error))
Listen for channel errors
Disconnection
client.disconnect()
Disconnect from the Realtime server