Skip to content

Updated

Postgres Changes

Use Realtime's Postgres Changes to listen to database events.

Quick start

This example creates a table, secures it with Row Level Security, and subscribes to every change with the Supabase JavaScript client.

1
Set up a Supabase project with a 'todos' table

Create a new project in the Supabase Dashboard.

After your project is ready, create a table in your Supabase database. You can do this with either the Table interface or the SQL Editor.

-- Create a table called "todos"
-- with a column to store tasks.
create table todos (
id serial primary key,
task text
);
2
Allow anonymous access

Turn on Row Level Security for the table and let anonymous users read it. To give each signed-in user only their own rows, see Let signed-in users read their own rows.

-- Grant the privileges roles need
grant select on public.todos to anon;
-- Turn on security
alter table "todos"
enable row level security;
-- Allow anonymous access
create policy "Allow anonymous access"
on todos
for select
to anon
using (true);
3
Add the table to the publication

Go to your project's Publications settings, and under supabase_realtime, toggle on the tables you want to listen to. If changes still don't arrive, see Postgres Changes troubleshooting.

Or add the table with SQL:

alter publication supabase_realtime
add table todos;
4
Install the client

Install the Supabase JavaScript client.

npm install @supabase/supabase-js
5
Create the client

Use this client to subscribe to Postgres Changes.

import { } from '@supabase/supabase-js'
const = (
'https://<project>.supabase.co',
'<sb_publishable_... key>'
)
6
Listen to changes by schema

Listen to changes on all tables in the public schema by setting schema to public and event to *. The event can be one of:

  • INSERT
  • UPDATE
  • DELETE
  • *

The channel name can be any string except 'realtime'.

const =
.('schema-db-changes')
.(
'postgres_changes',
{
: '*',
: 'public',
},
() => .()
)
.()
7
Insert a sample row

Insert a row. The channelA handler logs the change.

insert into todos (task)
values
('Change!');

Prepare a table

A table's changes reach a subscriber only when the table has all three of the following. The quick start sets up the first two for the anon role.

RequirementHow to set itWithout it
Membership in the supabase_realtime publicationalter publication supabase_realtime add table YOUR_TABLE;The server refuses the subscription with Unable to subscribe to changes with given parameters.
Read access for the subscriber's role: a select grant and, with Row Level Security on, a select policygrant select on YOUR_TABLE to authenticated;, then a policy such as the one in Let signed-in users read their own rowsWithout the policy, inserts and updates never arrive and no error appears. Without the grant, events arrive as Error 401: Unauthorized.
Replica identity full, for previous values and filtered deletesalter table YOUR_TABLE replica identity full;old on an UPDATE holds only the primary key, and a DELETE filtered on a column other than the primary key never arrives.

If changes still don't arrive, see Postgres Changes troubleshooting.

Let signed-in users read their own rows

Realtime sends an INSERT or UPDATE only to a subscriber whose role can read the row. DELETE events are the exception, because Realtime can't apply RLS to them. See Receive old records. Signed-in users subscribe as the authenticated role, so the quick start's anon policy sends them nothing. Give authenticated a policy that matches only each user's rows:

-- Store the owner of each row
alter table todos
add column user_id uuid references auth.users default auth.uid();
grant select on public.todos to authenticated;
create policy "Users can read their own todos"
on todos
for select
to authenticated
using ((select auth.uid()) = user_id);

The user_id default fills in the signed-in user's ID only for rows inserted in an authenticated request. A row inserted in the SQL Editor, including the quick start's sample row, has no owner, so no signed-in user receives it. To test, assign an owner to one existing row, or insert one with an owner. Replace 1 with the ID of your test row and USER_ID with a user's ID from the Users page:

update todos
set user_id = 'USER_ID'
where id = 1 and user_id is null;
insert into todos (task, user_id)
values ('Change!', 'USER_ID');

The quick start's anonymous access still applies after you add this policy, so anyone can read every row without signing in. To make the table private, remove it:

drop policy "Allow anonymous access" on todos;
revoke select on public.todos from anon;

A policy with using (true) sends every row to every signed-in user.

Sign the user in before you subscribe. The client sends the user's access token to Realtime, which checks the policy as that user.

Usage

You can use the Supabase client libraries to subscribe to database changes.

Listen to a schema

