Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 31 ยท Supabase Postgres Database

Supabase Realtime and Postgres Changes

Use Supabase Realtime channels for database change events, broadcast messages and presence, and learn how publications and RLS affect who hears what.

Many apps need to feel alive: a new message appears without a refresh, a cursor moves, a badge shows who is online. Supabase Realtime is the part of the platform that pushes events to connected browsers over WebSockets. You subscribe to a channel, and the server sends you what happened.

Realtime offers three different features that share one connection: Postgres Changes (events from your tables), Broadcast (short messages between clients) and Presence (shared "who is here" state). In this lesson you will see the real supabase-js code, which is read-only because it needs a project, and then run a stand-in channel that shows how broadcast and presence work. The stand-in is ours and is far simpler than the real service. If you know Firebase, compare it with Realtime Listeners and Offline Support.

One socket, three features

Postgres Changes Row inserts, updates and deletes from your tables.
Broadcast Small messages sent from one client to the others.
Presence Who is online and what they are doing.

Pick the lightest feature that does the job.

1 / 2

Channels

Everything starts with a channel. A channel is a named room. Clients that subscribe to the same name can exchange events. You create it, attach listeners, and then call subscribe().

JavaScript
// Supabase (read-only)
const channel = supabase.channel("room-1");

channel
  .on("broadcast", { event: "cursor" }, (payload) => {
    console.log("cursor moved", payload);
  })
  .subscribe((status) => {
    console.log(status);   // SUBSCRIBED, CHANNEL_ERROR, TIMED_OUT, CLOSED
  });

// Later, when the component goes away
await supabase.removeChannel(channel);

Always remove a channel you no longer need. Open channels keep a connection busy, and a page that creates a new channel on every render will leak subscriptions.

Postgres Changes

With Postgres Changes the database tells you when rows change. Internally, Postgres writes every change to its write-ahead log, and Realtime reads that log through logical replication. A table only takes part if it belongs to a publication named supabase_realtime.

SQL
-- Supabase SQL editor (read-only)
alter publication supabase_realtime add table public.messages;

The dashboard has a toggle that does the same thing for each table. Then you listen from the client:

JavaScript
// Supabase (read-only)
const channel = supabase
  .channel("messages-feed")
  .on(
    "postgres_changes",
    { event: "INSERT", schema: "public", table: "messages", filter: "room_id=eq.7" },
    (payload) => {
      console.log("new row:", payload.new);
    }
  )
  .on(
    "postgres_changes",
    { event: "*", schema: "public", table: "messages" },
    (payload) => {
      console.log(payload.eventType, payload.old, payload.new);
    }
  )
  .subscribe();

The payload has eventType, the new row in new, and the previous row in old. For updates and deletes, old contains only the primary key unless the table uses replica identity full, which logs the whole old row at some extra cost. The filter is a simple comparison such as room_id=eq.7; it is not a full SQL where.

Row Level Security applies

Realtime does not bypass your security. When a table has Row Level Security turned on, a client only receives changes for rows its policies let it select. That is good news, but note two limits:

  • Delete events cannot be checked against the deleted row, so they are not filtered by RLS. Do not put secrets in primary keys.
  • Every change is checked against each subscriber's policies, so a table with many listeners and heavy policies costs more. Keep policies cheap.

So the rule of thumb is: write a proper select policy first, then add the table to the publication.

Broadcast

Broadcast is for messages that do not belong in the database: cursor positions, "typing..." hints, game moves, or a ping to tell others to refetch. A client sends, the server relays, every other subscriber receives.

JavaScript
// Supabase (read-only)
const room = supabase.channel("room-1", {
  config: { broadcast: { self: false, ack: true } },
});

room
  .on("broadcast", { event: "typing" }, ({ payload }) => {
    console.log(payload.user, "is typing");
  })
  .subscribe(async (status) => {
    if (status === "SUBSCRIBED") {
      await room.send({ type: "broadcast", event: "typing", payload: { user: "ana" } });
    }
  });

self: false means you do not receive your own messages, and ack: true makes send wait for the server to confirm. Broadcast messages are not stored. A client that joins later never sees what was sent before. If history matters, write a row too and use Postgres Changes, or fetch it on load.

Channels can also be private, which uses policies on the realtime.messages table to decide who may join and send. Public channels let anyone with your public key join, so use private channels for anything sensitive.

Presence

Presence keeps a small piece of state for each connected client and shares the merged result with everyone. When a client joins, updates its state or disconnects, all others get sync, join and leave events.

JavaScript
// Supabase (read-only)
const room = supabase.channel("room-1", {
  config: { presence: { key: "user-ana" } },
});

room
  .on("presence", { event: "sync" }, () => {
    const state = room.presenceState();
    console.log(Object.keys(state));          // who is here
  })
  .on("presence", { event: "join" }, ({ key, newPresences }) => {
    console.log(key, "joined", newPresences);
  })
  .on("presence", { event: "leave" }, ({ key }) => {
    console.log(key, "left");
  })
  .subscribe(async (status) => {
    if (status === "SUBSCRIBED") {
      await room.track({ name: "Ana", status: "online" });
    }
  });

track() sets your state, and untrack() or closing the tab removes it. The server notices lost connections by missed heartbeats, so a leave can arrive a few seconds late. Presence state is held in memory on the server, never in your tables.

A stand-in channel

The real service runs on servers with WebSockets. The stand-in below is a tiny in-memory hub with the same shape: channel(name), .on(...), .subscribe(), .send(), .track() and .untrack(). It shows the key behaviors: broadcast reaches the others and not yourself, a late joiner misses old messages, and presence keeps merged state and emits join and leave.

JS Stand-in channel with broadcast and presence

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the sender never hears its own message, and that leave removes the member from the merged state. The real service adds networking, heartbeats, authorization and scaling, but the mental model is the same.

A second stand-in shows what a publication does: only tables on the list produce change events, and a policy function decides who may see each row.

JS Stand-in change feed with a publication and a policy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ana belongs to both rooms and hears both inserts. Ben belongs only to room 2, so the first insert never reaches him. The orders table is not in the publication, so it produces nothing at all.

Choosing the right feature

Need Use
Show new rows that are saved anyway Postgres Changes
Cursors, typing hints, game moves Broadcast
Online list, "viewing this page" Presence
Keep history Rows in a table, then Postgres Changes

A common pattern is hybrid: write the message to a table (so it is durable and protected by RLS), listen with Postgres Changes, and use Broadcast and Presence only for the throwaway signals around it. Always load the current data with a normal query first, then subscribe, because events only describe what changes from now on.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must be true for a table to send Postgres Changes events?

    Realtime reads the logical replication stream, which only includes tables that belong to the publication.
  2. 2. A client joins a Broadcast channel late. What does it receive?

    Broadcast messages are relayed, not stored. Use a table when history matters.
  3. 3. How does Row Level Security affect Postgres Changes?

    Realtime checks each change against the subscriber's policies. Delete events are an exception, because the deleted row cannot be checked.
  4. 4. Where does Presence state live?

    Presence is ephemeral state tracked by the server for connected clients. It disappears when they leave.

Summary

  • A channel is a named room; create it, attach listeners with .on(), call .subscribe() and remove it when done.
  • Postgres Changes needs the table in the supabase_realtime publication and respects your RLS select policies.
  • Broadcast relays short messages between clients without storing them; late joiners miss earlier ones.
  • Presence shares small per-client state with track() and fires sync, join and leave.
  • Load current data with a query, then subscribe for changes; combine tables with Broadcast and Presence as needed.

Next: Firestore Security Rules