Supabase "Database error deleting user": find what blocks the delete and fix it
By AI App Medic · Updated · Supabase · Auth · Postgres · Foreign keys
You open Authentication, Users in the Supabase dashboard, pick a user, click delete, and get:
Failed to delete user: Database error deleting user
From code it is the same thing. supabase.auth.admin.deleteUser(id) returns an error with status 500 and this body:
{"code":500,"error_code":"unexpected_failure","msg":"Database error deleting user"}
Some projects show the database message instead, which is more useful:
update or delete on table "users" violates foreign key constraint "profiles_id_fkey" on table "profiles"
It usually shows up the first time a real user asks you to close their account, or when you try to clean out test accounts before launch. Apple also requires apps that let people create an account to let them delete it, so a broken delete can hold up an App Store review.
What the error means
Deleting a user removes their row from auth.users. Supabase's own tables in the auth schema (sessions, identities, refresh tokens) are cleaned up by the Auth server. Your tables are not. Each foreign key that references auth.users, directly or through another table, has an ON DELETE rule, and the default is NO ACTION: Postgres refuses to delete a row that other rows still point at. Auth hides most database errors behind the generic message.
In apps generated by Lovable, Bolt or Cursor, the cause is nearly always one of three things:
- A table such as
profiles,orders,postsorsubscriptionsreferencesauth.users(id)orprofiles(id)with noON DELETErule. - A trigger on
auth.usersruns on delete (or on update) and its function fails. - The user still owns files in Supabase Storage. The Supabase docs say you cannot delete a user who owns Storage objects.
Supabase's own example for a profiles table uses references auth.users on delete cascade. Generated code often drops the on delete cascade part, and every table added later copies the same pattern.
Step 1: get the real database error
Do not guess from the generic message. Two ways to see the actual cause:
Postgres logs. In the dashboard, open Logs and pick Postgres (or the Auth logs, which link to the same request). Filter for ERROR around the time of the failed delete. You are looking for a line with 23503 (foreign key violation), a function name from a trigger, or storage.objects.
A delete you roll back. In the SQL Editor, run the delete yourself inside a transaction that is always undone:
begin;
delete from auth.users where id = 'PUT-THE-USER-ID-HERE';
rollback;
If something blocks it, the editor shows the full error, for example ERROR: 23503: update or delete on table "users" violates foreign key constraint "orders_user_id_fkey" on table "orders", with a DETAIL line naming the key. If it runs without an error, the rollback puts the user back and the problem is not in the database: check that your code calls the admin API with the secret key (see below). Keep the rollback line. Without it, this really deletes the user.
Step 2: list the foreign keys and their delete rules
This query lists every foreign key in your public schema, what it points at, and what happens on delete:
select
c.conrelid::regclass as child_table,
c.conname as constraint_name,
c.confrelid::regclass as points_at,
case c.confdeltype
when 'a' then 'NO ACTION (blocks delete)'
when 'r' then 'RESTRICT (blocks delete)'
when 'c' then 'CASCADE'
when 'n' then 'SET NULL'
when 'd' then 'SET DEFAULT'
end as on_delete,
pg_get_constraintdef(c.oid) as definition
from pg_constraint c
where c.contype = 'f'
and c.connamespace = 'public'::regnamespace
order by points_at::text, child_table::text;
Read it as a chain. Start with rows where points_at is auth.users. Then follow each of those tables: if profiles cascades from auth.users but posts points at profiles with NO ACTION, the delete still fails, one level down. That is the case people miss most often: they fix profiles_id_fkey, try again, and get the same error with a different table name.
Step 3: pick the right rule for each table
- ON DELETE CASCADE for data that has no meaning without the user: profile, settings, notification preferences, private drafts, API tokens. The rows go with the account.
- ON DELETE SET NULL for records you have to keep: orders, invoices, payments, messages in a shared thread, audit logs. The row stays and loses its owner. The column must allow null, and your UI must handle a missing author, for example by showing "Deleted user".
- RESTRICT or NO ACTION only where a person should act first, such as the owner of a team with other members. Then your delete-account code has to handle that case (transfer ownership or delete the team) before it deletes the user.
Check your legal side for the keep-or-delete decision. Tax records often have to be kept for years, while personal data in them may need to be removed on request. SET NULL plus clearing name and email columns covers most cases.
Step 4: replace the constraint in a migration
Postgres cannot change the rule of an existing foreign key, so drop it and add it again with the same name. Doing both in one ALTER TABLE means there is no moment without the constraint:
-- supabase/migrations/20261204120000_fix_user_delete_rules.sql
-- Belongs only to the user: delete with the account
alter table public.profiles
drop constraint profiles_id_fkey,
add constraint profiles_id_fkey
foreign key (id) references auth.users (id) on delete cascade;
alter table public.posts
drop constraint posts_user_id_fkey,
add constraint posts_user_id_fkey
foreign key (user_id) references public.profiles (id) on delete cascade;
-- Must be kept: keep the order, drop the owner
alter table public.orders alter column user_id drop not null;
alter table public.orders
drop constraint orders_user_id_fkey,
add constraint orders_user_id_fkey
foreign key (user_id) references auth.users (id) on delete set null;
Use the constraint names from the Step 2 query; yours may differ. Put this in a migration file, not only in the SQL Editor. If the project lives in a GitHub repo through Lovable, Bolt or the Supabase CLI, a change made only in the dashboard is lost the next time the schema is rebuilt from migrations, or worse, the next generated migration recreates the old constraint.
Two things for bigger tables. Adding a foreign key checks every existing row while holding a lock. On a table with millions of rows, add it with not valid and validate it in a second statement, which takes a lighter lock:
alter table public.events
drop constraint events_user_id_fkey,
add constraint events_user_id_fkey
foreign key (user_id) references auth.users (id) on delete cascade not valid;
alter table public.events validate constraint events_user_id_fkey;
And index the foreign key column. Postgres does not do it for you, and every user delete has to find the matching child rows. Without an index that is a full scan of each table, which can make deletes slow enough to time out:
create index if not exists posts_user_id_idx on public.posts (user_id);
create index if not exists orders_user_id_idx on public.orders (user_id);
Step 5: check triggers on auth.users
If the rolled-back delete in Step 1 fails with a function name instead of a constraint, a trigger is the problem. List them:
select tgname, pg_get_triggerdef(oid)
from pg_trigger
where tgrelid = 'auth.users'::regclass
and not tgisinternal;
You will usually see on_auth_user_created, which runs on insert and does not affect deletes. Look for anything that fires on delete or on update: an audit log, a "sync email to profiles" trigger, a cleanup function. The usual bugs are the same ones that break sign-ups: the function sets search_path = '' but refers to profiles instead of public.profiles, it writes to a table that now has a different shape, or it is not security definer and lacks rights on the table it touches. Run the function body by hand to see the error, fix it, and test the rolled-back delete again. The sign-up version of this problem is covered in Database error saving new user.
A delete trigger that removes the user's rows by hand is usually a sign the foreign keys should cascade instead. Once Step 4 is done, you can often drop that trigger.
Step 6: remove the user's Storage files first
If the error mentions storage.objects, or the user uploaded an avatar or documents, the files are in the way. Check what they own:
select bucket_id, name, created_at
from storage.objects
where owner_id = 'PUT-THE-USER-ID-HERE';
Remove them through the Storage API, not with a delete on storage.objects. Deleting the rows in SQL does not remove the files themselves, and recent projects block direct deletes on the Storage tables anyway.
A delete-account Edge Function that works
Put the whole flow on the server, where the secret key lives. Calling auth.admin.deleteUser() from the browser fails with a different error, User not allowed, and needs a key that must never be in the front end. This function lets a signed-in user delete their own account. It assumes files are stored under a folder named after the user id, which is what most generated upload code does:
// supabase/functions/delete-account/index.ts
import { createClient } from 'npm:@supabase/supabase-js@2'
const cors = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { ...cors, 'Content-Type': 'application/json' } })
Deno.serve(async (req) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: cors })
try {
const admin = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
{ auth: { persistSession: false, autoRefreshToken: false } }
)
// 1. Who is asking? Use the token from the request, never a user id from the body.
const token = (req.headers.get('Authorization') ?? '').replace('Bearer ', '')
const { data: { user }, error: authError } = await admin.auth.getUser(token)
if (authError || !user) return json({ error: 'Not signed in' }, 401)
// 2. Remove their files in each bucket that holds user uploads.
for (const bucket of ['avatars', 'documents']) {
const { data: files } = await admin.storage.from(bucket).list(user.id, { limit: 1000 })
const paths = (files ?? []).map((f) => `${user.id}/${f.name}`)
if (paths.length) {
const { error } = await admin.storage.from(bucket).remove(paths)
if (error) return json({ error: `Could not remove files in ${bucket}` }, 500)
}
}
// 3. Delete the user. Foreign keys with ON DELETE rules take care of the rest.
const { error } = await admin.auth.admin.deleteUser(user.id)
if (error) {
console.error('deleteUser failed', error)
return json({ error: 'Could not delete the account' }, 500)
}
return json({ ok: true })
} catch (err) {
console.error('delete-account failed', err)
return json({ error: 'Internal error' }, 500)
}
})
Adjust the bucket names, and if a user can have more than 1,000 files or nested folders, page through list and recurse into folders. In the app, call it with supabase.functions.invoke('delete-account'), then call supabase.auth.signOut() and send the user to the home page. If the call fails before your code runs, see Edge Function returned a non-2xx status code.
When the database error is gone, the call can still fail for non-database reasons. A 403 with User not allowed means the admin client was created with the anon or publishable key, or with a user's token in a global header. Use the secret key and no user session on that client.
What about soft delete?
auth.admin.deleteUser(id, true) soft-deletes the user: Auth keeps the row in auth.users and marks it deleted, so foreign keys are not touched and nothing blocks. It cannot be undone, and your own tables still hold the user's data, so it does not answer a "delete my data" request by itself. Use it only if you have a reason to keep references intact and you clean your own tables separately. For most apps, fixing the foreign keys is the right answer.
Prevention
- Every new table that has a
user_idgets an expliciton delete cascadeoron delete set nullwhen it is created. Add that rule to the instructions you give your AI tool. - Run the Step 2 query before launch and after any big schema change. No row in it should say
NO ACTIONunless you chose it. - Keep a test that signs up a user, creates a row in every user-owned table, uploads a file, deletes the account, and checks it worked.
- Index every foreign key column that points at users.
- Our security checklist for AI-built apps covers the other admin and key mistakes that tend to appear next to this one.
FAQ
Will ON DELETE CASCADE delete other users' data?
Only rows that point at the user being deleted, plus rows that point at those rows if they also cascade. Before you switch a table to cascade, run the foreign key query in this guide and read the whole chain. If a shared object such as a team or a project would go with its creator, use SET NULL or move ownership first.
Why can I delete some users but not others?
The delete only fails for users who have rows in a table whose foreign key has no ON DELETE rule, or who own Storage files. A test account that never created anything deletes fine, and the first real customer who asks to close their account does not.
Is it safe to delete a user straight from auth.users in SQL?
For a one-off it works and follows the same rules, so it fails for the same reasons and shows you the real error. In the app, use auth.admin.deleteUser() from a server or Edge Function so Storage cleanup and logging happen in one place.
Does deleting the user sign them out right away?
Not completely. Their sessions and refresh tokens go, so they cannot get a new access token, but an access token already issued stays valid until it expires, one hour by default. Keep the default expiry and check the user still exists on sensitive actions.
Can I just delete the profile row first?
Yes, deleting the blocking rows by hand lets that one delete through. It does not fix the next one. Set the ON DELETE rule so the database handles it every time.
Related guides
- Supabase "AuthApiError: User not allowed" on auth.admin calls: the cause and a safe fix
- Supabase signUp fails with "Database error saving new user": fix the auth.users trigger
- Supabase storage bucket public by mistake: close it and switch to signed URLs
- Supabase auth email not sending in a Lovable app: the SMTP setup that actually works
- Supabase login redirects to localhost (or the preview URL) after deploy: how to fix it