Supabase RLS Fix for AI-Generated React Apps: Stop Leaking Data and Fix Broken Auth

Fix Supabase Auth and RLS in your Lovable React app: diagnose empty lists, 42501 errors, and open tables, then apply owner policies, grants, and tests.

Web DevTech
Skip to article text

Direct answer: Supabase RLS fix for a Lovable React app means enabling Row Level Security on every table, adding one policy per operation that limits rows to the signed-in owner with auth.uid(), granting only the roles that need access, and verifying with two test users. Do not disable RLS, do not use USING (true) for private data, and never ship the service_role key in browser code.

Your app looks finished. Login works. The dashboard loads. Then a second user signs up and sees the first user's data, or a new user sees nothing at all. Both symptoms have the same cause, and a Supabase RLS fix is the repair, not another prompt that says "fix auth."

Supabase Auth proves who the user is. Row Level Security, or RLS, decides which rows that user may touch. AI builders are good at the first part and unreliable at the second. This guide shows how to diagnose the exact failure, fix it in the right order, and prove it with two users. JUHENZA's web development work follows the same rule used here: scope before development, and verify before calling a fix done.

Why auth breaks in AI-generated React apps

Lovable, Bolt, and similar builders generate the table and the interface first. RLS comes later, if at all. When a policy error appears during a fix loop, the fastest way to make the error disappear is a policy that says USING (true). The preview looks fine. The data is public.

The browser client uses the anon key, also called the publishable key. That key is public by design. Anyone can read it from the network tab and call your database directly with curl. RLS is the only gate between that key and your rows.

Three failures repeat in AI-generated apps. First, RLS is off, so the anon key can read everything. Second, RLS is on with no policies, so every read returns empty and every write is blocked. Third, RLS is on with a permissive policy, so every user sees every row. The fix is different for each, so diagnosis comes before SQL.

A public scan of 50 Lovable repositories by ShipSafe found 89% had RLS off and 34% put the service_role key in client code. Treat that as a warning about the pattern, not as a claim about your app. Your app needs its own audit.

Diagnose it in 10 minutes

Start with symptoms, not guesses. The table below maps what you see to the likely cause.

Supabase RLS symptom to cause diagnosis table

Match the symptom to the gate before you run another fix prompt.

SymptomLikely causeFirst check
New user sees everyone's dataRLS off, or a USING (true) policyAudit SQL below
New user sees empty list, you see dataRLS on, no policy for that operationAudit SQL below
Reading works, saving failsMissing INSERT policy or missing WITH CHECKPolicy list
New table fails with 42501Missing grant, not RLSGrants section
Works for you, fails for a customerSession or redirect URL issueReact auth wiring

Run this audit in the Supabase SQL Editor. It lists RLS off, RLS on with zero policies, and policies that let everyone in.

-- tables with RLS off
select c.relname as table_name, 'RLS OFF' as finding
from pg_class c join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind in ('r','p') and not c.relrowsecurity;

-- RLS on, zero policies: this is the empty-list symptom
select c.relname, 'RLS ON, NO POLICIES' as finding
from pg_class c join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind in ('r','p') and c.relrowsecurity
  and not exists (select 1 from pg_policy p where p.polrelid = c.oid);

-- policies that are literally true: this is the everyone-sees-everything symptom
select tablename, policyname, cmd, qual, with_check
from pg_policies
where schemaname = 'public'
  and (coalesce(qual,'') in ('true','(true)') or coalesce(with_check,'') in ('true','(true)'));

Also list every table's policies in the Dashboard under Authentication, Policies, or Table Editor. Note which tables hold user data, which hold genuinely public data, and which hold shared team data. That list decides the fix for each table. Web development services that include portals and web apps need this same inventory before any permission change.

The fix in 5 steps

Use this order. Skipping the backfill step is how old rows disappear.

Step 1: Add the owner column, nullable for now

Most AI-generated tables lack a reliable owner column. Add one without making it required yet.

alter table public.projects
  add column if not exists user_id uuid references auth.users (id) on delete cascade;

If your table uses owner_id, author_id, or created_by, use that column consistently. Do not add three owner columns. Pick one and use it in every policy.

Step 2: Backfill existing rows before policies go live

Give every existing row an owner. The rule depends on your app: a created_by column, an email match, or one admin owner for seed data. Do this before you tighten policies, or the new owner policies will hide old rows from everyone. That looks like data loss, but it is a policy doing its job.