Subscribe to specific schema events using the schema parameter:

const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
schema: 'public', // Subscribes to the "public" schema in Postgres
event: '*', // Listen to all changes
},
(payload) => console.log(payload)
)
.subscribe()
supabase
.channel('schema-db-changes')
.onPostgresChanges(
schema: 'public', // Subscribes to the "public" schema in Postgres
event: PostgresChangeEvent.all, // Listen to all changes
callback: (payload) => print(payload))
.subscribe();
let myChannel = await supabase.channel("schema-db-changes")
let changes = await myChannel.postgresChange(AnyAction.self, schema: "public")
await myChannel.subscribe()
for await change in changes {
switch change {
case .insert(let action): print(action)
case .update(let action): print(action)
case .delete(let action): print(action)
case .select(let action): print(action)
}
}
val myChannel = supabase.channel("schema-db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction>(schema = "public")
changes
.onEach {
when(it) { //You can also check for <is PostgresAction.Insert>, etc.. manually
is HasRecord -> println(it.record)
is HasOldRecord -> println(it.oldRecord)
else -> println(it)
}
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"*",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
var channel = supabase.Realtime.Channel("schema-db-changes");
// Subscribes to the "public" schema in Postgres
channel.Register(new PostgresChangesOptions("public"));
channel.AddPostgresChangeHandler(ListenType.All, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();

The channel name can be any string except 'realtime'.

Listen to specific events

Use the event parameter to listen only to a specific database event. event can be INSERT, UPDATE, DELETE, or * to listen to all changes.

const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'DELETE',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.update,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.delete,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();

Pass the action type to select the event.

let myChannel = await supabase.channel("schema-db-changes")
let changes = await myChannel.postgresChange(InsertAction.self, schema: "public")
await myChannel.subscribe()
for await change in changes {
print(change.record)
}
let myChannel = await supabase.channel("schema-db-changes")
let changes = await myChannel.postgresChange(UpdateAction.self, schema: "public")
await myChannel.subscribe()
for await change in changes {
print(change.record)
}
let myChannel = await supabase.channel("schema-db-changes")
let changes = await myChannel.postgresChange(DeleteAction.self, schema: "public")
await myChannel.subscribe()
for await change in changes {
print(change.oldRecord)
}
let myChannel = await supabase.channel("schema-db-changes")
let changes = await myChannel.postgresChange(AnyAction.self, schema: "public")
await myChannel.subscribe()
for await change in changes {
switch change {
case .insert(let action): print(action.record)
case .update(let action): print(action.record)
case .delete(let action): print(action.oldRecord)
case .select(let action): print(action.record)
}
}

Pass the action type to select the event.

val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Insert>(schema = "public")
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Update>(schema = "public")
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Delete>(schema = "public")
changes
.onEach {
println(it.oldRecord)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction>(schema = "public")
changes
.onEach {
when (it) { //You can also check for <is PostgresAction.Insert>, etc.. manually
is HasRecord -> println(it.record)
is HasOldRecord -> println(it.oldRecord)
else -> println(it)
}
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"INSERT",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"UPDATE",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"DELETE",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"*",
schema="public",
callback=lambda payload: print(payload)
).subscribe()

Pass the ListenType to select the event.

var channel = supabase.Realtime.Channel("schema-db-changes");
channel.Register(new PostgresChangesOptions("public", eventType: ListenType.Inserts));
channel.AddPostgresChangeHandler(ListenType.Inserts, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();
var channel = supabase.Realtime.Channel("schema-db-changes");
channel.Register(new PostgresChangesOptions("public", eventType: ListenType.Updates));
channel.AddPostgresChangeHandler(ListenType.Updates, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();
var channel = supabase.Realtime.Channel("schema-db-changes");
channel.Register(new PostgresChangesOptions("public", eventType: ListenType.Deletes));
channel.AddPostgresChangeHandler(ListenType.Deletes, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();
var channel = supabase.Realtime.Channel("schema-db-changes");
channel.Register(new PostgresChangesOptions("public", eventType: ListenType.All));
channel.AddPostgresChangeHandler(ListenType.All, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();

Listen to a table

Subscribe to specific table events using the table parameter:

const changes = supabase
.channel('table-db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'todos',
},
(payload) => console.log(payload)
)
.subscribe()
supabase
.channel('table-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'todos',
callback: (payload) => print(payload))
.subscribe();
let myChannel = await supabase.channel("db-changes")
let changes = await myChannel.postgresChange(AnyAction.self, schema: "public", table: "todos")
await myChannel.subscribe()
for await change in changes {
switch change {
case .insert(let action): print(action)
case .update(let action): print(action)
case .delete(let action): print(action)
case .select(let action): print(action)
}
}
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction>(schema = "public") {
table = "todos"
}
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
changes = supabase.channel('db-changes').on_postgres_changes(
"UPDATE",
schema="public",
table="todos",
callback=lambda payload: print(payload)
).subscribe()
var channel = supabase.Realtime.Channel("table-db-changes");
channel.Register(new PostgresChangesOptions("public", "todos"));
channel.AddPostgresChangeHandler(ListenType.All, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();

Listen to multiple changes

To listen to different events and schema/tables/filters combinations with the same channel:

const channel = supabase
.channel('db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'messages',
},
(payload) => console.log(payload)
)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'users',
},
(payload) => console.log(payload)
)
.subscribe()
supabase
.channel('db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'messages',
callback: (payload) => print(payload))
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
table: 'users',
callback: (payload) => print(payload))
.subscribe();
let myChannel = await supabase.channel("db-changes")
let messageChanges = await myChannel.postgresChange(AnyAction.self, schema: "public", table: "messages")
let userChanges = await myChannel.postgresChange(InsertAction.self, schema: "public", table: "users")
await myChannel.subscribe()
val myChannel = supabase.channel("db-changes")
val messageChanges = myChannel.postgresChangeFlow<PostgresAction>(schema = "public") {
table = "messages"
}
val userChanges = myChannel.postgresChangeFlow<PostgresAction.Insert>(schema = "public") {
table = "users"
}
myChannel.subscribe()
changes = supabase.channel('db-changes').on_postgres_changes(
"*",
schema="public",
table="messages",
callback=lambda payload: print(payload)
).on_postgres_changes(
"INSERT",
schema="public",
table="users",
callback=lambda payload: print(payload)
).subscribe()
var channel = supabase.Realtime.Channel("db-changes");
channel.Register(new PostgresChangesOptions("public", "messages"));
channel.Register(new PostgresChangesOptions("public", "users", eventType: ListenType.Inserts));
channel.AddPostgresChangeHandler(ListenType.All, (sender, change) => Console.WriteLine(change.Payload));
channel.AddPostgresChangeHandler(ListenType.Inserts, (sender, change) => Console.WriteLine(change.Payload));
await channel.Subscribe();

Filter changes

Use the filter parameter for granular changes:

const changes = supabase
.channel('table-filter-changes')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'todos',
filter: 'id=eq.1',
},
(payload) => console.log(payload)
)
.subscribe()
supabase
.channel('table-filter-changes')
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
table: 'todos',
filter: PostgresChangeFilter(
type: PostgresChangeFilterType.eq,
column: 'id',
value: 1,
),
callback: (payload) => print(payload))
.subscribe();
let myChannel = await supabase.channel("db-changes")
let changes = await myChannel.postgresChange(
InsertAction.self,
schema: "public",
table: "todos",
filter: .eq("id", value: 1)
)
await myChannel.subscribe()
for await change in changes {
print(change.record)
}
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Insert>(schema = "public") {
table = "todos"
filter = "id=eq.1"
}
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
changes = supabase.channel('db-changes').on_postgres_changes(
"INSERT",
schema="public",
table="todos",
filter="id=eq.1",
callback=lambda payload: print(payload)
).subscribe()
var channel = supabase.Realtime.Channel("table-filter-changes");
channel.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts, "id=eq.1"));
channel.AddPostgresChangeHandler(ListenType.Inserts, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();

Available filters

A filter is a column=operator.value expression, such as id=eq.1, that Realtime evaluates on the server. For every operator, with examples for each client library, see Postgres Changes filters.

Select specific columns

By default each change event contains the full row. Use select to receive only a subset of columns instead. This reduces payload size and the data transferred per event, which is especially useful for tables with large bytea, jsonb, or text columns.

The listed columns must be selectable by the subscribing role, and the table's primary key is always included so you can identify the row. select requires an explicit schema and table — it's not supported on wildcard subscriptions.

const channel = supabase
.channel('changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'profiles',
select: ['id', 'username'], // payload.new only contains { id, username }
},
(payload) => console.log(payload)
)
.subscribe()
supabase
.channel('changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'profiles',
select: ['id', 'username'],
callback: (payload) => print(payload))
.subscribe();
let myChannel = await supabase.channel("db-changes")
let changes = await myChannel.postgresChange(
AnyAction.self,
schema: "public",
table: "profiles",
select: ["id", "username"]
)
await myChannel.subscribe()
changes = supabase.channel('changes').on_postgres_changes(
"*",
schema="public",
table="profiles",
select=["id", "username"],
callback=lambda payload: print(payload)
).subscribe()

