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:

begin;

-- remove the supabase_realtime publication
drop
publication if exists supabase_realtime;

-- re-create the supabase_realtime publication with no tables
create publication supabase_realtime;

commit;

-- add a table called 'messages' to the publication
-- (update this to match your tables)
alter
publication supabase_realtime add table messages;

Streaming inserts

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

import { createClient } from '@supabase/supabase-js'

const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)

const channel = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()

Streaming updates

You can use the UPDATE event to stream all updated rows.

import { createClient } from '@supabase/supabase-js'

const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)

const channel = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()

More resources