Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 31 ยท Real-World Projects

Project: Chat App with Presence

Design a chat app with rooms, messages, presence, pagination and security rules or RLS, with read-only SDK code and a runnable stand-in chat engine.

A chat app combines almost every realtime idea in one product: messages that must be saved, a feed that updates live, a list of who is online, history you can scroll back through, and rules that keep private rooms private. It is also an honest test of your data model, because chat grows fast.

In this project you will design the data, see the read-only SDK versions for Firebase and Supabase, and run a stand-in chat engine in JavaScript that has rooms, membership checks, presence, live delivery and cursor-based pagination. The engine is our own simplification: it shows the logic, not the real services, which need accounts and servers.

Four jobs of a chat app

Messages Saved, ordered, secured.
Rooms Only members get in.
Presence Who is online right now.
History Load older pages on demand.

Durable data and throwaway signals use different tools.

1 / 2

Durable versus ephemeral

The first design decision is what belongs in the database and what does not.

  • Messages must survive reloads and be seen by people who join later. They are rows or documents.
  • Presence ("Ana is online") and typing hints are short-lived. They belong in realtime channel state, not in your tables. Writing "online" to a document every few seconds is slow and costly.

Supabase has Presence and Broadcast built into Realtime (see Supabase Realtime and Postgres Changes). Firestore has no presence feature, so Firebase apps usually use the Realtime Database with its onDisconnect handler for online status, and Firestore for messages. Check the current Firebase documentation for the exact presence recipe; the key idea is that the server, not the client, clears your status when the connection drops.

Data model

Supabase

SQL
-- Supabase (read-only)
create table rooms (
  id         bigint generated always as identity primary key,
  name       text not null,
  is_private boolean not null default true
);

create table room_members (
  room_id bigint not null references rooms(id) on delete cascade,
  user_id uuid   not null references auth.users(id) on delete cascade,
  primary key (room_id, user_id)
);

create table messages (
  id         bigint generated always as identity primary key,
  room_id    bigint not null references rooms(id) on delete cascade,
  user_id    uuid   not null default auth.uid() references auth.users(id),
  body       text   not null check (char_length(body) between 1 and 2000),
  created_at timestamptz not null default now()
);

create index messages_room_id_id on messages (room_id, id desc);

The composite index on (room_id, id desc) makes "the latest messages of one room" fast, which is the query you run constantly.

Firebase

JavaScript
// Firebase (read-only)
// rooms/{roomId}                      { name, memberIds: ["uidA", "uidB"] }
// rooms/{roomId}/messages/{messageId} { uid, text, createdAt }

Messages live in a subcollection because a room's history is unbounded. The room document keeps a small memberIds array so rules can check membership with one read. For big public rooms you would use a members subcollection instead, as in Multi-Tenant and Team Apps.

Security

Chat is a classic place for leaks, since "a message in a private room" is exactly what an attacker wants.

SQL
-- Supabase (read-only)
alter table messages enable row level security;

create policy "members read messages" on messages for select to authenticated
  using ( exists (
    select 1 from room_members m
    where m.room_id = messages.room_id and m.user_id = (select auth.uid())
  ));

create policy "members send as themselves" on messages for insert to authenticated
  with check (
    user_id = (select auth.uid())
    and exists (
      select 1 from room_members m
      where m.room_id = messages.room_id and m.user_id = (select auth.uid())
    )
  );
Text
// firestore.rules (read-only)
match /rooms/{roomId}/messages/{messageId} {
  allow read: if request.auth != null
    && request.auth.uid in get(/databases/$(database)/documents/rooms/$(roomId)).data.memberIds;
  allow create: if request.auth != null
    && request.auth.uid in get(/databases/$(database)/documents/rooms/$(roomId)).data.memberIds
    && request.resource.data.uid == request.auth.uid
    && request.resource.data.text is string
    && request.resource.data.text.size() <= 2000;
  allow update, delete: if false;
}

Notice two safeguards: the sender field must equal the caller (so nobody posts as someone else), and edits and deletes are denied. Both platforms need the rules in addition to the UI; see Firestore Security Rules and Row Level Security Policies.

