Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 31 ยท Real-World Projects

Project: Realtime Todo App

Build a realtime, per-user todo app with auth, live sync and optimistic UI, designed around a storage adapter that works with Firebase or Supabase.

A todo list is the "hello world" of BaaS apps, but a good one touches almost everything you have learned: sign-in, per-user data, security rules, realtime updates and an interface that feels instant. In this project you design one app and implement its storage twice, once for Firebase and once for Supabase, behind a tiny interface so the rest of the app does not care which one is underneath.

The real SDK versions are read-only here because they need accounts. The runnable part is a stand-in app on our Node server: an in-memory adapter, a todo store with optimistic UI, and a simulated failure that shows the rollback. Everything you run is ours, not Firebase or Supabase code.

What we are building

Sign in Each user owns their todos.
Realtime Open two tabs and both update.
Optimistic UI The list changes before the server answers.
Adapter One interface, two backends.

The UI never imports a backend SDK directly.

1 / 2

The design

The app has four small parts:

  1. Auth: an email and password sign-in (see Email and Password Sign-In).
  2. A storage adapter: list(), add(text), toggle(id), remove(id) and subscribe(callback).
  3. A store that holds the list in memory, applies optimistic changes and reconciles with the backend.
  4. A view that renders whatever the store holds.

Keeping the adapter interface small is the whole trick. Swapping Firebase for Supabase means writing one new adapter, not rewriting screens. It also makes the app testable: you can run the store against a fake adapter, exactly as the TryIt below does.

JavaScript
// The adapter contract (our own convention)
// list()               -> Promise<Todo[]>
// add(text)            -> Promise<Todo>
// setDone(id, done)    -> Promise<void>
// remove(id)           -> Promise<void>
// subscribe(callback)  -> unsubscribe function; callback receives the full list

Data and security

Each todo belongs to one user. The shape is the same in both backends: id, userId, text, done, createdAt.

For Firebase, store todos in a per-user path and let the path carry ownership:

JavaScript
// Firebase (read-only)
// users/{uid}/todos/{todoId}  ->  { text, done, createdAt }
Text
// firestore.rules (read-only)
match /users/{uid}/todos/{todoId} {
  allow read, delete: if request.auth != null && request.auth.uid == uid;
  allow create: if request.auth != null && request.auth.uid == uid
                && request.resource.data.text is string
                && request.resource.data.text.size() > 0
                && request.resource.data.text.size() <= 200
                && request.resource.data.done == false;
  allow update: if request.auth != null && request.auth.uid == uid
                && request.resource.data.text == resource.data.text;
}

The update rule here only lets the owner change fields other than text, which is enough for toggling done. Real apps might allow editing text too; the point is that rules validate shape, not just identity. See Firestore Security Rules.

For Supabase, one table and four policies:

SQL
-- Supabase (read-only)
create table todos (
  id         bigint generated always as identity primary key,
  user_id    uuid not null default auth.uid() references auth.users(id) on delete cascade,
  text       text not null check (char_length(text) between 1 and 200),
  done       boolean not null default false,
  created_at timestamptz not null default now()
);

alter table todos enable row level security;

create policy "own todos: select" on todos for select to authenticated
  using ( user_id = (select auth.uid()) );
create policy "own todos: insert" on todos for insert to authenticated
  with check ( user_id = (select auth.uid()) );
create policy "own todos: update" on todos for update to authenticated
  using ( user_id = (select auth.uid()) )
  with check ( user_id = (select auth.uid()) );
create policy "own todos: delete" on todos for delete to authenticated
  using ( user_id = (select auth.uid()) );

alter publication supabase_realtime add table todos;

The default auth.uid() fills the owner automatically so the client never sends user_id. Wrapping auth.uid() in (select ...) is a common performance habit so Postgres evaluates it once per query; details are in Row Level Security Policies.

The Firebase adapter (read-only)

JavaScript
// Firebase (read-only)
import {
  collection, addDoc, updateDoc, deleteDoc, doc,
  query, orderBy, onSnapshot, serverTimestamp,
} from "firebase/firestore";

export function firebaseAdapter(db, uid) {
  const todos = collection(db, "users", uid, "todos");
  return {
    async add(text) {
      const ref = await addDoc(todos, { text, done: false, createdAt: serverTimestamp() });
      return { id: ref.id, text, done: false };
    },
    async setDone(id, done) {
      await updateDoc(doc(db, "users", uid, "todos", id), { done });
    },
    async remove(id) {
      await deleteDoc(doc(db, "users", uid, "todos", id));
    },
    subscribe(callback) {
      const q = query(todos, orderBy("createdAt"));
      return onSnapshot(q, (snap) => {
        callback(snap.docs.map((d) => ({ id: d.id, ...d.data() })));
      });
    },
  };
}

