Supabase "new row violates row-level security policy": what it means and the safe fix
You insert a row with supabase-js and get: new row violates row-level security policy for table "todos" It is Postgres error 42501. You see HTTP 403 for signed-in requests and 401 for anonymous ones. What it me
You insert a row with supabase-js and get:
new row violates row-level security policy for table "todos"
It is Postgres error 42501. You see HTTP 403 for signed-in requests and 401 for anonymous ones.
What it means
Row Level Security is on for the table, but no INSERT or UPDATE policy's WITH CHECK clause allows the row you sent. The database is doing its job. It refuses to write the row.
Why it happens
- RLS is enabled and there is no INSERT policy, or its
WITH CHECKis false for this row. - The request ran as
anonbecause the user's session was not attached, soauth.uid()is null. - The
user_idcolumn is empty, or set to someone else's id. - You call
.insert(...).select(). The row that comes back also needs a matching SELECT policy.
How to fix it
- Confirm the user is signed in before writing.
supabase.auth.getUser()should return a user. - Default the owner column to the caller, and add owner-scoped policies:
alter table public.todos enable row level security;
alter table public.todos alter column user_id set default auth.uid();
create policy "insert own rows" on public.todos
for insert to authenticated
with check ((select auth.uid()) = user_id);
create policy "update own rows" on public.todos
for update to authenticated
using ((select auth.uid()) = user_id)
with check ((select auth.uid()) = user_id);
create policy "read own rows" on public.todos
for select to authenticated
using ((select auth.uid()) = user_id);
Fixes to avoid
- Turning RLS off. The error goes away and every visitor can read and write the table.
- A policy with
with check (true). Same result, with extra steps.
Check it is fixed
Insert as user A, which should work. Then, still signed in as A, try to insert a row with user B's user_id. That should fail. Then confirm that an anonymous visitor cannot read the table.
Same steps with the FAQ: https://proofforge.live/errors/new-row-violates-row-level-security-policy . To see whether your live app exposes any table to the public, run the free outside check at https://proofforge.live
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.