Felipe Chernicharo
Felipe Chernicharo

Reputation: 4547

Supabase: update/delete entries in auth.users from the client

I've learned from supabase docs and this discussion that we can pass in a service_role key to the supabaseClient so to bypass RLS (row-level-security), and therefore be able to access/modify data in the auth.users table client-side.

For now, I'm using a second instance of the supabase client to perform updates to the auth.users table when needed.

import { createClient } from "@supabase/supabase-js"; // version  "2.0.4"

const {
  VITE_PROJECT_URL,
  VITE_ANON_PUB,
  VITE_SERVICE_ROLE,
} = import.meta.env

export const supabase = createClient(VITE_PROJECT_URL, VITE_ANON_PUB); // 1. regular client

export const supabaseAdmin = createClient(VITE_PROJECT_URL, VITE_SERVICE_ROLE) // 2. admin client

This approach works great in Dev mode: I'm capable of updating/deleting entries in auth.users alright.

// works in Dev, Error in Prod
 const { data } = await supabaseAdmin.auth.admin.deleteUser(customer.auth_id);

// example from docs: slightly different syntax 
const { data: user, error } = await supabase.auth.api.deleteUser(
  '715ed5db-f090-4b8c-a067-640ecee36aa0'
)

However, this is not working in production. Getting the following error: Uncaught Error: supabaseKey is required.

That said, my question is: How should I deploy code that interacts the auth.users table? Will I need a server function to do only this? (Already trying it BTW, having that same problem supabaseKey is required though

Upvotes: 1

Views: 2595

Answers (1)

Felipe Chernicharo
Felipe Chernicharo

Reputation: 4547

For the record, managed to have it fixed 🎉!

The error was caused by bad environment variables setup on my hosting provider (netlify). Totally a stupid mistake, I'm the only one to blame

However, I learned a bit on my way debugging it and would like to share it here for reference

mistake #1
Double check env variables setup in whatever platform you're using to host the app (netlify, vercel, etc.), this can save you hours of useless frustration...🤦🏽

mistake #2
Supabase docs say it all the time: Don't use your service_role in frontend code. So if you don't have a backend, use cloud functions for the job. Pretty much all providers nowadays have this feature.

mistake #3
not setting the access-control-allow-origin header in the server-side function respose. This should spare you from problems with cors

Upvotes: 1

Related Questions