Fix “new row violates row-level security policy” in Supabase

Updated

Error messagenew row violates row-level security policy for table "profiles"

Postgres rejected the write because no policy allows it for the current user. Usually the table has a SELECT policy but no INSERT policy, the request went out as an anonymous user because the session wasn’t loaded yet, or the row’s user_id doesn’t match auth.uid(). Add an INSERT policy with a WITH CHECK on the owner column. Don’t disable RLS or use the service_role key in the browser to make the error go away.

Find which of the three causes it is

  1. No policy for this operation. List what the table has:
    select policyname, cmd, roles, with_check
    from pg_policies where tablename = 'profiles';
    If there is no row with cmd = INSERT (or ALL), that’s it.
  2. The request is anonymous. Log the session right before the insert: console.log((await supabase.auth.getSession()).data.session). null means the request used the anon role. This happens right after sign-up when email confirmation is on: there is no session until the user clicks the link.
  3. The owner doesn’t match. The client sends a user_id from somewhere other than the session, or sends none at all.

The fix

Let the database fill the owner and check it:

alter table public.profiles
  alter column user_id set default auth.uid();

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

Now the client doesn’t send user_id at all, and nobody can insert a row on someone else’s behalf.

Two cases that produce the same error:

  • upsert needs an UPDATE policy as well, because it can turn into an update.
  • .insert(...).select() returns the new row, so it must also pass a SELECT policy.

Same error on file upload

Storage keeps files in the storage.objects table, which has RLS too. Allow each user to write only to their own folder:

create policy "Users 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
);

Upload to a path that starts with the user id: avatars/<user-id>/photo.png.

Check that it worked

Sign in as user A and insert a row: it works. Then try to insert a row with user B’s id from user A’s session: it must fail with the same error. If the second insert succeeds, the policy is too broad.

AI agents often suggest alter table ... disable row level security or a service role client to “fix” this. Both remove the protection for every user, not just yours.

Sources