Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 31 ยท Real-World Projects

Project: SaaS Starter with Teams

Design a SaaS backend on Firebase or Supabase: teams, invitations, plan limits and webhook-driven subscriptions, with runnable idempotent webhook code.

Most paid web products share the same skeleton. People sign up, create or join a team, invite colleagues, and the team pays for a plan that limits what it can do. A payment provider tells your backend when a subscription starts, renews or is canceled, and your app must react correctly even when messages arrive twice or out of order.

This project lays out that skeleton on both platforms. The Firebase and Supabase code is read-only, because it needs real projects and a real payment provider. The runnable parts are stand-ins in plain JavaScript: a plan-limit check and a webhook handler with signature checking and idempotency. They are ours, not part of either product, but the ideas are exactly what you would put into a Cloud Function or an Edge Function. Background reading: Multi-Tenant and Team Apps, Cloud Functions and Edge Functions and Security Pitfalls in Both Platforms.

Four building blocks

Teams Members with roles.
Invitations Join by a one-time token.
Plans Limits per subscription.
Webhooks The provider updates your data.

The browser never decides what a team has paid for.

1 / 2

Step 1: Model teams and members

A user may belong to many teams, so membership is its own record, not a field on the user. Each membership has a role. Subscriptions belong to the team, not to a person.

In Supabase, that is three tables:

SQL
-- read-only: Supabase schema
create table public.teams (
  id uuid primary key default gen_random_uuid(),
  name text not null check (char_length(name) between 2 and 60),
  created_by uuid not null references auth.users (id)
);

create table public.team_members (
  team_id uuid not null references public.teams (id) on delete cascade,
  user_id uuid not null references auth.users (id) on delete cascade,
  role text not null check (role in ('owner', 'member')),
  primary key (team_id, user_id)
);

create table public.subscriptions (
  team_id uuid primary key references public.teams (id) on delete cascade,
  plan text not null default 'free' check (plan in ('free', 'pro', 'business')),
  status text not null default 'active',
  current_period_end timestamptz,
  provider_customer_id text unique
);

In Firebase, the shape is a document per team with a members subcollection (or a map of uid to role when teams are small), and the subscription as a separate document so that rules can make it read-only for clients:

JavaScript
// read-only: Firestore layout
// teams/{teamId}                 { name, createdBy }
// teams/{teamId}/members/{uid}   { role: "owner" | "member" }
// teams/{teamId}/billing/current { plan, status, currentPeriodEnd }   <- written by server only

Step 2: Security policies

Members may read their team. Only owners may change members. Nobody on the client may write billing data.

SQL
-- read-only: Supabase policies
alter table public.teams enable row level security;
alter table public.team_members enable row level security;
alter table public.subscriptions enable row level security;

-- a helper that avoids a recursive policy on team_members
create function private.is_member(t uuid) returns boolean
language sql stable security definer set search_path = ''
as $$ select exists (
  select 1 from public.team_members
  where team_id = t and user_id = (select auth.uid())
) $$;

create policy "members read their team" on public.teams
  for select to authenticated using ((select private.is_member(id)));

create policy "members read the member list" on public.team_members
  for select to authenticated using ((select private.is_member(team_id)));

create policy "members read the subscription" on public.subscriptions
  for select to authenticated using ((select private.is_member(team_id)));
-- no insert/update/delete policy on subscriptions: only the service role writes it
Text
// read-only: Firestore rules (sketch)
match /teams/{teamId} {
  function memberRole() {
    return get(/databases/$(database)/documents/teams/$(teamId)/members/$(request.auth.uid)).data.role;
  }
  function isMember() {
    return request.auth != null
      && exists(/databases/$(database)/documents/teams/$(teamId)/members/$(request.auth.uid));
  }

  allow read: if isMember();

  match /members/{uid} {
    allow read: if isMember();
    allow write: if isMember() && memberRole() == 'owner';
  }
  match /billing/{doc} {
    allow read: if isMember();
    allow write: if false;      // the Admin SDK in a Cloud Function bypasses rules
  }
}

The empty write rule on billing is the key. A user who could write plan: "business" for their own team would upgrade for free. Server code uses the Admin SDK (Firebase) or the service role (Supabase), both of which skip rules and policies, so secrets for them must stay on the server.

