23

Based on the docs, inserting a new record

const { error } = await supabase
  .from('countries')
  .insert({ name: 'Denmark' })

returns

{
  "status": 201,
  "statusText": "Created"
}

For columns that are Is Identity, it automatically assigns a sequential unique number to the column.

How to get the ID of the newly inserted record on Supabase with JavaScript client?

3 Answers 3

57

You can add .select() after your insert statement in order to get the newly inserted record.

const { data, error } = await supabase
  .from('countries')
  .insert({ name: 'Denmark' })
  .select()

You will see the inserted record inside data variable. Note that retrieving the inserted record requires you to have not only insert permission, but select permission on RLS policies.

On a side note, you can click on the buttons on the right of the docs to view different use cases. You can see this example on Create a record and return it example. Supabase docs

Sign up to request clarification or add additional context in comments.

4 Comments

I've been using select() but gives me row level security issue, only skipped by using {returning: 'minimal'}. I'm using v.2
@Richi Double check your supabase-js version. {returning: 'minimal'} does not exist in v2.
thanks for the comment @dshukertjr but only works for me if i disable rls
@Richi That probably means that the user does not have the appropriate permission via RLS for performing the action. In order for the user to be able to insert and select the data, they need both insert and select permissions. Make sure they do have the permission, and if you are still hitting a wall, I would suggest you to create a separate question providing the RLS policies you have set.
1

As per the code comments in node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts.

Perform an INSERT into the table or view. By default, inserted rows are not returned. To return it, chain the call with .select().

Just add .select() at the end.

await supabase
  .from('countries')
  .insert({ name: 'Denmark', {returning: 'minimal'}})
  .select()

Comments

-1

I think you needed this:

const { data, error } = await supabase
  .from('countries')
  .insert({ name: 'Denmark', {returning: 'minimal'}})
  .select()

With this the data will only contain the id of the created country.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.