Sending, listening and paging

JavaScript
// Supabase (read-only)
// 1. load the latest page, newest first
const { data: page } = await supabase
  .from("messages")
  .select("id, user_id, body, created_at")
  .eq("room_id", roomId)
  .order("id", { ascending: false })
  .limit(30);

// 2. older page: use the smallest id you have as a cursor
const { data: older } = await supabase
  .from("messages")
  .select("id, user_id, body, created_at")
  .eq("room_id", roomId)
  .lt("id", oldestIdLoaded)
  .order("id", { ascending: false })
  .limit(30);

// 3. live inserts
supabase
  .channel(`room-${roomId}`)
  .on("postgres_changes",
      { event: "INSERT", schema: "public", table: "messages", filter: `room_id=eq.${roomId}` },
      (payload) => addToScreen(payload.new))
  .subscribe();
JavaScript
// Firebase (read-only)
const first = query(
  collection(db, "rooms", roomId, "messages"),
  orderBy("createdAt", "desc"),
  limit(30)
);
const unsubscribe = onSnapshot(first, (snap) => render(snap.docs));

// older page: continue after the last document of the previous page
const next = query(
  collection(db, "rooms", roomId, "messages"),
  orderBy("createdAt", "desc"),
  startAfter(lastDoc),
  limit(30)
);

Both use cursor pagination: "give me 30 messages older than this one". Never use page numbers or offsets for chat. New messages arrive all the time, so offsets shift and you would see duplicates or gaps. Cursors are covered in Queries, Indexes and Pagination.

For presence, Supabase would call channel.track({ name }) on a presence channel for the room, and read presenceState() to draw the online list.

The stand-in chat engine

The engine below implements the whole design in memory: rooms with members, a membership check on read and send, live delivery to subscribers, presence with join and leave, and cursor pagination. Rooms, users and messages are plain arrays and objects. Run it and read the output line by line.

JS Stand-in chat engine with presence and pagination

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

No output.

Three things to notice. After stop() Ben no longer receives live messages, but the message is stored, so any member can still load it with page. Pagination uses the id as a cursor, so the second page continues exactly where the first one ended even when new messages arrive. And every operation starts with assertMember, the same idea as the RLS policy and the Firestore rule: the check happens on the server side of the boundary, not in the interface.

Presence in practice

In real apps, presence needs more than a Map:

  • Heartbeats: the server marks a client as gone after missed heartbeats, because a closed laptop never says goodbye.
  • Multiple tabs: one user can have several connections; show them as online while at least one exists.
  • Privacy: decide who can see online status. Presence state in a channel is visible to everyone in that channel.
  • Scale: broadcasting every join to a room of 10,000 people is expensive, so large rooms often show only a count.

Improvements to try

  • Show "typing..." with a broadcast signal that is never stored.
  • Add read receipts: a last_read_message_id per member (a row or field you update when the user scrolls to the bottom).
  • Limit messages per user per minute in a function; see Security Pitfalls in Both Platforms.
  • Add soft deletion (deleted_at) instead of real deletes, and let policies hide deleted rows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which data belongs in the database rather than only in a realtime channel?

    Messages are durable history. Typing hints, cursors and presence are short-lived signals.
  2. 2. Why use a cursor such as the oldest loaded id instead of page numbers?

    A cursor means older than this message, which stays correct while new messages keep arriving.
  3. 3. What must an insert policy or rule check for a chat message?

    Without both checks, outsiders could post, or members could post pretending to be someone else.
  4. 4. Why does a real presence system use heartbeats?

    Servers mark a client as gone after missed heartbeats, so the online list does not show ghosts.

Summary

  • Keep messages in the database and presence, typing and cursors in realtime channels.
  • Model rooms, membership and messages; index messages by room and id (or timestamp) for fast latest-page queries.
  • Enforce membership and sender identity in RLS policies or Firestore rules, and deny edits you do not need.
  • Paginate with cursors, never offsets, and subscribe for live inserts after loading history.
  • Real presence needs heartbeats, multi-tab handling and privacy decisions.

Next: Project: Blog with Auth, Storage and Roles