Subscribe to database changes with Supabase Realtime, build a live chat, and understand broadcast and presence.
Supabase wraps PostgreSQL's logical replication into a WebSocket API. Changes to any table can broadcast to subscribed clients instantly.
import { supabase } from './supabase';
// Listen to all inserts in 'messages' table
const channel = supabase
.channel('public:messages')
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'messages' },
(payload) => {
console.log('New message:', payload.new);
setMessages(prev => [...prev, payload.new]);
}
)
.subscribe();
// Cleanup on unmount
return () => supabase.removeChannel(channel);// Send
await supabase.channel('room:123').send({
type: 'broadcast',
event: 'user_typing',
payload: { userId: user.id, name: user.name }
});
// Receive
supabase.channel('room:123')
.on('broadcast', { event: 'user_typing' }, ({ payload }) => {
setTypingUsers(prev => [...prev, payload.name]);
})
.subscribe();const channel = supabase.channel('room:123');
channel
.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState();
console.log('Online users:', Object.values(state));
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({ userId: user.id, name: user.name });
}
});postgres_changes subscription fires when rows are inserted, updated, or deleted.