Subscribing to Database Changes
Supabase allows you to subscribe to real-time changes on your database from your client application.
You can listen to database changes using the Postgres Changes extension. The following video shows how you can enable this feature for your tables.
Demo
Setup
You'll first need to create a supabase_realtime
publication and add your tables (that you want to subscribe to) to the publication:
_15begin;_15_15-- remove the supabase_realtime publication_15drop_15 publication if exists supabase_realtime;_15_15-- re-create the supabase_realtime publication with no tables_15create publication supabase_realtime;_15_15commit;_15_15-- add a table called 'messages' to the publication_15-- (update this to match your tables)_15alter_15 publication supabase_realtime add table messages;
Streaming inserts
You can use the INSERT
event to stream all new rows.
_15import { createClient } from '@supabase/supabase-js'_15_15const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)_15_15const channel = supabase_15 .channel('schema-db-changes')_15 .on(_15 'postgres_changes',_15 {_15 event: 'INSERT',_15 schema: 'public',_15 },_15 (payload) => console.log(payload)_15 )_15 .subscribe()
Streaming updates
You can use the UPDATE
event to stream all updated rows.
_15import { createClient } from '@supabase/supabase-js'_15_15const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)_15_15const channel = supabase_15 .channel('schema-db-changes')_15 .on(_15 'postgres_changes',_15 {_15 event: 'UPDATE',_15 schema: 'public',_15 },_15 (payload) => console.log(payload)_15 )_15 .subscribe()
More resources
- Learn more about the Postgres Changes extension.
- Client Libraries: