Skip to content

Instantly share code, notes, and snippets.

@chupzzz
Created September 25, 2024 16:18
Show Gist options
  • Save chupzzz/27da56655046da4eb56fea035c098725 to your computer and use it in GitHub Desktop.
Save chupzzz/27da56655046da4eb56fea035c098725 to your computer and use it in GitHub Desktop.
Supabase: LITE JS request without official lib

Sometimes you need to get just a few values from your public Supabase table. It can be done using vanilla JS without official library and save you 100 kb.

Supabase API endpoint

Select all fields from table by id:

https://your-db-id.supabase.co/rest/v1/your-table?select=*&id=eq.your-id

But we have to pass public key. See JS wrapper below.

// Supabase credentials. Can be found in the settings of your project
const supaUrl = 'https://base-id.supabase.co'
const supaKey = 'public-key-hash'
/**
* Retrieve a row from table by its ID.
*
* @param {string} table Table where we're looking for our row.
* @param {string} id The ID of the row to retrieve.
* @returns {Promise<*|{}>} The row object with the given ID, or `undefined` if it was not found.
*/
export async function apiGetRow (table, id) {
const url = `${supaUrl}/rest/v1/${table}`
// If we skip params - it will return all rows from the table
const params = `?select=*&id=eq.${id}`
try {
const response = await fetch(url + params, {
method: 'GET',
headers: {
'Authorization': `Bearer ${supaKey}`,
'apikey': supaKey,
},
})
const res = await response.json()
return res[0]
} catch (error) {
console.error('Could not retrieve Supabase data', error)
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment