How to ban a user in Supabase (and make it stick)
Supabase bans a user with a single admin call. To make the ban apply where a valid access token is still around, you need a few additions in Edge Functions and Row Level Security.
This guide shows how to ban users in Supabase, why the ban does not apply everywhere at once, and how to close the gap. It works without Limenia. What Limenia can take off your hands is in the last section.
ban_duration in the Auth admin API
Supabase Auth keeps a banned_until timestamp for every user. You set it through the admin API with ban_duration, in the JavaScript client with auth.admin.updateUserById. The call belongs in an Edge Function or another backend, because it needs a secret key.
import { createClient } from "npm:@supabase/supabase-js@2";
// Edge Functions receive all secret keys of the project by name, here the key "moderation"
const secretKeys = JSON.parse(Deno.env.get("SUPABASE_SECRET_KEYS")!);
const admin = createClient(Deno.env.get("SUPABASE_URL")!, secretKeys["moderation"], {
auth: { persistSession: false, autoRefreshToken: false },
});
async function setBan(userId: string, banDuration: string) {
const { error } = await admin.auth.admin.updateUserById(userId, { ban_duration: banDuration });
if (error) throw error;
}
// permanent: about 100 years
await setBan(userId, "876000h");
// temporary, until a point in time
const seconds = Math.ceil((until.getTime() - Date.now()) / 1000);
await setBan(userId, `${seconds}s`);
// lift
await setBan(userId, "none");
The three cases:
| Case | ban_duration |
What happens |
|---|---|---|
| Permanent ban | 876000h |
banned_until is set about 100 years ahead |
| Temporary ban | a duration like 72h or 259200s |
The ban ends by itself; nothing to schedule |
| Lift the ban | none |
banned_until is cleared |
The duration uses Go’s format: numbers with the units ns, us (or µs), ms, s, m and h, also combined like 2h45m. There is no unit for days.
Do not delete banned users. If a complaint succeeds you have to lift the ban, and that only works while the account exists.
Why a ban doesn’t end every session at once
Supabase checks the ban immediately in three places: at sign-in, at token refresh and on calls to Supabase Auth itself, such as getUser(). The refresh fails with “Invalid Refresh Token: User Banned”, the sign-in with the error code user_banned.
What does not stop at once is an access token that was already issued. It is a signed JWT and stays valid until it expires, one hour by default. Until then the Data API, Storage and Realtime keep accepting it, and Row Level Security sees only auth.uid(), not the ban. Supabase cannot end a session by user ID: auth.admin.signOut expects the session’s JWT, not a user ID.
For most apps an hour of overlap is acceptable. For harassment in a chat or a spam wave it often is not. The next two sections help.
getUser() instead of getClaims(), or a shorter JWT lifetime
In Edge Functions you have two ways to find out who sent a token:
getClaims()verifies the JWT locally against your project’s JWKS when you use asymmetric signing keys. It is fast, but it cannot see a ban while the token is valid.getUser()asks the Auth server on every call. For banned users it returns an error.
For actions a ban should stop right away (posting, sending messages, reporting), use getUser():
import { createClient } from "npm:@supabase/supabase-js@2";
const publishableKeys = JSON.parse(Deno.env.get("SUPABASE_PUBLISHABLE_KEYS")!);
const supabase = createClient(Deno.env.get("SUPABASE_URL")!, publishableKeys["default"]);
Deno.serve(async (req) => {
const token = req.headers.get("Authorization")?.replace(/^Bearer\s+/i, "");
if (!token) return new Response("Unauthorized", { status: 401 });
const { data, error } = await supabase.auth.getUser(token);
if (error || !data.user) return new Response("Forbidden", { status: 403 }); // banned users too
// ... do the work for data.user.id
return new Response(null, { status: 204 });
});
For direct database access from the app, add a restrictive policy. It is combined with every other policy using AND. The helper function lives in a schema the Data API does not expose, because it runs as security definer:
create schema if not exists private;
create or replace function private.is_banned()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select coalesce(
(select u.banned_until > now() from auth.users u where u.id = auth.uid()),
false
);
$$;
grant usage on schema private to authenticated;
revoke execute on function private.is_banned() from public, anon;
grant execute on function private.is_banned() to authenticated;
create policy "banned users cannot post"
on public.posts
as restrictive
for insert
to authenticated
with check (not (select private.is_banned()));
Wrapping the call in (select …) lets Postgres compute it once per statement instead of once per row. Add the same policy for update, for messages and for Storage buckets.
The third option is a shorter access token lifetime, in the Auth settings under Sessions. Supabase recommends at least five minutes. Shorter tokens mean more refreshes and only narrow the gap.
A dedicated secret key instead of service_role
Supabase has introduced new API keys: publishable keys (sb_publishable_…) for the app and secret keys (sb_secret_…) for the backend. According to the Supabase docs, the legacy anon and service_role keys are being phased out by the end of 2026.
For bans from an Edge Function this means:
- Create a dedicated secret key in the dashboard under API Keys, for example named
moderation. - Hosted Edge Functions receive it automatically in
SUPABASE_SECRET_KEYS, a JSON object keyed by name. Read it withJSON.parse(Deno.env.get("SUPABASE_SECRET_KEYS")!)["moderation"], as in the code above. - Use it only in the functions that need the admin API.
A dedicated key can be deleted on its own if it leaks, without breaking other services. One thing does not change: secret keys bypass every RLS policy. They never go into the Flutter app, remote config or Git. Supabase rejects secret keys in browsers, but that does not protect a mobile app.
Moderating content with Edge Functions and webhooks
A ban is the end of the process. It starts with a report. With Supabase you don’t even need a function for that if RLS decides who is reporting and a trigger takes the snapshot:
create table public.reports (
id uuid primary key default gen_random_uuid(),
reporter_id uuid not null default auth.uid() references auth.users (id),
post_id uuid not null references public.posts (id),
reason_category text not null check (reason_category ~ '^[a-z0-9_]{2,40}$'),
reason_text text check (char_length(reason_text) <= 2000),
author_id uuid,
snapshot_text text,
status text not null default 'open',
created_at timestamptz not null default now(),
unique (post_id, reporter_id)
);
alter table public.reports enable row level security;
create policy "report as yourself"
on public.reports for insert to authenticated
with check (reporter_id = (select auth.uid()) and status = 'open');
-- snapshot from the database, not from the app
create or replace function private.fill_report_snapshot()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
select p.author_id, p.content into new.author_id, new.snapshot_text
from public.posts p where p.id = new.post_id;
return new;
end;
$$;
create trigger reports_snapshot before insert on public.reports
for each row execute function private.fill_report_snapshot();
Without a select policy nobody can read other people’s reports. The unique constraint stops the same person from reporting the same post twice.
Next, add a Database Webhook on insert into reports. It calls an Edge Function asynchronously, which notifies your moderators or forwards the report to a moderation tool. Give the webhook a secret header and check it in the function, because the function URL is public.
Once a decision is made, a function applies it: hide the post (status = 'removed' rather than deleting it), ban the user and send the statement of reasons. Under Art. 17 DSA every ban and every removal needs a clear and specific statement of reasons; the guide on the statement of reasons under Art. 17 DSA has the details. A banned user can no longer sign in, so send the statement by e-mail and show it when sign-in fails with user_banned. How complaints against bans work is covered in the guide on internal complaint handling.
With Limenia: the Supabase connector
Limenia covers the part between report and action: grouping reports, deciding in the dashboard, writing the Art. 17 statement of reasons, informing reporters and accepting complaints. Your Edge Function forwards reports to POST /v1/reports; the API key stays in your function secrets, never in the app.
The Supabase connector (Pro and Premium) applies bans directly in Supabase Auth:
| Decision in Limenia | In Supabase Auth |
|---|---|
| Permanent ban | ban_duration: 876000h |
| Temporary suspension | the remaining seconds until it ends; Supabase lifts it by itself |
| Restore account, end of a suspension | ban_duration: none |
| Remove content, warn | nothing; this goes through the webhook |
You create a dedicated secret key just for Limenia. Limenia does not accept legacy service_role keys. Only the user UUID and the ban duration go to Supabase, and Limenia never deletes users. Your backend has to send the UUID from auth.users.id as the user ID.
The connector does not change any tables. Hiding content and showing the statement of reasons stay with your webhook receiver, and getUser() and the RLS policy above remain useful. An Edge Functions example is in the examples repository on GitHub, and section 2.5 of the integration guide walks through every step. For Flutter apps there is the limenia package on pub.dev with ready-made widgets for the report sheet, complaints and statements of reasons. More on the connector in Moderation for Supabase apps, and on the app side in Moderation for Flutter apps.
Supabase is a trademark of Supabase, Inc. Flutter is a trademark of Google LLC.
Sources
- Supabase JavaScript reference: auth.admin.updateUserByIdsupabase.com
- Supabase JavaScript reference: auth.getClaimssupabase.com
- Supabase: User sessionssupabase.com
- Supabase: Understanding API keyssupabase.com
- Supabase: Row Level Securitysupabase.com
- Supabase: Edge Function secretssupabase.com
- Supabase: Database Webhookssupabase.com
- Regulation (EU) 2022/2065 (Digital Services Act), Art. 17 and 20, EUR-Lexeur-lex.europa.eu
- Limenia integration guide (section 2.5 Flutter + Supabase, 7.2 Supabase connector)limenia.eu
- Limenia example backends on GitHub (Apache 2.0)github.com