onSnapshot returns an unsubscribe function, which maps directly onto our contract. Firestore also fires listeners immediately for local writes (with pending metadata), so it gives you optimistic updates for free; see Realtime Listeners and Offline Support.

The Supabase adapter (read-only)

JavaScript
// Supabase (read-only)
export function supabaseAdapter(supabase) {
  const load = async () => {
    const { data, error } = await supabase
      .from("todos")
      .select("id, text, done")
      .order("created_at");
    if (error) throw error;
    return data;
  };
  return {
    async add(text) {
      const { data, error } = await supabase.from("todos").insert({ text }).select().single();
      if (error) throw error;
      return data;
    },
    async setDone(id, done) {
      const { error } = await supabase.from("todos").update({ done }).eq("id", id);
      if (error) throw error;
    },
    async remove(id) {
      const { error } = await supabase.from("todos").delete().eq("id", id);
      if (error) throw error;
    },
    subscribe(callback) {
      load().then(callback);                       // initial data
      const channel = supabase
        .channel("todos-feed")
        .on("postgres_changes", { event: "*", schema: "public", table: "todos" }, () => load().then(callback))
        .subscribe();
      return () => supabase.removeChannel(channel);
    },
  };
}

Here the realtime event only triggers a refetch, which is the simplest correct approach. It reuses your RLS-protected query, so you never trust a payload blindly. Compare it with Supabase Realtime and Postgres Changes. Supabase does not echo your own write instantly, so the store below must provide the optimistic part.

Optimistic UI

When a user taps a checkbox, waiting 200 ms for a round trip feels sluggish. Optimistic UI changes the screen first and talks to the server second:

  1. Apply the change locally and render.
  2. Send it to the backend.
  3. If it succeeds, keep going. If it fails, roll back and tell the user.
sequenceDiagram
    participant U as User
    participant S as Store
    participant B as Backend
    U->>S: toggle todo
    S->>S: apply locally, render
    S->>B: setDone(id, true)
    alt success
        B-->>S: ok (and a realtime event)
    else failure
        B-->>S: error
        S->>S: roll back, show message
    end

The screen changes first; only a failure sends it back.

Run the stand-in app

The stand-in has three pieces: an in-memory adapter that implements our contract (and can be told to fail), a store with optimistic updates and rollback, and a script that plays a session. The subscribe callback acts as the realtime feed, and a second store watching the same adapter plays the "other tab". The code runs on our Node server and contains no network access.

Node.js Stand-in realtime todo app with an adapter

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output from top to bottom. When tab A adds a todo, tab B immediately hears it through its subscription. When tab B toggles an item, it shows the change at once ("optimistic"), and then both tabs print the confirmed list ("realtime"). On the simulated failure, tab A flips the checkbox and then flips it back with a message. After unsubscribe, tab B no longer hears anything, which is why real apps unsubscribe when a component unmounts.

One more detail to notice: after a toggle the store replaces its list with the server's list. That keeps tabs consistent even if two people edited at the same moment, with last write wins. For a todo app that is acceptable.

Extending the stand-in

Now make the app yours. You could:

  • Add rename(id, text) and validate length in the adapter, like the rules above.
  • Make the store retry failed writes twice before rolling back.
  • Add a filter ("all", "open", "done") as a pure function over items.
  • Write a second adapter that stores data in an array of "rows" with user_id, and prove both pass the same checks.

The last idea is the real payoff of the adapter: one set of tests, any backend.

Production checklist

  • Rules or RLS turned on and tested before launch (never ship test mode or open policies).
  • The service role key is nowhere in the client bundle.
  • Every subscription is removed on unmount.
  • Inputs are validated in rules or constraints, not only in the form.
  • Errors reach the user: a toast or inline message, not just the console.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of the storage adapter interface?

    A small contract lets you swap Firebase for Supabase, or a fake, without changing screens.
  2. 2. What should optimistic UI do when the server rejects a write?

    The screen was ahead of the server. On failure it must return to the true state and explain what happened.
  3. 3. Why does the Supabase adapter refetch after a Postgres Changes event?

    A refetch trusts only what your query returns under RLS. You can apply payloads directly later as an optimization.
  4. 4. Why unsubscribe from a listener when a screen closes?

    Active listeners keep running (and may be billed) even if nothing displays their results.

Summary

  • Design the app around a small adapter contract (add, setDone, remove, subscribe) so backends are interchangeable.
  • Firestore stores todos under users/{uid}/todos with rules for ownership and shape; Supabase uses a todos table with RLS policies and a realtime publication.
  • Optimistic UI changes the screen first, then confirms or rolls back.
  • Realtime subscriptions keep tabs in sync; always unsubscribe when done.
  • Test the store against a fake adapter before connecting a real backend.

Next: Project: Chat App with Presence