You asked Lovable for an admin dashboard, and it built one: a page at /admin with a user list, order totals and a few buttons that edit or delete things. The link only appears when you sign in with your own account, so it feels private. Whether it is private depends on something the page can’t show you: what your database and server code do when a signed-in user who isn’t you sends the same requests.
This guide sets up admin access so the database and the server enforce it, not the React code. It covers where to keep the role, a user_roles table nobody can write to from the app, a helper function your policies can call, the same check inside your server code, an optional JWT claim, and a short test you can run as a normal user. It applies to Lovable Cloud and to a Supabase project you connected yourself; the Supabase and Lovable tool pages on this site gather related guides for both setups.
The admin page is a door; the database needs the lock
Everything in the browser belongs to the visitor. They can read the JavaScript bundle, find the /admin route, edit a variable in DevTools, or skip your pages altogether and call your database with the project URL and publishable key, both of which ship inside the app. Lovable’s security best practices say the same thing plainly: code in the browser shouldn’t make security decisions, roles and permissions should be checked on the server, and front-end auth state is only for deciding what the UI shows.
So the check if (profile.role === 'admin') in a component is fine for hiding a menu item. It protects nothing. The protection has to live in two places:
- Row Level Security (RLS) policies for every table the admin panel reads or changes through the Supabase client.
- Server code (Edge Functions, plus the server functions and API routes in newer Lovable apps) for anything that runs with the service role, because that role ignores RLS.
Lovable’s database access page adds a point worth reading twice: the authenticated database role only tells Postgres that someone is signed in. It says nothing about whether that person is an admin of your app. A policy that lets authenticated read every order lets every customer read every order.
Where the role must not live
Before building anything, find where your app currently stores “admin”. Ask Lovable to show you, or search the code for admin, role and is_admin. Three places are unsafe:
user_metadata(thedatayou pass at sign-up, stored inraw_user_meta_data). Supabase’s user data docs explain that a user who is logged in can rewrite those fields at will throughupdateUser(), and Supabase Auth runs no checks on what they write. The RLS guide gives the same warning about readinguser_metadatafrom the token inside a policy. A role kept there is a role users can give themselves.- A column users can update, such as
profiles.is_adminorprofiles.roleon a table where each user may update their own row. Policies work row by row and ignore columns (Supabase’s column level security page makes the same point), so an owner-update policy plus a table-wide update grant lets a user flip that column on their own profile. - Anything sent by the browser, like an
isAdmin: truefield in a request body that a function trusts. Our code review guide shows how a reviewer spots this pattern.
There are two safe homes. app_metadata (stored in raw_app_meta_data) can’t be edited by the user; Supabase’s docs say to set it from trusted server code with the secret key, for example auth.admin.updateUserById(). Or use a separate table that the app can’t write to, which is also the route Supabase’s column level security page points to for roles. The rest of this guide uses the table, because you can see and change it with plain SQL, and every policy check reads the current value instead of a copy inside a token.
Step 1: a user_roles table the app can only read
This follows the shape of Supabase’s RBAC guide, cut down to roles only. Run it in the SQL editor (Lovable Cloud: More → Database → Manage → SQL editor; your own project: the Supabase dashboard), or have Lovable add it as a migration through the chat. Lovable’s database page notes that SQL typed into its editor goes straight to the database and no migration file is kept for it, so use the chat if you want the change recorded in your project’s code.
-- The roles your app knows about. Add more later with ALTER TYPE.
create type public.app_role as enum ('admin', 'staff');
-- One row per user per role.
create table public.user_roles (
user_id uuid not null references auth.users on delete cascade,
role public.app_role not null,
primary key (user_id, role)
);
alter table public.user_roles enable row level security;
-- Start from zero, then allow reading only.
revoke all on table public.user_roles from anon, authenticated, public;
grant select on table public.user_roles to authenticated;
-- A signed-in user can see their own role rows and nobody else's.
create policy "Users read their own roles"
on public.user_roles
for select
to authenticated
using ( (select auth.uid()) = user_id );
What each part does:
- No insert, update or delete grant for
anonorauthenticated. With no grant, Postgres refuses the write before any policy runs, so no sign-in can create an admin row through the API. - The revoke line works on every project. Whether a new
publictable starts with grants for the three API roles (anon,authenticated,service_role) depends on the project. Supabase’s changelog entry schedules the end of those automatic grants for every existing project on October 30, 2026, yet when we checked on December 3, 2026, the RLS guide (updated November 25) still describes existing projects as getting them and adds that not every project does. So don’t assume either way. The revoke strips any automatic grants, and on a project that has none it changes nothing. - The read policy is a choice, not a requirement. It lets the app show or hide the admin link from a real lookup instead of a guess. Supabase’s RBAC example gives
anonandauthenticatedno policy at all on its roles table; only its auth hook reads it. Either is safe; what matters is that nothing in the app can write to it.
Step 2: an is_admin() helper, and policies that use it
Each admin rule needs to ask “is the current user an admin?”. Put that question in one function so every policy asks it the same way:
create schema if not exists private;
create or replace function private.is_admin()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.user_roles
where user_id = (select auth.uid())
and role = 'admin'
);
$$;
-- Only signed-in users may call it.
revoke execute on function private.is_admin() from public, anon;
grant usage on schema private to authenticated;
grant execute on function private.is_admin() to authenticated;
Now give admins the extra access, table by table. For an orders table where customers already see their own rows through an owner policy (templates for those are in our RLS policies guide):
create policy "Admins read all orders"
on public.orders
for select
to authenticated
using ( (select private.is_admin()) );
Postgres joins permissive policies for the same command with OR (PostgreSQL: CREATE POLICY), so a customer still matches the owner policy and sees their own orders, and an admin matches this one and sees all of them. Add matching update or delete policies only where the panel really edits or removes rows. The table also needs grants for those operations; if a request fails with “permission denied for table”, see our 42501 guide.
Why it’s written this way:
security definermakes the function run with its owner’s rights. Supabase’s database functions page notes that functions made in the dashboard or through migrations belong topostgres, a role RLS doesn’t restrict, so it can readuser_roleswithout hitting that table’s own policies. For the same reason, admin policies onuser_rolesitself can call it without the policy calling itself in a loop.set search_path = ''with schema-qualified names (public.user_roles,auth.uid()). The RLS guide tells you to pin it on every definer function so a caller can’t swap in an object of their own.(select private.is_admin())in parentheses withselect. The RLS guide explains that wrapping a function this way lets Postgres run it once per statement instead of once per row.- The grants. Postgres lets a role use objects in a schema only after it gets
USAGEon that schema (PostgreSQL: Schemas), and because the SQL above revokesexecutefrompublic,authenticatedhas to get it back explicitly; Supabase’s functions page calls out helpers used by RLS policies as functions that need this grant.
The two Supabase pages disagree on where the helper goes
Supabase’s RBAC guide creates its authorize() helper as security definer in the public schema. The RLS guide forbids putting a definer function in any schema your API settings mark as exposed, because the Data API lets anyone with execute rights call it with the owner’s privileges, and its own example uses private.
A schema that isn’t exposed satisfies both pages, which is why the helper above lives in private. If Lovable already generated a definer helper in public, read what it takes as input. A helper that only reports on the caller reveals nothing about anyone else, while one that accepts any user ID lets whoever can call it test whether a given account is an admin. Moving it to private and updating the policies that call it is the cleaner fix.
Step 3: every admin function checks the role again
Admin features such as deleting a user from Auth, cancelling a subscription or emailing every customer can’t go through RLS. Those run in an Edge Function with the service role, and the service role skips every policy. Lovable’s database access page puts the permission check on your server code whenever it uses that role, and Supabase’s API keys page says the secret key never belongs in a browser, a shipped app or source control.
So every admin function should do three things in this order: confirm who is calling, look up their role on the server, then do the privileged work. With Supabase’s withSupabase wrapper from its Edge Function auth docs:
import { withSupabase } from 'npm:@supabase/server@1'
export default {
fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
// 1. auth: 'user' means a valid user JWT was required to get here.
// 2. Look up the caller's role with their own RLS-scoped client.
const { data: rows, error } = await ctx.supabase
.from('user_roles')
.select('role')
.eq('role', 'admin')
if (error || !rows || rows.length === 0) {
return Response.json({ error: 'Admins only' }, { status: 403 })
}
// 3. Only now use the privileged client. It ignores RLS,
// so filter every query yourself.
const { userId } = await req.json()
const { error: delError } = await ctx.supabaseAdmin.auth.admin.deleteUser(userId)
if (delError) {
return Response.json({ error: delError.message }, { status: 400 })
}
return Response.json({ ok: true })
}),
}
The role lookup works because of the read policy from Step 1: the caller’s own client sees only their own rows, so the query returns a row only if they are an admin. If your project’s functions use an older pattern (Deno.serve plus createClient), keep the same order: build a client from the caller’s Authorization header, get the user, check user_roles, and return 403 before touching the service-role client. Never accept a role or isAdmin flag from the request body.
Newer Lovable apps might have no Edge Functions. Lovable’s edge functions page says apps created since May 13, 2026 run on TanStack Start, with their server code living inside the app in the form of server functions and API routes, so a newer app might contain no edge function. Both kinds carry the same duty: Lovable’s security best practices tell each server function and API route to verify the caller and what that caller is permitted to do. The withSupabase example above is Edge Function code. For a server function or API route, keep the same order (caller, then role lookup on the server, then privileged work), and have Lovable confirm in the chat that each admin action does it.
Two more server-side details matter. Supabase’s auth page warns that ctx.supabaseAdmin queries on a shared table return every user’s rows unless you filter by the caller. And on a project where new tables get no automatic grants, a table you create later has none for service_role either; Supabase’s API keys page says a missing grant fails even for that role, so the admin client can hit “permission denied” until you add one. The fix is a grant, covered in the 42501 guide. For other function errors, start with our non-2xx guide.
Optional: copy the role into the JWT using an access token hook
Supabase’s RBAC guide also shows how to copy the role into the user’s access token. You register a Postgres function as your project’s Custom Access Token hook, and Supabase Auth calls it each time it is about to hand out a token, and the function adds a claim such as user_role. Policies then read auth.jwt() ->> 'user_role' instead of querying a table, and the front end can decode the token to decide what to show. The RBAC guide has the full SQL: the hook function, execute granted to supabase_auth_admin and revoked from anon, authenticated and public, table access plus a select policy on user_roles for supabase_auth_admin, and switching the hook on under Authentication → Hooks in the dashboard.
Trade-offs to weigh before you add it:
- It undoes a grant from Step 1. The hook SQL in Supabase’s RBAC guide revokes every privilege on
user_rolesfromauthenticated, and that removes the select grant you gave it in Step 1. Rungrant select on table public.user_roles to authenticated;again afterwards. Without it, the role lookup in Step 3 and any app query on that table fail with “permission denied” (theis_admin()helper still works, because it runs as its owner). - Tokens go stale. The RLS guide warns that a change you make isn’t visible through
auth.jwt()until the user’s token is refreshed. The hook’s input liststoken_refreshamong the ways a token is requested, so a new role reaches the claim at the next refresh. Until then, someone you just removed as admin still carries the old claim. The table lookup in Step 2 sees the change on the next query. - Don’t call the claim
role. The access token already has a requiredroleclaim, and its value is the Postgres role (anon,authenticatedorservice_role), per Supabase’s JWT fields reference. Your app’s role needs its own name, such asuser_role. - Lovable Cloud. When we checked on December 3, 2026, Lovable’s pages on its built-in backend and on users and authentication didn’t mention auth hooks. If your app runs on Lovable Cloud, the table and helper above need only SQL, which the SQL editor runs. With your own connected Supabase project, the hook is configured in the Supabase dashboard as described.
A decoded claim in the browser is still only a hint for the UI. Policies and Edge Functions make the decision.
Make the first admin
Nobody can insert into user_roles from the app, so the first admin is added by hand in the SQL editor:
insert into public.user_roles (user_id, role)
select id, 'admin'
from auth.users
where email = 'you@yourdomain.com';
Check that it worked with select * from public.user_roles;. Later admins can be added the same way. If you want admins to manage roles from the panel, grant insert and delete on user_roles to authenticated and add policies for those two commands that use (select private.is_admin()), so only an existing admin can add or remove a role. If the panel also lists everyone’s roles, add a select policy with the same check, since the Step 1 policy lets each user see just their own rows. Leave update out; deleting one row and inserting another is easier to audit.
Two-minute test with a non-admin account
Don’t trust the setup until a non-admin account fails to get in. Create a second account in your live app with a different email, sign in with it, and leave your own account out of this.
- Open DevTools (the menu names here are Chrome’s), go to the Network tab and reload a page that loads data. Find a request to
/rest/v1/, right-click it, open the Copy submenu and pick Copy as cURL (Chrome DevTools: Network reference lists it). The copied command carries the publishable key and this user’s session token. - Try to become an admin. Edit the command into a
POSTto/rest/v1/user_roleswith the headerContent-Type: application/jsonand the body{"user_id": "<this user's id>", "role": "admin"}. You want an error back, “permission denied for table user_roles” or a row-level security violation, never a201. - Read an admin-only table. Change the URL to
/rest/v1/orders?select=*(or whatever your panel lists). You want only this user’s own rows or[]. - Call an admin function. Send the same headers to the function’s address. On Lovable Cloud, More → Database → Manage → Edge functions has a Copy URL option for each function; on a Supabase project the address is
https://<project-ref>.supabase.co/functions/v1/<your-admin-function>(Supabase: Edge Functions quickstart). If your admin actions are server functions or API routes, copy the request your admin page sends the way you did in step 1. You want a403. - Open
/admindirectly. The page may render an empty shell; that’s fine as long as no data loads and every action fails.
Then repeat step 3 with no Authorization header at all, the logged-out test from our security checklist. If any step returns data or a success code, the policy or function behind it is the one to fix before you publish.
Prompt: have Lovable audit and fix the admin checks
Copy this into the project chat. It asks for a report before changes, so you can compare the plan with the steps above:
Before changing anything, list every place this app decides whether a user is an admin: React components, routes, hooks, RLS policies, database functions and Edge Functions. For each, say where the role is read from (user_metadata, app_metadata, a profiles column, a user_roles table or the request body) and whether that check happens client-side or server-side.
Then propose this change and wait for my approval:
1. A public.user_roles table (user_id, role as an enum) with RLS on, a select-only grant to authenticated, a policy letting users read only their own rows, and no insert, update or delete for anon or authenticated.
2. A private.is_admin() function, security definer, search_path set to '', with execute granted only to authenticated and usage on schema private granted to authenticated.
3. Admin-only RLS policies that use (select private.is_admin()), one per table and command the admin panel needs, with the explicit table grants those commands require.
4. In every admin Edge Function, server function and API route: verify the caller, check user_roles on the server, return 403 if not admin, and only then use the service role client.
5. Remove any role checks that read user_metadata or a column the user can edit. Keep front-end checks only for showing or hiding UI.
Read the migration before you approve it, and run the test above once it’s applied.
FAQ
Is a React check like user.role === ‘admin’ enough?
No. Anyone can change what React believes or skip React and call your database directly. Lovable’s own security guidance limits front-end auth state to shaping the UI. Use it to hide the link, and let RLS and your Edge Functions refuse the requests.
Could a user promote themselves to admin?
Yes, if the role sits in user_metadata, in a column they’re allowed to update, or in a request field your server trusts. With the setup above they can’t: user_roles has no write grant for app users, and the helper only reads it. Step 2 of the test proves this on your real project.
Custom claims or a roles table: which do I need?
A roles table plus a helper function is enough for an admin panel. Claims save a table lookup per request, but they only update when the token is refreshed, and they add a hook to maintain. Add them later if you have a measured reason.
How is the first admin created?
Insert a row into user_roles from the SQL editor, taking your account’s ID from its row in auth.users. It has to be done there, because the app itself has no permission to write to that table.
Will Lovable’s security scan flag an unprotected admin page?
Lovable’s security overview says its advanced checks look at whether actions meant for only certain users, admin actions included, check the user’s role rather than just sign-in. Treat that as one input, not proof: run the non-admin test yourself after any change. Our Lovable security scan guide explains how to read and act on the findings.
Comments