Step 3: Invitations

An invitation is a row with a random, single-use token and an expiry. The owner creates it; the invitee opens a link, signs in, and a trusted function turns the invitation into a membership. Store only a hash of the token, so a database leak does not hand out working invitations.

JavaScript
// read-only: accepting an invitation in a Supabase Edge Function (sketch)
const { data: invite } = await admin
  .from("invitations")
  .select("id, team_id, email, expires_at, accepted_at")
  .eq("token_hash", await sha256(token))
  .single();

if (!invite || invite.accepted_at || new Date(invite.expires_at) < new Date()) {
  return new Response("Invitation is invalid or expired", { status: 400 });
}
await admin.from("team_members").insert({ team_id: invite.team_id, user_id: user.id, role: "member" });
await admin.from("invitations").update({ accepted_at: new Date().toISOString() }).eq("id", invite.id);

Real code would also compare the invitation email with the signed-in user's verified email, and make the two writes one transaction (a Postgres function via RPC does that neatly).

Step 4: Plans and limits

A plan is just data: limits per plan, such as how many members and projects a team may have. Keep the table of limits in one place on the server and check it before creating anything. In Postgres you can enforce it in a trigger; in Firebase you enforce it in a callable function, since rules cannot count documents cheaply.

JS Stand-in plan limits

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

No output.

Never display a limit as the only guard. A disabled button is a courtesy; the real check happens where the data is written.

Step 5: Webhook-driven subscriptions

When a customer pays, the provider sends an HTTP request (a webhook) to a URL you own. Your function must:

  1. Verify the signature so strangers cannot fake an upgrade. The provider signs the raw request body with a shared secret; you recompute the signature and compare in constant time.
  2. Be idempotent. Providers retry when they do not get a fast 2xx answer, so the same event can arrive more than once. Record each event id and skip ones you have seen.
  3. Tolerate odd order. An "updated" event may arrive before "created." Compare event timestamps or fetch current state before overwriting.
  4. Answer quickly and do slow work afterwards.

The exact header names and signature formats differ per provider, so check your provider's documentation. The code below uses a simple stand-in scheme (HMAC-SHA256 of the body, hex) to demonstrate the logic with node:crypto; it runs on the site's Node runner.

Node.js Stand-in webhook handler with signature and idempotency

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.

The tampered request fails the signature check, the retry of evt_1 is ignored, and the old event cannot undo the cancellation. In production the seen-event set is a database table with a unique constraint on the event id, so two parallel deliveries cannot both win. In Postgres that is insert ... on conflict do nothing and checking whether a row was inserted.

The real function would be an HTTP Cloud Function or an Edge Function using the provider's own verification helper, with the signing secret stored as a function secret (see Cloud Functions and Edge Functions). It would write the subscription with the Admin SDK or service role.

Step 6: Show the plan in the app

The client simply reads subscriptions (or the billing/current document) and shows the plan. Because the webhook writes that record, a realtime listener can flip the interface to "Pro" the second the payment is confirmed, with no polling.

JS Stand-in: the UI follows the subscription record

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

No output.

Launch checklist

  • Subscription and billing writes are impossible from clients (rules deny, no policy exists).
  • Webhook signatures are verified on the raw body; events are deduplicated by id.
  • Every limit is enforced where data is written.
  • Invitation tokens are random, hashed, single-use and expiring.
  • Secrets (service role, Admin credentials, webhook secret) live only in server environments.
  • Tests cover a non-member, a member, an owner and a server write.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the subscription record not writable by clients?

    Billing state must come from the payment provider through trusted server code.
  2. 2. What does idempotency mean for a webhook handler?

    Providers retry deliveries, so duplicates must not apply twice.
  3. 3. How should webhook signatures be compared?

    Constant-time comparison avoids timing leaks, and the raw body is what was signed.
  4. 4. Where do you store an invitation token?

    A hash stops a database leak from yielding usable invitations.

Summary

  • Teams, memberships and subscriptions are separate records; subscriptions belong to the team.
  • Clients read billing data; only server code with elevated credentials writes it.
  • Invitations use hashed, single-use, expiring tokens.
  • Webhooks need signature verification, deduplication by event id and tolerance for stale events.
  • Enforce plan limits at write time, never only in the UI.

Next: Practice Exercises with Solutions