supabasesupabase-database

INSERT into the table and return id of the record Supabase JS


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?


Solution

  • 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