Fix guide · updated 2026-11-16
Supabase "User not allowed" (AuthApiError 403 not_admin)
AuthApiError: User not allowed · 403 · not_admin
Your admin page fails with AuthApiError: User not allowed (status 403, code not_admin) when it lists, creates, invites or deletes users. Everything under supabase.auth.admin needs Supabase's secret key, and that key must never be in a browser. We ran Supabase's real Auth server with supabase-js 2.119, plus the fix on Supabase's Edge Functions runtime, and wrote down what each call does. Two surprises: signing in as your admin changes nothing, because supabase-js sends your project's public key for these calls, not the user's session; and the "is admin" flag many apps check, in user_metadata, is one any user can set on themselves.
What the error means
Supabase Auth runs its admin calls only for a token whose role is service_role (or Supabase's own supabase_admin). Your secret key gives that role, and so does the legacy service_role key. The publishable key (legacy: the anon key) gives anon, and a signed-in user's session gives authenticated. Anything but the secret key gets:
403 {"code":"not_admin","message":"User not allowed"}
In our test, every admin call answered that from a client made with the anon key: listUsers(), createUser(), getUserById(), updateUserById(), deleteUser(), inviteUserByEmail() and generateLink(). In supabase-js 2.119 it arrives as AuthApiError, with status 403 and error.code "not_admin". Supabase's Auth log adds the reason: this token needs to have one of the following roles: service_role, supabase_admin.
1. Signing in as an admin changes nothing
We signed a user in and called auth.admin.listUsers() from that same client. supabase-js still sent the project's anon key for it, not the user's session, so it failed the same way. Even our admin user, with "role": "admin" in their app_metadata, got User not allowed. Sending the user's own token by hand failed too, because its role is authenticated. No change to your app's login fixes this. These calls have to run somewhere that holds the secret key.
2. Don't put the secret key in your app
The quick fix an AI tool may suggest is to create the client with the secret key, or the service_role key, in your frontend. Don't. That key skips every row level security policy and can read, change and delete every user, and anyone can read it in your site's files. Supabase's new secret keys (sb_secret_…) refuse to work from a browser and answer 401, according to Supabase's docs. The legacy service_role key (a long key starting with eyJ) does work there, which is worse. If either key was ever in your frontend code, treat it as leaked and replace it: Supabase's guide Rotate a leaked or compromised API key shows how.
3. The fix: an Edge Function that checks who is calling
Move the admin call into an Edge Function. The secret key stays on Supabase's servers, your app sends the user's session, and the function decides. This one deletes a user, for admins only:
import { createClient } from 'npm:@supabase/supabase-js@^2'
import { corsHeaders } from 'npm:@supabase/supabase-js@^2/cors'
// The secret key: SUPABASE_SECRET_KEYS with the new keys, else the legacy service_role key.
const secretKeys = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS') ?? '{}')
const secretKey = secretKeys['default'] ?? Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')
const supabaseAdmin = createClient(Deno.env.get('SUPABASE_URL')!, secretKey)
export default {
fetch: async (req) => {
if (req.method === 'OPTIONS') {
return Response.json({ ok: true }, { headers: corsHeaders })
}
try {
// 1. Who is calling? supabase.functions.invoke sends the user's token.
const token = (req.headers.get('Authorization') ?? '').replace('Bearer ', '')
const { data: { user } } = await supabaseAdmin.auth.getUser(token)
if (!user) {
return Response.json({ error: 'Please sign in again.' }, { status: 401, headers: corsHeaders })
}
// 2. Is the caller an admin? Only the secret key can change app_metadata.
if (user.app_metadata?.role !== 'admin') {
return Response.json({ error: 'Only admins can do this.' }, { status: 403, headers: corsHeaders })
}
// 3. Only now, the admin call.
const { userId } = await req.json()
const { error } = await supabaseAdmin.auth.admin.deleteUser(userId)
if (error) {
return Response.json({ error: error.message }, { status: error.status ?? 500, headers: corsHeaders })
}
return Response.json({ ok: true }, { headers: corsHeaders })
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return Response.json({ error: message }, { status: 400, headers: corsHeaders })
}
},
}
Supabase gives every function both SUPABASE_SECRET_KEYS and the legacy SUPABASE_SERVICE_ROLE_KEY, so this works with either kind of key. Keep Verify JWT on for this function (the default). In our test, on the Edge Functions runtime the Supabase CLI uses, with the real supabase-js:
- Not signed in: 401,
Please sign in again. - A normal user: 403,
Only admins can do this.Also for a user who had put"role": "admin"in their ownuser_metadata(section 5). - An admin:
{"ok":true}, and the user was gone. - An id that doesn't exist: 404,
User not found. An id that isn't a UUID: 400 with supabase-js's own message. Without thetry/catch, that one crashed the function with a bareInternal Server Error.
For other admin calls, keep steps 1 and 2 and change step 3, for example to listUsers() or inviteUserByEmail(email).
4. Call it from your app
import { FunctionsHttpError } from '@supabase/supabase-js'
const { error } = await supabase.functions.invoke('admin-delete-user', {
body: { userId },
})
if (error instanceof FunctionsHttpError) {
const body = await error.context.json().catch(() => ({}))
setError(body.error ?? 'Something went wrong. Please try again.')
} else if (error) {
setError("We couldn't reach the server. Please try again.")
}
supabase.functions.invoke sends the signed-in user's token by itself. When the function answers with an error, supabase-js only says Edge Function returned a non-2xx status code, and the function's own message (like Only admins can do this.) is in error.context, as above. See our guide to that message.
5. Keep "is admin" in app_metadata, never in user_metadata
app_metadata: only the secret key can change it. In our test, a signed-in user who tried got 403,Updating app_metadata requires admin privileges.user_metadata: every signed-in user can change their own.updateUser({ data: { role: 'admin' } })worked in our test, and the new value was in that user's next token. Never decide permissions on it.
To make someone an admin, run this once in the SQL editor:
update auth.users
set raw_app_meta_data = raw_app_meta_data || '{"role": "admin"}'
where email = 'you@example.com';
In our test the function let that user in right away, without signing out and in again, because getUser() reads the account, not the token. Removing it worked right away too:
update auth.users
set raw_app_meta_data = raw_app_meta_data - 'role'
where email = 'you@example.com';
If your app keeps roles in a table instead (many Lovable apps have a user_roles table), check that table in step 2 of the function, with supabaseAdmin.
Other messages from the same calls
This endpoint requires a valid Bearer token(401,no_authorization): the request had noAuthorizationheader at all, for example a hand-writtenfetch.invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments(403,bad_jwt): the header holds something that isn't a token.invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid(403,bad_jwt): a service_role key from another Supabase project.Updating app_metadata requires admin privileges(403,not_admin): a user tried to change their ownapp_metadata(section 5).
If an AI tool built your app
Give your tool this prompt:
My app calls supabase.auth.admin from the browser and gets "User not allowed" (403 not_admin). Don't put the secret or service_role key in the frontend. Create a Supabase Edge Function for this action that: answers the CORS preflight with corsHeaders from npm:@supabase/supabase-js@^2/cors; creates an admin client with the default key from SUPABASE_SECRET_KEYS, or SUPABASE_SERVICE_ROLE_KEY if there's none; gets the caller with supabaseAdmin.auth.getUser() and the token from the Authorization header, and answers 401 if there's no user; answers 403 unless user.app_metadata.role is 'admin'; only then runs the admin call, inside try/catch. In the app, call it with supabase.functions.invoke and show the function's error message from error.context. Don't change anything else.
Not quite your error?
- "Edge Function returned a non-2xx status code": read your function's real answer.
- The browser blocks the call to your function with a CORS error: Supabase Edge Function CORS errors.
- "Database error deleting user": the delete itself fails in the database.
- Not sure what else your frontend gives away: our security checklist for AI-built apps.
Still stuck?
Open Supabase's Auth log (Logs, Log Type Auth) and find the 403. If the call came from your Edge Function and still says User not allowed, the function's client wasn't made with the secret key: check the createClient line at the top. If it says Updating app_metadata requires admin privileges, that change has to go through the function or the SQL editor too.
Other Supabase problems? See Supabase fixes.