KevinTale
KevinTale

Reputation: 1878

Cannot insert to table with authenticated role policy in Supabase

I'm trying to insert a row in my table which has RLS enabled and the Enable insert for authenticated users only policy added. Unfortunately, I cannot insert even though I'm correctly login.

Steps to reproduce:

  1. Create submissions table
create table submission (
  stuff text
);
  1. Enable RLS
alter table submissions
  enable row level security
  1. Add Policy
CREATE POLICY "Enable insert for authenticated users only" ON public.submissions FOR INSERT WITH CHECK (auth.role() = 'authenticated');
  1. On client, I log in using magic links (the object is correctly added in localstorage so I know I'm log in)

  2. I try to insert

const { data, error } = await supabase
 .from("submissions")
 .insert({ stuff: 'hello' });

The Authorization Bearer <Jwt> is present in http call.

  1. But I got error
{
  "hint":null,
  "message":"new row violates row-level security policy for table \"submissions\"",
  "code":"42501",
  "details":null
}

What am I doing wrong here?

Upvotes: 7

Views: 5214

Answers (2)

Mark Burggraf
Mark Burggraf

Reputation: 626

Yep -- I ran into the same thing the first time I tried to add a RLS policy that only allowed INSERT and not SELECT (for letting users log info to a table.)

We've discussed making { returning: "minimal" } the default for insert, update, and delete, but I don't think that will happen.

It's just something to be aware of (and it is in the documentation, but easy to miss.)

Upvotes: 2

KevinTale
KevinTale

Reputation: 1878

I found what was wrong.

The thing is, the default behaviour of supabase.insert returns the row we just inserted, in other words it selects it (reads it) from the table. As I didn't added a Policy to read the table, it failed.

So two solutions:

  1. Add a new Policy to be able to SELECT from that table
  2. Add { returning: "minimal" } to the supabase.insert so it does not send the row back

Upvotes: 13

Related Questions