Supabase "AuthApiError: User not allowed" on auth.admin calls: the cause and a safe fix

By AI App Medic · Updated · Supabase · Auth · Security · Lovable

You asked the AI to build an admin page that lists users, invites a teammate or deletes an account. It wrote a call like supabase.auth.admin.listUsers(), and the page fails with:

AuthApiError: User not allowed
  status: 403
  code: "not_admin"

The raw response from the Auth server is {"code":"not_admin","message":"User not allowed"}. It happens for every method under supabase.auth.admin: listUsers, getUserById, createUser, inviteUserByEmail, generateLink, updateUserById and deleteUser. Signing in as the owner of the app does not change anything.

The common "fix" an AI tool suggests is to create the client with the service_role key. In a Lovable or Bolt app that runs in the browser, that makes the error go away and hands every visitor full control of your database. Here is what the error means and how to fix it without that risk.

Why it happens

The admin endpoints of Supabase Auth only accept a token whose role is service_role (or Supabase's internal supabase_admin). Each key and token carries a role:

Anything but the last one gets not_admin. In practice the error comes from one of three setups:

  1. The admin call runs in the browser. The client there uses the publishable key, as it should. This is the usual case in Lovable, Bolt and v0 apps.
  2. A server client was created with the wrong key. The environment variable named SUPABASE_SERVICE_ROLE_KEY actually holds the anon key, or the code falls back to the anon key when the variable is missing on the host.
  3. A server client has the secret key and a user's token in the same client. A common Edge Function pattern creates one client like this:
    const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
      global: { headers: { Authorization: req.headers.get('Authorization')! } },
    })
    supabase-js merges global headers over the key for the requests its auth client sends, so supabase.auth.admin.deleteUser() goes out with the user's token, whose role is authenticated. The key is right and the call still fails.

Step 1: confirm which key the request used

Open the Network tab and find the failing request to /auth/v1/admin/.... If it is there at all, the admin call runs in the browser, and that is your answer: it has to move to a server (Step 3).

If the call runs on a server, log which kind of key the client was created with, without printing the key itself:

const key = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
if (key.startsWith('sb_secret_')) console.log('secret key')
else if (key.startsWith('sb_publishable_')) console.log('publishable key: wrong for admin calls')
else console.log('legacy key with role:', JSON.parse(atob(key.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))).role)

A legacy key prints service_role or anon. If you see anon, the wrong value is stored in that variable. In the Supabase dashboard you can also open Logs, pick the Auth logs, and find the failed admin request; the entry usually names the roles the endpoint needed.

Step 2: do not put the secret key in the browser

The secret key bypasses every Row Level Security policy. In a browser anyone can read it from your JavaScript, then read, change and delete every row and every user. Supabase's new sb_secret_ keys refuse browser requests and return 401, but the legacy service_role key (a long string starting with eyJ) works from anywhere, which makes a leak worse.

If either key was ever in front-end code, in a VITE_ or NEXT_PUBLIC_ variable or in a public repository, treat it as leaked. The steps to replace it are in Supabase service role key exposed, and Vite env API key exposed explains why front-end variables are always public.

Step 3: move the admin action into an Edge Function

The function holds the secret key, checks who is calling, and only then calls the admin API. Keep two clients apart: an admin client created with the secret key and no user session, and the caller's token, which you only use to find out who they are. This function deletes a user, for admins only:

// supabase/functions/admin-delete-user/index.ts
import { createClient } from 'npm:@supabase/supabase-js@2'

const corsHeaders = {
  'Access-Control-Allow-Origin': 'https://your-app.com',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

function json(body: unknown, status = 200) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  })
}

// New projects get SUPABASE_SECRET_KEYS; older ones still have SUPABASE_SERVICE_ROLE_KEY.
const secretKeys = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS') ?? '{}')
const secretKey = secretKeys['default'] ?? Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!

// Admin client: secret key only. No global Authorization header, no stored session.
const admin = createClient(Deno.env.get('SUPABASE_URL')!, secretKey, {
  auth: { persistSession: false, autoRefreshToken: false },
})

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })

  try {
    // 1. Who is calling? functions.invoke sends the user's access token.
    const token = (req.headers.get('Authorization') ?? '').replace('Bearer ', '')
    const { data: { user }, error: authError } = await admin.auth.getUser(token)
    if (authError || !user) return json({ error: 'Please sign in again' }, 401)

    // 2. Is the caller an admin? app_metadata can only be set with the secret key or SQL.
    if (user.app_metadata?.role !== 'admin') return json({ error: 'Admins only' }, 403)

    // 3. Validate input, then do the admin action.
    const { userId } = await req.json().catch(() => ({}))
    if (typeof userId !== 'string') return json({ error: 'userId is required' }, 400)
    if (userId === user.id) return json({ error: 'You cannot delete your own account here' }, 400)

    const { error } = await admin.auth.admin.deleteUser(userId)
    if (error) return json({ error: error.message }, 400)
    return json({ ok: true })
  } catch (err) {
    console.error('admin-delete-user failed', err)
    return json({ error: 'Internal error' }, 500)
  }
})

