Short answer
Row level security (RLS) is the Postgres feature that decides which rows each user may read or change. In a Supabase app the browser talks to the database directly with a public key, so RLS is what keeps one user’s data away from everyone else. Turn it on for every table in the public schema, add one owner policy per action, keep the secret key out of the browser and test your policies as a real user.
Ask an AI about this page:ChatGPTClaude
On this page
Key takeaways
- Your Supabase key is in your browser code on purpose. That means anyone can talk to your database; RLS decides what they get.
- A filter like
.eq("user_id", userId)in your frontend is a convenience, not protection. An attacker simply leaves it out. - Tables created in SQL migrations do not get RLS automatically. Check every table in
public. - The safe default is one owner policy per action, written as
(select auth.uid()) = user_id, for theauthenticatedrole only. - Test as a real user, not as the dashboard admin: the dashboard and the secret key skip RLS entirely.
What row level security does
Most apps built with Lovable, Bolt or a similar tool follow the same pattern: the React frontend calls Supabase directly, for example supabase.from("documents").select(). There is no server of your own in between. Supabase turns that call into a database query through its Data API and sends the result straight back to the browser.
For that to work, your Supabase URL and a public key ship inside your website’s JavaScript. Anyone can open the browser’s developer tools and copy both. That is expected and fine, as long as the database itself knows who may see which row. That is exactly what row level security is: a rule stored in Postgres that is checked for every single row on every query, no matter where the query comes from.
Without RLS, a table that the public roles can reach is answered in full. With RLS enabled and a policy that says “a row belongs to the user whose ID is in user_id”, the same request returns only the caller’s rows. Postgres removes everything else before the data leaves the database.
Why AI-built apps get this wrong so often
RLS problems are rarely the result of carelessness. They come from three things that feel safe while you build.
1. The frontend filter hides the problem. AI builders usually generate a query like this:
const { data } = await supabase
.from("documents")
.select("id, title, created_at")
.eq("user_id", userId);In the app, every user only ever sees their own documents, so everything looks right. But the filter runs because your code asks for it. Someone calling the API with your public key can drop the .eq(…) and ask for every row.
2. Migrations don’t switch RLS on by themselves. In Postgres, a new table starts with RLS off. AI tools create tables with SQL migrations, so unless your project adds RLS automatically, the protection exists only if the migration contains the line that turns it on.
3. Testing as yourself proves nothing. You test with your own account, see your own data and move on. The leak only shows up when a second user, or nobody at all, asks for data that isn’t theirs.
Here is the migration from one of our own test apps, a small Lovable-style document manager that we deliberately built with this mistake:
create table public.documents (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users (id) on delete cascade,
title text not null,
content text not null default '',
created_at timestamptz not null default now()
);
grant select, insert, update, delete on table public.documents to anon, authenticated;There is no enable row level security and the table is granted to anon, the role used by visitors who are not signed in. Every visitor of the site can read, change and delete every user’s documents.
Check your own app in five minutes
You don’t need to read every migration. These three checks find most problems.
Open the Security Advisor
In your Supabase dashboard, open Advisors → Security Advisor. It flags, among other things, tables in the public schema without RLS (lint 0013), tables that have policies while RLS is still off (0007) and views that bypass RLS (0010). Fix every red entry before anything else.
List every table without RLS
Run this in the SQL Editor. Every row it returns is a table that the API can serve without any row check:
select n.nspname as schema, c.relname as table_name
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where c.relkind in ('r', 'p')
and n.nspname = 'public'
and not c.relrowsecurity;Find policies that allow everything
A policy of using (true) turns RLS on in name only. This query lists them:
select tablename, policyname, cmd, roles, qual, with_check
from pg_policies
where schemaname = 'public'
and (qual = 'true' or with_check = 'true');Some of them are intentional, for example a public list of blog posts. Each one should be something you can explain.
The owner-only pattern, step by step
Most tables in a typical app belong to one user: notes, documents, settings, uploads. For all of them the same four policies work. Here is the complete fix for the documents table above:
alter table public.documents enable row level security;
revoke all on table public.documents from anon;
create policy "Owners can read their documents"
on public.documents for select
to authenticated
using ((select auth.uid()) = user_id);
create policy "Owners can add documents"
on public.documents for insert
to authenticated
with check ((select auth.uid()) = user_id);
create policy "Owners can edit their documents"
on public.documents for update
to authenticated
using ((select auth.uid()) = user_id)
with check ((select auth.uid()) = user_id);
create policy "Owners can delete their documents"
on public.documents for delete
to authenticated
using ((select auth.uid()) = user_id);
create index if not exists documents_user_id_idx on public.documents (user_id);What each part does:
enable row level securityswitches the check on. From now on nothing gets through unless a policy allows it.revoke all … from anonremoves access for visitors who are not signed in. If signed-out visitors never need this table, this is a second lock behind RLS.to authenticatedlimits each policy to signed-in users. Without it, the policy also runs foranon, which is wasted work at best.(select auth.uid())reads the ID of the signed-in user from their session token. Wrapping it inselectlets Postgres compute it once per query instead of once per row, which matters for large tables.- The index on
user_idkeeps the policy fast, because every query now filters by that column.
For your own table and column names, the RLS policy builder writes these policies, plus the team and public-read variants, and gives you a test script.
USING and WITH CHECK, explained
The two clauses answer different questions, and mixing them up is a classic way to leave a hole.
| Clause | Question it answers | Used by |
|---|---|---|
using (…) | Which existing rows may this user see or touch? | select, update, delete |
with check (…) | Is this new or changed row allowed to be written? | insert, update |
An update needs both: using decides which rows you may change, with check decides what they may look like afterwards. If you leave out with check, Postgres reuses the using condition for the new row, which is safe. The hole is a with check that is looser than using, such as with check (true): then a user can change user_id to someone else’s ID and hand their row over, or move data between accounts.
One more trap: an update only reaches rows the user is also allowed to select, so every update policy needs a matching select policy. With an update policy but no select policy, update finishes without an error and changes nothing. If saves “silently do nothing” after you add RLS, check the select policy first.
Shared data: teams and workspaces
As soon as several users share data, the owner check becomes a membership check. The clean way is a small helper function that looks up the membership table:
create schema if not exists private;
create or replace function private.is_member(ws uuid)
returns boolean
language sql
security definer
set search_path = ''
stable
as $$
select exists (
select 1 from public.workspace_members m
where m.workspace_id = ws
and m.user_id = (select auth.uid())
);
$$;
create policy "Members can read their team's projects"
on public.projects for select
to authenticated
using (private.is_member(workspace_id));Three details make this safe:
security definerlets the function readworkspace_memberseven though that table has its own RLS. Without it, the check can run into the policies of the table it is checking, and the lookup fails or loops.set search_path = ''forces fully qualified names likepublic.workspace_members, so nobody can slip in a look-alike table or function. The Security Advisor flags functions without it (lint 0011).- The
privateschema is not exposed through the Data API, so the function can’t be called from the browser as an endpoint.
The membership table itself needs RLS as well, and users must not be able to add themselves to a workspace. Let inserts into workspace_members happen through an invite flow on the server, not through a client policy.
Five mistakes that keep data open
A policy that says yes to everyone
using (true) is the default suggestion in some templates (“Enable read access for all users”). It is right for public content and wrong for everything else.
Checking roles in user_metadata
user_metadata (stored as raw_user_meta_data) can be changed by the signed-in user themselves. A policy like (auth.jwt() -> 'user_metadata' ->> 'role') = 'admin' lets anyone make themselves admin. Store roles in app_metadata, which only your server can write, or in a table with its own RLS. The Security Advisor flags this as lint 0015.
using ((select auth.jwt() -> 'user_metadata' ->> 'role') = 'admin')using ((select auth.jwt() -> 'app_metadata' ->> 'role') = 'admin')Views that skip RLS
A normal view runs with the rights of the user who created it, which in Supabase is an admin role. It shows every row, even if the table underneath has perfect policies. On Postgres 15 and later, create views with security_invoker so they check the caller’s rights:
create view public.document_titles
with (security_invoker = true)
as select id, title, user_id from public.documents;The secret key in the browser
The secret key (sb_secret_…, or the older service_role key) bypasses RLS completely. If it appears in frontend code or a VITE_ variable, every policy in this guide is irrelevant. Keep it in server code and edge functions only, and rotate it if it ever shipped to the browser.
Edge functions that trust the request
An edge function that uses the secret key and takes a userId from the request body does the same damage as a missing policy. Read the user from the verified session token instead, and check that they may touch the record before you use admin rights.
Storage buckets need policies too
Files in Supabase Storage are rows in the storage.objects table, protected by the same mechanism. A common, safe layout puts each user’s files in a folder named after their user ID:
create policy "Users read their own files"
on storage.objects for select
to authenticated
using (
bucket_id = 'documents'
and (storage.foldername(name))[1] = (select auth.uid()::text)
);Add matching insert, update and delete policies, and check that the bucket is not marked public unless every file in it may be seen by anyone with the link.
Test your policies as a real user
The dashboard and the secret key ignore RLS, so “I can see my data in the dashboard” tells you nothing. Instead, pretend to be a user inside a transaction and roll it back afterwards:
begin;
set local role authenticated;
set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
select count(*) from public.documents;
rollback;Replace the ID with a real user ID from Authentication → Users. The count should match that user’s rows only. Then check what a signed-out visitor sees:
begin;
set local role anon;
select count(*) from public.documents;
rollback;After the fix above this fails with permission denied for table documents, which is exactly what you want. For a project that changes often, put these checks into database tests (Supabase supports pgTAP tests with supabase test db) so a future migration can’t quietly undo them.
What our audit reports for this bug
We keep a set of small, deliberately broken test apps to measure ShipRely’s audit engine. The documents app from this guide is one of them. A matching clean twin, a profiles table with correct owner policies, sits in the same repository, and the audit must stay quiet about it.
For the broken table, the engine reports one finding rated critical: the table never enables row level security, it is granted to anon and authenticated, and the only user_id filter lives in the browser code. The finding points to the migration and to src/hooks/useDocuments.ts, maps to CWE-862 and comes with the fix above as a prompt. That is the format we aim for on every finding: what is wrong, where it is, how sure we are, and what to paste into your AI builder.
A fix prompt for your AI builder
If you build with Lovable, Cursor, Claude Code or Bolt, you can hand the whole fix to your tool. Paste this and review the migration it writes before you apply it:
Add a new Supabase migration for the table public.documents (replace with your table name). Enable row level security on it. Revoke all privileges from the anon role. Create four policies for the authenticated role only: select, insert, update and delete, each allowing access only when (select auth.uid()) = user_id. The update policy needs both USING and WITH CHECK. Add an index on user_id if none exists.
Do not use the service role key in any browser code. Do not change any other table. Afterwards, show me the full migration and list every other table in the public schema that has RLS disabled.
Checklist before you launch
Supabase RLS launch checklist
0/10 done
Your progress is saved in this browser only.
Frequently asked questions
Is the Supabase anon or publishable key a secret?
No. It is meant to be in your browser code and anyone can copy it from your site. It only identifies your project; what it can reach is decided by your grants and RLS policies. The secret key (sb_secret_…, or the older service_role key) is different: it bypasses RLS and must never reach the browser.
What happens if RLS is enabled but a table has no policies?
Nobody using the public or signed-in roles can read or write any row. Postgres denies by default when RLS is on and no policy allows the action. Your app will look broken, but your data is safe; add the policies you need.
Does row level security make my app slow?
Usually not noticeably, if you follow two habits: wrap auth.uid() in a select, as in (select auth.uid()) = user_id, and add an index on the column your policy filters by, such as user_id.
Do I still need RLS if my app only uses edge functions?
If the browser never talks to a table and the role your API uses has no grants on it, the table is not reachable through the Data API. Most AI-built apps do query tables from the browser, though, and turning RLS on costs nothing, so enable it on every table in the public schema anyway.
Does Lovable or Bolt add RLS automatically?
Don’t rely on it. Whether a table is protected depends on the exact migration that created it. Run the check in this guide against your own project and look at every table it lists.
Sources
- 1.Row Level Security — Supabase Docs
- 2.Performance and Security Advisors — Supabase Docs
- 3.Understanding API keys — Supabase Docs
- 4.Storage access control — Supabase Docs
- 5.Testing your database — Supabase Docs
- 6.Row Security Policies — PostgreSQL Documentation
- 7.CWE-862: Missing Authorization — MITRE
- 8.A01 Broken Access Control — OWASP Top 10