Supabase “new row violates row-level security policy” – causes and fix

By Abheesht Tripathi · Published

new row violates row-level security policy for table "notes"  (code 42501)

What it means

Row Level Security is on for the table, and the row you tried to write did not pass any WITH CHECK rule for the role your request ran as. Postgres refuses the write. It is not a bug in your client library: the database is doing what the policies say.

The five usual causes

  1. There is no INSERT (or UPDATE) policy at all. A table with only a SELECT policy can be read but never written.
  2. The request runs as anon, the policy is to authenticated. Common in server code (Next.js route handlers, server actions, Edge Functions) when the user's session isn't passed to the Supabase client, so the request goes out with only the anon key.
  3. user_id is not sent. The policy checks auth.uid() = user_id, the insert leaves user_id empty, null = uid is not true, so the row is rejected.
  4. .insert().select() or upsert. Returning the new row also needs a SELECT policy, and upsert needs INSERT and UPDATE policies and SELECT (Postgres checks SELECT on every upsert, whether or not you return the row).
  5. Storage uploads. The same error comes from storage.objects when the bucket has no INSERT policy for the uploader; upsert: true needs UPDATE and SELECT too.

The fix

Give each role exactly the write it needs, and let the database fill in the owner:

-- fill user_id automatically
alter table public.notes alter column user_id set default auth.uid();

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

create policy "read own rows" on public.notes
  for select to authenticated
  using ((select auth.uid()) = user_id);

-- only if you use upsert or edit rows
create policy "update own rows" on public.notes
  for update to authenticated
  using ((select auth.uid()) = user_id)
  with check ((select auth.uid()) = user_id);

For storage, scope uploads to a folder named after the user:

create policy "upload to own folder" on storage.objects
  for insert to authenticated
  with check (
    bucket_id = 'avatars'
    and (storage.foldername(name))[1] = (select auth.uid())::text
  );

How to see which role your request ran as

In server code, call supabase.auth.getUser() on the same client right before the insert. If it returns no user, the request is anon and an authenticated policy will never match: fix the session handling (for example the cookie-based server client), not the policy.

What not to do

Don't turn RLS off, and don't put the service_role key in the browser to make the error go away. Both make every row writable by anyone who opens your app.

Related guides

More in Supabase RLS and Storage · all guides