One of the most powerful features of Supabase, mirroring Firebase, is its real-time capabilities. This means your application can automatically receive updates as data changes in your database, without needing to constantly poll for new information. Supabase client libraries make setting up these real-time subscriptions incredibly straightforward.
How does it work? When you subscribe to changes on a specific table, Supabase sets up a WebSocket connection. Whenever a row in that table is inserted, updated, or deleted, Supabase broadcasts these changes over the WebSocket. Your client library then receives these events and can act upon them – perhaps by updating your UI, re-fetching data, or triggering other logic.
Let's look at how to set up a real-time subscription using the JavaScript client library. We'll subscribe to changes on a 'todos' table.
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseKey = 'YOUR_SUPABASE_ANON_KEY'
const supabase = createClient(supabaseUrl, supabaseKey)
// Subscribe to changes in the 'todos' table
const subscription = supabase.from('todos').on('*', payload => {
console.log('New data:', payload.new)
console.log('Old data:', payload.old)
console.log('Event type:', payload.eventType)
console.log('Table:', payload.table)
console.log('Schema:', payload.schema)
}).subscribe()
// To unsubscribe later:
// subscription.unsubscribe()In this example:
supabase.from('todos')targets the 'todos' table..on('*', ...)subscribes to all types of events (INSERT, UPDATE, DELETE) on that table. You can also specify event types like'INSERT','UPDATE', or'DELETE'.- The callback function receives a
payloadobject containing details about the change. payload.newwill have the new data for INSERT or UPDATE events.payload.oldwill have the old data for UPDATE or DELETE events.payload.eventTypetells you if it was an 'INSERT', 'UPDATE', or 'DELETE'..subscribe()initiates the real-time connection.- It's crucial to store the result of
.on()(which is the subscription object) so you can.unsubscribe()later to prevent memory leaks, especially in single-page applications.
You can also filter your real-time subscriptions to only receive events that match certain criteria. This is very useful for optimizing your application and reducing unnecessary updates.