VibeCPR

← All fixes

Supabase · Postgres · Constraints

Your app's rules only live in the frontend: move them into Supabase

Updated · Applies to: Supabase, Lovable, Bolt, Cursor

TL;DR fix: If a rule only exists in your React code (a "username taken" check, a max quantity, a hidden "Mark as paid" button), it isn't a rule. Your Supabase URL and public key ship in the app, so anyone signed in can call the database directly with supabase.from('orders').insert(...) or curl and skip your UI. Move each rule into the database: a unique index on lower(username) for duplicates, check constraints for allowed values and ranges, default auth.uid() plus an RLS WITH CHECK so users can't create rows for someone else, and a BEFORE INSERT OR UPDATE trigger for status changes only your server may make.

Steps

  1. List the rules your UI enforces. Go through every form and button: uniqueness (usernames, slugs), allowed values (status, plan, category), ranges (quantity, price, rating), ownership (user_id), and who may change a status.
  2. Test one from the browser console. Signed in as a normal user, insert a row that breaks a rule, for example a duplicate username in different case or an order with quantity -5. If it saves, the rule only lives in the frontend.
  3. Add unique indexes. Create a unique index on lower(username) (or slug, email) so case variants count as duplicates. Clean up existing duplicates first or the index will fail to build.
  4. Add check constraints. Add CHECK constraints for allowed values and ranges, for example status in ('pending','paid','shipped','cancelled') and quantity between 1 and 100.
  5. Pin ownership with RLS. Set user_id default auth.uid() and not null, and make the INSERT policy WITH CHECK ((select auth.uid()) = user_id) instead of WITH CHECK (true).
  6. Guard status changes with a trigger. Add a BEFORE INSERT OR UPDATE trigger that only lets anon and authenticated create pending rows and make the transitions you allow, like pending to cancelled. Your server sets paid or shipped with the service role.
  7. Retest and handle the errors in the UI. Repeat the console tests; each should fail. Map error code 23505 (unique violation) and 23514 (check violation) to friendly messages in your forms.

Why frontend rules don’t count

Vibe-coded apps put a lot of logic in the UI: the sign-up form checks whether a username is taken, the cart caps quantity at 10, and only admins see the “Mark as paid” button. None of that runs when someone talks to your database directly, and with Supabase anyone can, because the project URL and public key ship in your app:

// From the browser console of your live app, signed in as a normal user
await supabase.from('profiles').insert({ id: myId, username: 'Bob' })   // 'bob' already exists
await supabase.from('orders').insert({ user_id: someoneElse, status: 'paid', quantity: -5 })
await supabase.from('orders').update({ status: 'paid' }).eq('id', 42)

All three succeeded in our test against a typical schema with RLS on. RLS was doing its job (it checks rows), but nobody had told the database the rules. As a builder put it on X, curl skips your frontend.

Step 1: find rules that only live in the UI

-- Which tables have no unique or check constraints beyond the primary key?
select c.relname as table_name,
       count(*) filter (where con.contype = 'u') as unique_constraints,
       count(*) filter (where con.contype = 'c') as check_constraints
from pg_class c
join pg_namespace n on n.oid = c.relnamespace and n.nspname = 'public'
left join pg_constraint con on con.conrelid = c.oid
where c.relkind = 'r'
group by c.relname order by c.relname;

-- INSERT policies that don't pin the owner
select tablename, policyname, with_check
from pg_policies
where schemaname = 'public' and cmd in ('INSERT', 'ALL');

A with_check of true, or tables with zero unique and check constraints, are where to look first. Then do the console test above for each rule your forms enforce.

Fix 1: duplicates → unique index

create unique index profiles_username_lower_key
on public.profiles (lower(username));

lower() makes Bob and bob the same name. Do the same for slugs, invite codes and anything else that must be one-of-a-kind. Postgres rejects a duplicate with duplicate key value violates unique constraint (code 23505), even when two requests arrive at the same moment.

Fix 2: bad values → check constraints

alter table public.orders
  add constraint orders_quantity_positive check (quantity between 1 and 100),
  add constraint orders_status_valid check (status in ('pending', 'paid', 'shipped', 'cancelled'));

A bad row fails with new row for relation "orders" violates check constraint (code 23514). If old rows already break the rule, add the constraint not valid, fix the data, then alter table ... validate constraint ....

Fix 3: rows for someone else → default + WITH CHECK

alter table public.orders
  alter column user_id set default auth.uid(),
  alter column user_id set not null;

drop policy if exists "Anyone can create orders" on public.orders;
create policy "Users create their own orders"
on public.orders for insert to authenticated
with check ( (select auth.uid()) = user_id );

Now the browser doesn’t need to send user_id at all, and a row for another user fails with new row violates row-level security policy.

Fix 4: status changes → a guard trigger

RLS can’t compare the old and new value of a column, so use a trigger:

create or replace function public.guard_order_status()
returns trigger language plpgsql as $$
begin
  if current_user in ('authenticated', 'anon') then
    if tg_op = 'INSERT' and new.status <> 'pending' then
      raise exception 'new orders must start as pending';
    end if;
    if tg_op = 'UPDATE' and new.status is distinct from old.status
       and not (old.status = 'pending' and new.status = 'cancelled') then
      raise exception 'status change % -> % is server-only', old.status, new.status;
    end if;
  end if;
  return new;
end $$;

create trigger guard_order_status
before insert or update on public.orders
for each row execute function public.guard_order_status();

Your Stripe webhook (after verifying the signature) or an Edge Function uses the service role, so it can set paid and shipped. The same idea protects plan and is_admin columns.

Show friendly errors

Keep your form checks for a nice experience, and treat the database as the real gate: map 23505 to “That name is taken” and 23514 to “Please check that value” when error.code comes back from supabase-js.

Paste this into Lovable, Bolt or Cursor

Every rule my UI enforces must also be enforced by the database. Don't rely on frontend checks.
1. List every rule in my forms and buttons: unique fields, allowed values, number ranges,
   who owns a row, and who may change a status.
2. For uniqueness, add unique indexes (use lower() for usernames, slugs and emails).
3. For allowed values and ranges, add CHECK constraints. Find and list existing rows that break them first.
4. Set user_id default auth.uid() not null, and make INSERT policies
   WITH CHECK ((select auth.uid()) = user_id), never WITH CHECK (true).
5. Add a BEFORE INSERT OR UPDATE trigger so anon/authenticated can only create 'pending' rows
   and only make the status changes I allow. Only server code with the service role sets the rest.
6. Map Postgres errors 23505 and 23514 to friendly messages in the forms.
7. Then test from the browser console as a normal user: a duplicate username, quantity -5,
   an order for another user, and marking my own order paid must all fail.

What we verified

  • Reproduced on Postgres 17 (PGlite) with Supabase-style anon/authenticated roles and an auth.uid() stand-in. Before the fixes, a signed-in user inserted a case-variant duplicate username and an order for another user with status = 'paid' and quantity = -5. After the fixes: the duplicate failed with duplicate key value violates unique constraint, the order for another user failed with new row violates row-level security policy, -5 failed the check constraint, inserting as paid and self-marking paid were blocked by the trigger, cancelling a pending order worked, a normal insert got user_id from auth.uid(), and the server role could still set paid.
  • Not reproduced on a live Supabase project. Constraint and error-code behavior is standard Postgres (linked docs).

The same goes for login “lockouts” counted in the browser: the attacker calls Supabase Auth directly and never sees your form. See login lockout keyed only on email.

Related: new row violates row-level security policy, USING (true) policies, users updating their own plan, and apps that open for anyone with the link.

When to get help

Get help if you already have duplicate or invalid rows in production, if several tables depend on the same status field, or if your app writes through Edge Functions as well as the client.

FAQ

My form already checks if a username is taken. Why do I need a unique index?

The form check runs in the browser, and anyone can call Supabase directly with your public key and skip it. Two sign-ups at the same moment can also both pass a "SELECT then INSERT" check. A unique index is enforced by Postgres on every insert and update: create unique index profiles_username_lower_key on public.profiles (lower(username)); A duplicate then fails with "duplicate key value violates unique constraint" (error code 23505).

How do I stop negative quantities or made-up status values in Supabase?

Use check constraints: alter table public.orders add constraint orders_quantity_positive check (quantity between 1 and 100), add constraint orders_status_valid check (status in ('pending','paid','shipped','cancelled')); A bad row fails with "new row for relation orders violates check constraint" (error code 23514), no matter which client sent it.

Can a user create rows for another user in Supabase?

Yes, if your INSERT policy is WITH CHECK (true) and the browser sends user_id. Set the column to default auth.uid() not null and change the policy to WITH CHECK ((select auth.uid()) = user_id). Then a row for someone else fails with "new row violates row-level security policy".

How do I let users cancel an order but not mark it paid?

RLS can't compare old and new values, so use a BEFORE INSERT OR UPDATE trigger: when current_user is anon or authenticated, only allow new rows with status pending and only the pending to cancelled change. Your Stripe webhook or Edge Function, using the service role, sets paid and shipped.

Is hiding the admin button enough?

No. Hiding a button changes what people see, not what the database accepts. Every rule that matters for money, ownership or permissions has to be enforced in Postgres (constraints, RLS, triggers) or in server code that uses a secret key.

Will adding a unique index or check constraint break my existing data?

If existing rows already break the rule, Postgres refuses to create the index or constraint. Find them first (for example group by lower(username) having count(*) > 1) and fix them. For a check constraint you can add it NOT VALID to cover new rows only, then clean up and run VALIDATE CONSTRAINT.

Sources

Related fixes