-- illustrative backfill: replace with your real rule
update public.projects set user_id = '<owner uuid>' where user_id is null;

Back up before you run this on production. A backfill without a backup and a rollback plan is a gamble.

Step 3: Make the owner required, with a server-side default

Now make the column required and default it to the signed-in user. The default matters because Lovable-generated inserts often do not send user_id. Without a default, those inserts fail with "new row violates row-level security policy."

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

Do not add the column as NOT NULL DEFAULT auth.uid() in one step on a table that already has rows. The SQL Editor has no signed-in user, so auth.uid() is null for every old row and Postgres refuses the change. Backfill first, then constrain.

Step 4: Enable RLS and write one policy per operation

Enable RLS, then write four policies: SELECT, INSERT, UPDATE, DELETE. A FOR ALL policy hides which operation each rule was meant to cover, so write them separately.

alter table public.projects enable row level security;

drop policy if exists "Enable read access for all users" on public.projects;

create policy "owner select" on public.projects
  for select to authenticated
  using (user_id = (select auth.uid()));

create policy "owner insert" on public.projects
  for insert to authenticated
  with check (user_id = (select auth.uid()));

create policy "owner update" on public.projects
  for update to authenticated
  using (user_id = (select auth.uid()))
  with check (user_id = (select auth.uid()));

create policy "owner delete" on public.projects
  for delete to authenticated
  using (user_id = (select auth.uid()));

Three details matter. First, name the role with TO authenticated. A policy with no TO clause applies to public, which includes anon. Second, use (select auth.uid()) rather than bare auth.uid() so Postgres evaluates it once per statement, not once per row. Third, UPDATE needs both USING and WITH CHECK, or a user can reassign a row to someone else by changing user_id.

Step 5: Add an index on the owner column

RLS evaluates the policy against candidate rows. An unindexed user_id turns a read into a sequential scan as the table grows.

create index if not exists projects_user_id_idx on public.projects (user_id);

Repeat steps 1 to 5 for every user-owned table. Do not copy the same policy name across tables without checking for conflicts. Keep the naming pattern, change the table.

Grants vs RLS, and the 30 Oct 2026 change

Grants and RLS are two separate gates. Grants decide whether a role can touch a table at all. RLS decides which rows that operation applies to. You need both.

Diagram of the grants gate and the RLS policy gate in Supabase

Grants open the door. RLS chooses the rows. A missing grant returns 42501; a missing policy returns an empty list.

A missing grant raises 42501 before any policy runs. A WITH CHECK violation also raises 42501. A USING filter raises nothing and returns zero rows. That is why "permission denied" and "empty list" need different fixes.

Supabase changed the default for new tables in public. From 30 October 2026, that change applied to existing projects as well: new tables are no longer exposed to the Data API automatically. A new table needs an explicit grant before anon or authenticated can reach it through the API. Existing tables keep their current grants. Source: the Supabase changelog for the Data API grants change.

Put grants in the same migration as the table, RLS, and policies. Grant only what the app uses, only to the role that needs it.

-- illustrative grants for a user-owned table
grant select, insert, update, delete on table public.projects to authenticated;
revoke all on table public.projects from anon;

Do not fix 42501 with GRANT ALL to anon. Do not fix it by disabling RLS. Both make the app work by removing protection. The software services overview includes integration and application work where this same least-privilege rule applies to APIs, not only to databases.

React auth wiring that Lovable often gets wrong

Even correct RLS fails if the React app never sends a signed-in session. Check these four points.

First, confirm the user is actually signed in before you blame RLS. auth.uid() is null for every anon request, so an owner policy returns no rows for a signed-out user.

const {
  data: { user },
} = await supabase.auth.getUser();
if (!user) throw new Error("Not signed in");

Second, check the Supabase client uses only the anon or publishable key in browser code. The service_role key bypasses RLS entirely. It belongs in server code only, such as an Edge Function with a narrow job. If it ever reached a browser bundle, rotate it. Rotating a key is not optional after exposure.

Third, check redirect URLs. In Supabase, set Site URL to your published domain, not localhost, and add every deployment URL to the allowed redirect list. A login that works in preview and fails in production is often a redirect URL problem, not an RLS problem.