Deploy it with supabase functions deploy admin-delete-user. Supabase provides SUPABASE_URL and the keys to every function, so there is no secret to set. If your Lovable app runs on Lovable Cloud, ask Lovable to create the function there with the same logic; the rules about keys are the same.

The same pattern works for listing users, inviting by email or banning: verify the caller, check the flag, then call admin.auth.admin. For listing, return only the fields the page needs, such as id, email and created_at, not the full user objects.

If the delete now reaches Supabase but fails with Database error deleting user, the key is fine and something in your database is blocking it, usually a foreign key without an ON DELETE rule. See Database error deleting user.

Step 4: mark who is an admin

Put the flag in app_metadata, which users cannot change. Run this once in the SQL editor:

update auth.users
set raw_app_meta_data = coalesce(raw_app_meta_data, '{}'::jsonb) || '{"role": "admin"}'::jsonb
where email = 'you@yourcompany.com';

The function above reads the user fresh with getUser, so the change applies right away. If you also check the flag in the front end to show or hide the admin menu, the user needs to sign in again or refresh the session before it appears in their token. Hiding the menu is only cosmetic; the check in the function is the one that protects you.

Do not use user_metadata for this. Any signed-in user can call supabase.auth.updateUser({ data: { role: 'admin' } }) on themselves.

Step 5: call the function from the app

Replace the admin call in the front end:

const { data, error } = await supabase.functions.invoke('admin-delete-user', {
  body: { userId },
})
if (error) {
  const message = await error.context?.json?.().then((b: { error?: string }) => b.error).catch(() => null)
  toast.error(message ?? 'Could not delete the user')
}

functions.invoke sends the signed-in user's token automatically. If the call fails with a 401 before your code runs, see Edge Function 401 Invalid JWT. If the browser blocks it, the CORS headers are the problem: Edge Function CORS errors in Lovable.

If you call the admin API from a Next.js server

The same rules apply in a Route Handler or Server Action. Keep the admin client in its own server-only module and never import it from client components:

// lib/supabase/admin.ts
import 'server-only'
import { createClient } from '@supabase/supabase-js'

export const supabaseAdmin = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_SECRET_KEY!, // no NEXT_PUBLIC_ prefix
  { auth: { persistSession: false, autoRefreshToken: false } }
)

Check the caller first with the normal cookie-based server client and supabase.auth.getClaims(), look at app_metadata, and only then use supabaseAdmin. Do not build the admin client with createServerClient and the request cookies: the user's session then takes over the database requests, and you get confusing results that depend on who is logged in. Never call signInWithPassword on the admin client for the same reason.

Prevention

FAQ

I am signed in as an admin. Why does it still say User not allowed?

Supabase Auth runs admin endpoints only for a token whose role is service_role or supabase_admin. Your session token has the role authenticated, whatever your app calls an admin, and a client made with the publishable key sends that key's anon role. The admin API never checks your own admin flag. Only the secret key works, and it must stay on a server.

Can I use the service_role key in my Lovable or Vite app if I hide it in an environment variable?

No. Anything the front end reads, including VITE_ and NEXT_PUBLIC_ variables, ends up in the JavaScript bundle that every visitor downloads. The new sb_secret_ keys refuse requests from browsers and return 401, but a legacy service_role key works from anywhere, so a leak gives full access to your data and users. If it was ever shipped, rotate it.

My server client uses the service role key and still gets User not allowed. Why?

Check for a global Authorization header. supabase-js merges global headers into the requests its auth client sends, so a client built with the secret key plus the user's Authorization header sends the user's token to the admin endpoint. Also check that the environment variable really holds the secret key and not the anon key copied into the wrong field.

Is there a way to list users without the admin API?

Yes, for most apps. Keep a public profiles table filled by a trigger on auth.users, and protect it with RLS so admins can read all rows and other users only their own. Use the admin API for actions that change auth itself, such as inviting, banning or deleting users.

Why should the admin flag be in app_metadata and not user_metadata?

Any signed-in user can change their own user_metadata with supabase.auth.updateUser, so a check on it lets anyone make themselves an admin. app_metadata can only be changed with the secret key or SQL, so it is safe to base permissions on.

Related guides