Realtime

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:


_15
begin;
_15
_15
-- remove the supabase_realtime publication
_15
drop
_15
publication if exists supabase_realtime;
_15
_15
-- re-create the supabase_realtime publication with no tables
_15
create publication supabase_realtime;
_15
_15
commit;
_15
_15
-- add a table called 'messages' to the publication
_15
-- (update this to match your tables)
_15
alter
_15
publication supabase_realtime add table messages;

Streaming inserts

You can use the INSERT event to stream all new rows.


_15
import { createClient } from '@supabase/supabase-js'
_15
_15
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)
_15
_15
const 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.


_15
import { createClient } from '@supabase/supabase-js'
_15
_15
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)
_15
_15
const 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