Fourth, check session persistence after refresh. If the app clears the session on reload, every query becomes anon. Test by logging in, refreshing, then creating a record. If the record fails after refresh, fix session handling before you touch policies again.

Illustrative example: Maple Notes

Maple Notes is an illustrative Canada SaaS app, not a verified client case. It lets founders save notes. The AI build created a notes table with RLS off. Founder A created 40 notes. Founder B signed up and saw all 40 notes.

The fix followed the five steps above. The team added user_id, backfilled Founder A's 40 notes to Founder A, added owner policies, granted authenticated only, and verified with two browsers. Founder B then saw zero notes, Founder A still saw 40, and a curl request with Founder B's token also returned []. That last check matters. A UI that hides rows is not proof. An API that returns no rows is proof.

Edge cases: storage, teams, and views

Public data is fine, if it is deliberate

A blog, a pricing page, or a published catalog should be readable by everyone. Make it explicit and keep writes to the owner.

create policy "anyone reads published" on public.posts
  for select to anon, authenticated
  using (published = true);

create policy "author writes" on public.posts
  for all to authenticated
  using (author_id = (select auth.uid()))
  with check (author_id = (select auth.uid()));

Do not use USING (true) for private data. Do not use it for drafts. Public means public to anyone with the anon key, not just public to logged-in users.

Storage needs its own policies

A public bucket does not mean public uploads. Supabase Storage enforces RLS on storage.objects for writes. If uploads fail with 403, add a policy on storage.objects for the bucket, scoped to authenticated and to that bucket_id. Keep downloads and uploads separate. A bucket that is readable by everyone should not be writable by everyone.

In the Dashboard, open Storage, then Policies, and check the upload bucket. Confirm the INSERT policy is scoped to the bucket and to authenticated, and that the bucket is not writable by anon.

Teams need a membership check, not a second owner column

If access depends on membership, a naive policy that queries the membership table can query itself and fail with "infinite recursion detected in policy." The fix is a security definer function that checks membership without re-entering RLS.

create or replace function public.is_workspace_member(ws uuid)
returns boolean language sql security definer set search_path = public stable as $$
  select exists (
    select 1 from public.workspace_members m
    where m.workspace_id = ws and m.user_id = auth.uid()
  );
$$;

create policy "members read" on public.documents
  for select to authenticated
  using (public.is_workspace_member(workspace_id));

Use security definer only for narrow checks like this. A broad security definer function that returns whole rows can undo RLS. Keep the function small, stable, and reviewed.

Views bypass RLS by default

In Postgres, views are often created with security definer, so a view over a protected table can hand out rows the policies were meant to withhold. For Postgres 15 and above, create views with security_invoker = true so they obey the underlying tables' RLS for anon and authenticated. On older versions, revoke access from client roles or put the view in an unexposed schema. Check every view, not only tables.

Canada note: PIPEDA, residency, and what RLS proves

For a Canada SaaS founder, RLS is also a sales question. Canadian customers often ask where data lives and who can see it. PIPEDA, Canada's federal private-sector privacy law, does not by itself require personal information to stay in Canada, but you remain responsible for it when a service provider processes it, and you should be transparent about cross-border processing. The Office of the Privacy Commissioner's guidance on cross-border processing sets out that accountability. Some customers and contracts do require Canadian residency, so check your contracts and choose a Canadian region if your buyers require it.

RLS helps you show row-level separation. It does not prove PIPEDA compliance by itself. You still need a privacy policy, consent and retention rules, breach handling, and processor terms that match your situation. This section is general information, not legal advice. Consult a qualified professional for your product and contracts.

Verify with two users, not the SQL Editor

The SQL Editor runs as postgres, which bypasses RLS. A query that works there proves nothing about what users see. Verify as users.

Two-user verification matrix for Supabase RLS

A UI that hides rows is not proof. An API that returns no rows is proof.

  1. Open two browsers or two profiles. Create a record as User A. User B must not see it in the UI.
  2. Call the API as User B with User B's token. Expect [].
  3. Try an anon call with only the anon key. Expect [] for private tables.
  4. Try an insert as User B with User A's user_id. Expect a 42501 error.
  5. Re-run the audit SQL. Every flagged table should now be fixed or documented as intentionally public.
curl "https://<project>.supabase.co/rest/v1/projects?select=*" \
  -H "apikey: <anon key>" \
  -H "Authorization: Bearer <user B token>"