Receive old records

By default, old on an UPDATE or DELETE event holds only the primary key. To receive the whole previous row in old, set the table's replica identity to full:

alter table
todos replica identity full;

Private schemas

Postgres Changes works out of the box for tables in the public schema. You can listen to tables in your private schemas by granting the database role found in your access token USAGE on the schema and SELECT on the table. Without USAGE, Realtime can't resolve the table when it checks RLS as that role. You can run queries similar to the following:

grant usage on schema "non_private_schema" to authenticated;
grant select on "non_private_schema"."some_table" to authenticated;

Custom tokens

You may choose to sign your own tokens to customize claims that can be checked in your RLS policies.

Your project JWT secret is found in the Settings > API keys section of the Dashboard.

To use your own JWT with Realtime make sure to set the token after instantiating the Supabase client and before connecting to a Channel.

const { createClient } = require('@supabase/supabase-js')
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY, {})
// Set your custom JWT here
supabase.realtime.setAuth('your-custom-jwt')
const channel = supabase
.channel('db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'messages',
filter: 'body=eq.bye',
},
(payload) => console.log(payload)
)
.subscribe()
supabase.realtime.setAuth('your-custom-jwt');
supabase
.channel('db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'messages',
filter: PostgresChangeFilter(
type: PostgresChangeFilterType.eq,
column: 'body',
value: 'bye',
),
callback: (payload) => print(payload),
)
.subscribe();
await supabase.realtime.setAuth("your-custom-jwt")
let myChannel = await supabase.channel("db-changes")
let changes = await myChannel.postgresChange(
UpdateAction.self,
schema: "public",
table: "products",
filter: "name=in.(red,blue,yellow)"
)
await myChannel.subscribe()
for await change in changes {
print(change.record)
}
val supabase = createSupabaseClient(supabaseUrl, supabaseKey) {
install(Realtime) {
jwtToken = "your-custom-jwt"
}
}
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Update>(schema = "public") {
table = "products"
filter = "name=in.(red,blue,yellow)"
}
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
supabase.realtime.set_auth('your-custom-jwt')
changes = supabase.channel('db-changes').on_postgres_changes(
"UPDATE",
schema="public",
table="products",
filter="name=in.(red,blue,yellow)",
callback=lambda payload: print(payload)
).subscribe()
// Set your custom JWT after instantiating the client and before subscribing to a channel
supabase.Realtime.SetAuth("your-custom-jwt");
var channel = supabase.Realtime.Channel("db-changes");
channel.Register(new PostgresChangesOptions("public", "messages", ListenType.All, "body=eq.bye"));
channel.AddPostgresChangeHandler(ListenType.All, (sender, change) =>
{
Console.WriteLine(change.Payload);
});
await channel.Subscribe();

Limitations

Delete events

You can filter DELETE events only when the table's replica identity is full. See Receive old records.

Scaling Postgres Changes

Postgres Changes authorizes every event against each subscriber. When you make a single change to a table with 100 subscribed users, Realtime performs 100 authorization checks — one per user — so throughput scales with the number of subscribers, not the write rate. Changes are also processed on a single thread to preserve their order, which means larger compute add-ons don't meaningfully increase Postgres Changes throughput.

For most applications this is plenty. To get the best performance:

Use the estimator below to gauge the maximum throughput for your instance, and run your own benchmarks to confirm it fits your use case:

If you're unsure which approach fits your use case, reach out through the Support Form — our engineers are happy to help you find the best solution.

Next steps

To keep going, use these pages: