Files
supabase/apps/docs/content/guides/realtime/postgres-changes.mdx
Miranda Limonczenko 45b5235705 docs: pass Postgres Changes eval (#54332)
Closes DOCS-1815

## Problem

The Postgres Changes page is failing. 

The reason is this:
The Postgres Changes quick start sets up the `anon` role only. A reader
who secures the table for signed-in users gets no events and no error.
The publication step and replica identity sit in separate sections, so a
reader can miss either.

I have verified that this change fixes the issue in the Eval. 

This additionally breaks out many unused Eval lines into another topic.

## Solution

- **Prepare a table:** a new section that lists the three requirements,
how to set each, and what a reader sees without it.
- **Signed-in users:** a policy that sends each user only their own
rows.
- **Filters page:** the operator reference moves to its own page.
`#available-filters` still resolves.
- **Corrections:** the publication step names `todos`, and the old
record section says what `UPDATE` and `DELETE` carry.
- **Style and structure:** imperative headings, a description, and Next
steps.

| Site | Live | Preview | Search for |
| ---- | ---- | ------- | ---------- |
| Docs |
[/docs/guides/realtime/postgres-changes](https://supabase.com/docs/guides/realtime/postgres-changes)
|
[/docs/guides/realtime/postgres-changes](https://docs-git-docs-realtime-table-requirements-supabase.vercel.app/docs/guides/realtime/postgres-changes)
| Prepare a table |
| Docs | New page |
[/docs/guides/realtime/postgres-changes-filters](https://docs-git-docs-realtime-table-requirements-supabase.vercel.app/docs/guides/realtime/postgres-changes-filters)
| Combining filters with `AND` |

## Manual testing

1. Open the preview of `/docs/guides/realtime/postgres-changes` and go
to **Prepare a table**. The table lists three requirements.
2. Open `/docs/guides/realtime/postgres-changes#receiving-old-records`.
The page lands on **Receive old records**.
3. In the sidebar, click **Postgres Changes filters**. The page lists
all 13 operators.
2026-12-01 10:26:52 -08:00

1544 lines
37 KiB
Plaintext

---
title: 'Postgres Changes'
description: 'Listen to inserts, updates, and deletes in your Postgres tables with Supabase Realtime, and set up a table so its changes reach signed-in subscribers.'
tocVideo: _-y_Lnujq64
---
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.
<StepHikeCompact>
<StepHikeCompact.Step step={1}>
<StepHikeCompact.Details title="Set up a Supabase project with a 'todos' table">
[Create a new project](https://app.supabase.com) in the Supabase Dashboard.
After your project is ready, create a table in your [Supabase database](/docs/guides/database/overview). You can do this with either the Table interface or the [SQL Editor](https://app.supabase.com/project/_/sql).
</StepHikeCompact.Details>
<StepHikeCompact.Code>
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="sql"
queryGroup="database-method"
>
<TabPanel id="sql" label="SQL">
```sql
-- Create a table called "todos"
-- with a column to store tasks.
create table todos (
id serial primary key,
task text
);
```
</TabPanel>
<TabPanel id="dashboard" label="Dashboard">
<video width="99%" muted playsInline controls={true}>
<source
src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/api/api-create-table-sm.mp4"
type="video/mp4"
/>
</video>
</TabPanel>
</Tabs>
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={2}>
<StepHikeCompact.Details title="Allow anonymous access">
Turn on [Row Level Security](/docs/guides/database/postgres/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](#let-signed-in-users-read-their-own-rows).
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```sql
-- 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);
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={3}>
<StepHikeCompact.Details title="Add the table to the publication">
Go to your project's [Publications settings](/dashboard/project/_/database/publications), and under `supabase_realtime`, toggle on the tables you want to listen to. If changes still don't arrive, see [Postgres Changes troubleshooting](/kb/troubleshooting/realtime-postgres-changes-troubleshooting).
Or add the table with SQL:
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```sql
alter publication supabase_realtime
add table todos;
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={4}>
<StepHikeCompact.Details title="Install the client">
Install the Supabase JavaScript client.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```bash
npm install @supabase/supabase-js
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={5}>
<StepHikeCompact.Details title="Create the client">
Use this client to subscribe to Postgres Changes.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
'https://<project>.supabase.co',
'<sb_publishable_... key>'
)
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={6}>
<StepHikeCompact.Details title="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'.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('your_project_url', 'your_supabase_api_key')
// ---cut---
const channelA = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
<StepHikeCompact.Step step={7}>
<StepHikeCompact.Details title="Insert a sample row">
Insert a row. The `channelA` handler logs the change.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```sql
insert into todos (task)
values
('Change!');
```
</StepHikeCompact.Code>
</StepHikeCompact.Step>
</StepHikeCompact>
## 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.
| Requirement | How to set it | Without it |
| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Membership in the `supabase_realtime` publication | `alter 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` policy | `grant select on YOUR_TABLE to authenticated;`, then a policy such as the one in [Let signed-in users read their own rows](#let-signed-in-users-read-their-own-rows) | Without 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 deletes | `alter 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](/kb/troubleshooting/realtime-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](#receiving-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:
```sql
-- 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](/dashboard/project/_/auth/users):
```sql
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:
```sql
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:
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
{/* prettier-ignore */}
```js
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()
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
```dart
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();
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
```swift
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)
}
}
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
```kotlin
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
```python
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"*",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
```c#
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();
```
</TabPanel>
</$Show>
</Tabs>
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.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="insert"
queryGroup="pg-changes-event"
>
<TabPanel id="insert" label="Insert">
```js
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
```
</TabPanel>
<TabPanel id="update" label="Update">
```js
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
```
</TabPanel>
<TabPanel id="delete" label="Delete">
```js
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'DELETE',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
```
</TabPanel>
<TabPanel id="all" label="All events">
```js
const changes = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
},
(payload) => console.log(payload)
)
.subscribe()
```
</TabPanel>
</Tabs>
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="insert"
queryGroup="pg-changes-event"
>
<TabPanel id="insert" label="Insert">
```dart
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
```
</TabPanel>
<TabPanel id="update" label="Update">
```dart
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.update,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
```
</TabPanel>
<TabPanel id="delete" label="Delete">
```dart
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.delete,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
```
</TabPanel>
<TabPanel id="all" label="All events">
```dart
supabase
.channel('schema-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
callback: (payload) => print(payload))
.subscribe();
```
</TabPanel>
</Tabs>
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
Pass the action type to select the event.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="insert"
queryGroup="pg-changes-event"
>
<TabPanel id="insert" label="Insert">
```swift
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)
}
```
</TabPanel>
<TabPanel id="update" label="Update">
```swift
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)
}
```
</TabPanel>
<TabPanel id="delete" label="Delete">
```swift
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)
}
```
</TabPanel>
<TabPanel id="all" label="All events">
```swift
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)
}
}
```
</TabPanel>
</Tabs>
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
Pass the action type to select the event.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="insert"
queryGroup="pg-changes-event"
>
<TabPanel id="insert" label="Insert">
```kotlin
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Insert>(schema = "public")
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
```
</TabPanel>
<TabPanel id="update" label="Update">
```kotlin
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Update>(schema = "public")
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
```
</TabPanel>
<TabPanel id="delete" label="Delete">
```kotlin
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction.Delete>(schema = "public")
changes
.onEach {
println(it.oldRecord)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
```
</TabPanel>
<TabPanel id="all" label="All events">
```kotlin
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()
```
</TabPanel>
</Tabs>
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="insert"
queryGroup="pg-changes-event"
>
<TabPanel id="insert" label="Insert">
```python
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"INSERT",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
<TabPanel id="update" label="Update">
```python
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"UPDATE",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
<TabPanel id="delete" label="Delete">
```python
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"DELETE",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
<TabPanel id="all" label="All events">
```python
changes = supabase.channel('schema-db-changes').on_postgres_changes(
"*",
schema="public",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
</Tabs>
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
Pass the `ListenType` to select the event.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="insert"
queryGroup="pg-changes-event"
>
<TabPanel id="insert" label="Insert">
```c#
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();
```
</TabPanel>
<TabPanel id="update" label="Update">
```c#
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();
```
</TabPanel>
<TabPanel id="delete" label="Delete">
```c#
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();
```
</TabPanel>
<TabPanel id="all" label="All events">
```c#
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();
```
</TabPanel>
</Tabs>
</TabPanel>
</$Show>
</Tabs>
### Listen to a table
Subscribe to specific table events using the `table` parameter:
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
```js
const changes = supabase
.channel('table-db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'todos',
},
(payload) => console.log(payload)
)
.subscribe()
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
```dart
supabase
.channel('table-db-changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'todos',
callback: (payload) => print(payload))
.subscribe();
```
</TabPanel>
</$Show>
<$Show if="sdk:swfit">
<TabPanel id="swift" label="Swift">
```swift
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)
}
}
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
```kotlin
val myChannel = supabase.channel("db-changes")
val changes = myChannel.postgresChangeFlow<PostgresAction>(schema = "public") {
table = "todos"
}
changes
.onEach {
println(it.record)
}
.launchIn(yourCoroutineScope)
myChannel.subscribe()
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
```python
changes = supabase.channel('db-changes').on_postgres_changes(
"UPDATE",
schema="public",
table="todos",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
```c#
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();
```
</TabPanel>
</$Show>
</Tabs>
### Listen to multiple changes
To listen to different events and schema/tables/filters combinations with the same channel:
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
```js
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()
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
```dart
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();
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
```swift
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
```kotlin
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
```python
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
```c#
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();
```
</TabPanel>
</$Show>
</Tabs>
### Filter changes [#filtering-for-specific-changes]
Use the `filter` parameter for granular changes:
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
```js
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()
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
```dart
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();
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
```swift
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)
}
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
```kotlin
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
```python
changes = supabase.channel('db-changes').on_postgres_changes(
"INSERT",
schema="public",
table="todos",
filter="id=eq.1",
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
```c#
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();
```
</TabPanel>
</$Show>
</Tabs>
## 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](/docs/guides/realtime/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.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
```js
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()
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
```dart
supabase
.channel('changes')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'profiles',
select: ['id', 'username'],
callback: (payload) => print(payload))
.subscribe();
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
```swift
let myChannel = await supabase.channel("db-changes")
let changes = await myChannel.postgresChange(
AnyAction.self,
schema: "public",
table: "profiles",
select: ["id", "username"]
)
await myChannel.subscribe()
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
```python
changes = supabase.channel('changes').on_postgres_changes(
"*",
schema="public",
table="profiles",
select=["id", "username"],
callback=lambda payload: print(payload)
).subscribe()
```
</TabPanel>
</$Show>
</Tabs>
## Receive old records [#receiving-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`:
```sql
alter table
todos replica identity full;
```
<Admonition type="caution">
Realtime doesn't apply RLS policies to `DELETE` events, because Postgres can't check access to a row that no longer exists. On a table with RLS turned on, `old` on a `DELETE` event holds only the primary key, even with replica identity `full`.
</Admonition>
## 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:
```sql
grant usage on schema "non_private_schema" to authenticated;
grant select on "non_private_schema"."some_table" to authenticated;
```
<Admonition type="caution">
We strongly encourage you to enable RLS and create policies for tables in private schemas. Otherwise, any role you grant access to will have unfettered read access to the table.
</Admonition>
## 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**](/dashboard/project/_/settings/api-keys) section of the Dashboard.
<Admonition type="caution">
Do not expose the `service_role` token on the client because the role is authorized to bypass row-level security.
</Admonition>
To use your own JWT with Realtime make sure to set the token after instantiating the Supabase client and before connecting to a Channel.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
```js
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()
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Dart">
```dart
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();
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
```swift
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)
}
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
```kotlin
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
```python
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()
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
```c#
// 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();
```
</TabPanel>
</$Show>
</Tabs>
## Limitations
### Delete events
You can filter `DELETE` events only when the table's replica identity is `full`. See [Receive old records](#receiving-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 [filters](/docs/guides/realtime/postgres-changes-filters) and [column selection](#select-specific-columns) to send each client only the events and columns it needs.
- Keep authorization cheap with indexed [RLS policies](/docs/guides/database/postgres/row-level-security).
Use the estimator below to gauge the maximum throughput for your instance, and run your own benchmarks to confirm it fits your use case:
<RealtimeLimitsEstimator />
<Admonition type="note">
If you expect more than ~3,000 concurrent subscribers on the same changes, use [Broadcast to stream database changes](/docs/guides/realtime/subscribing-to-database-changes#using-broadcast) instead. Broadcast sends each change once and fans it out to all subscribers, so it scales to far higher connection counts than per-subscriber authorization allows.
</Admonition>
If you're unsure which approach fits your use case, reach out through the [Support Form](/dashboard/support/new) — our engineers are happy to help you find the best solution.
## Next steps
To keep going, use these pages:
- [Postgres Changes filters](/docs/guides/realtime/postgres-changes-filters): send each subscriber only the rows it needs.
- [Row Level Security](/docs/guides/database/postgres/row-level-security): write the policies that decide which changes each user receives.
- [Subscribing to database changes](/docs/guides/realtime/subscribing-to-database-changes): compare Postgres Changes with Broadcast for large numbers of subscribers.