Expected for a private table: []. If you get rows, the policy is still permissive. If you get 42501, check grants first, then policies.

Tell the builder what you did. If you ran SQL directly in Supabase, paste it into Lovable as "this migration was applied" so generated types and the next prompt stay in sync. Otherwise the next "add a feature" prompt may recreate the permissive policy. The Lovable Stripe webhook fix follows the same principle for payments: fix delivery, verification, and the database write in order, then keep the builder in sync.

Common mistakes, limits, and when to get help

Common mistakes:

  • Disabling RLS to make an error disappear
  • Using USING (true) for private tables
  • Shipping the service_role key in browser code
  • Adding NOT NULL before backfill, hiding old rows
  • Writing only a SELECT policy, then wondering why saves fail
  • Testing only in the SQL Editor
  • Forgetting grants for new tables after 30 October 2026
  • Leaving a view or a Storage bucket unprotected while tables are locked

Limits: RLS does not fix broken session handling, wrong redirect URLs, or a leaked service_role key by itself. RLS does not protect data that a server function exposes without checks. RLS does not make a public table private. It only enforces the policies you wrote.

When to involve a specialist: Bring in help if you have team or multi-tenant rows, if you use views or Edge Functions that bypass RLS, if you need admin or support roles that can see across users, or if you need to prove separation for a Canadian enterprise buyer. A specialist should also review any migration that touches existing customer data. Do not run a backfill on production without a backup and a rollback plan.

A note on evidence

No first-hand client result or named app is claimed in this guide. The steps come from the Supabase documentation, the published grants changelog, and the security research cited above. The Maple Notes example is illustrative. If you want proof for a specific fix, ask for the table list, the before-and-after audit SQL, the policy definitions, and the two-user API results. Evidence you can re-run beats a promise you cannot.

FAQ

Why does my Lovable app return empty lists even though the table has rows?

RLS filters SELECT results silently. If RLS is on and no policy allows that SELECT for the current role, Postgres returns zero rows with no error. Check the audit SQL for RLS on with zero policies, then add the missing SELECT policy for authenticated with the correct owner check.

What does "new row violates row-level security policy" mean?

It means RLS is on and the row you tried to write did not pass any INSERT policy's WITH CHECK. The usual causes are a missing INSERT policy, a user_id that does not match auth.uid(), or no signed-in user at all. Fix the policy, fix the user_id default, and confirm the session before you change anything else.

Is USING (true) ever a correct fix?

Only for data that is meant to be public to anyone with the anon key, such as published posts or a public catalog. It is not a fix for private user data. For private data, scope the policy to the owner with user_id = (select auth.uid()) and name the role with TO authenticated.

Why did my new table break after 30 October 2026 when old tables still work?

Supabase changed the default so new tables in public are no longer exposed to the Data API automatically. Existing tables kept their grants. A new table needs an explicit grant before the API can reach it, even if RLS policies are correct. Add the grant in the same migration as RLS and policies.

Should I use the service_role key to fix a failing query?

No. The service_role key bypasses RLS. Using it in browser code removes the protection you just built. Keep it in server code only, for narrow jobs. If it ever reached a browser bundle, rotate it and audit what it could have accessed.

How do I test RLS without guessing?

Use two test users and curl. Create a record as User A, then call the API as User B and as anon. Both should return [] for private tables. Try an insert as User B with User A's user_id and expect 42501. Re-run the audit SQL. Do not rely on the SQL Editor, which bypasses RLS.

Where this fits

This post sits in AI-Built Apps: Lovable + Supabase Fixes, under Software & AI Engineering. For the payments side of the same stack, see the Lovable Stripe webhook fix. For the broader archive, see engineering articles.

Next step

If your Lovable app is leaking data, returning empty lists, or blocking saves, do the 10-minute audit above, then apply the backfill-first fix and the two-user test. If you want a specialist to review the policies, grants, and verification before you ship, discuss your project and send your table list, symptoms, and whether the data is user-owned, public, or shared.

References

  1. Supabase Docs — Row Level Security
  2. Supabase Changelog — Tables not exposed to Data and GraphQL API automatically
  3. Office of the Privacy Commissioner of Canada — Guidelines for processing personal data across borders

Related articles

Let’s discuss
your project.

Tell us what you need to build or change. If you’re still planning, use AI to draft an approach before deciding whether to share it.