Supabase Realtime
Supabase Realtime enables you to listen to database changes, broadcast messages between clients, and track user presence - all in real-time using WebSockets.
β‘ Realtime Features
- Postgres Changes: Listen to database INSERT, UPDATE, DELETE
- Broadcast: Send messages between connected clients
- Presence: Track online users and their state
Postgres Changes
Subscribe to database changes in real-time:
// Subscribe to all changes on a table
const channel = supabase
.channel('posts-changes')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'posts' },
(payload) => {
console.log('Change:', payload)
}
)
.subscribe()
// Subscribe to specific events
const channel = supabase
.channel('new-posts')
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'posts' },
(payload) => {
console.log('New post:', payload.new)
}
)
.subscribe()
Filter Changes
// Only listen to changes for a specific user
const channel = supabase
.channel('user-posts')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'posts',
filter: 'user_id=eq.user-123'
},
(payload) => {
console.log('User post changed:', payload)
}
)
.subscribe()
Broadcast
Send messages directly between connected clients:
// Create a channel
const channel = supabase.channel('room-1')
// Listen for messages
channel.on('broadcast', { event: 'cursor' }, (payload) => {
console.log('Cursor moved:', payload)
})
// Subscribe to the channel
channel.subscribe((status) => {
if (status === 'SUBSCRIBED') {
// Send a message
channel.send({
type: 'broadcast',
event: 'cursor',
payload: { x: 100, y: 200 }
})
}
})
Presence
Track who's online and their current state:
const channel = supabase.channel('online-users')
// Track presence changes
channel.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState()
console.log('Online users:', state)
})
channel.on('presence', { event: 'join' }, ({ key, newPresences }) => {
console.log('User joined:', newPresences)
})
channel.on('presence', { event: 'leave' }, ({ key, leftPresences }) => {
console.log('User left:', leftPresences)
})
// Subscribe and track your presence
channel.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({
user_id: 'user-123',
username: 'john_doe',
online_at: new Date().toISOString()
})
}
})
React Realtime Hook
import { useEffect, useState } from 'react'
import { supabase } from './supabase'
function useRealtimePosts() {
const [posts, setPosts] = useState([])
useEffect(() => {
// Fetch initial posts
supabase.from('posts').select('*').then(({ data }) => {
setPosts(data || [])
})
// Subscribe to changes
const channel = supabase
.channel('posts')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'posts' },
(payload) => {
if (payload.eventType === 'INSERT') {
setPosts(prev => [...prev, payload.new])
} else if (payload.eventType === 'DELETE') {
setPosts(prev => prev.filter(p => p.id !== payload.old.id))
} else if (payload.eventType === 'UPDATE') {
setPosts(prev => prev.map(p =>
p.id === payload.new.id ? payload.new : p
))
}
}
)
.subscribe()
return () => {
supabase.removeChannel(channel)
}
}, [])
return posts
}
Cleanup
// Unsubscribe from a channel
await supabase.removeChannel(channel)
// Unsubscribe from all channels
await supabase.removeAllChannels()
π‘ Key Takeaways
- β’ Postgres Changes listens to database INSERT/UPDATE/DELETE
- β’ Broadcast sends messages between connected clients
- β’ Presence tracks online users and their state
- β’ Always cleanup subscriptions when components unmount
π Learn More
-
Realtime Documentation β
Complete guide to Supabase Realtime features.
-
Postgres Changes Guide β
Listen to database changes in real-time.