Guide
Supabase Content Moderation: Screen Posts Before They Reach Your Tables
With Supabase, the browser usually talks to the database directly: supabase.from('posts').insert(...), and row-level security decides what's allowed. For user-generated content that's not enough: "may this user insert a row?" and "should other people see this text?" are separate questions, and RLS only answers the first.
This guide makes posts invisible to other users until they've been checked. It uses a moderation_status column that defaults to pending, RLS that only shows approved rows (plus your own), an Edge Function that checks text and images with the Vettly content moderation API before writing, and a review queue for flagged content. At the end there's a variant that keeps client-side inserts and moderates them from a Database Webhook.
How a check works
POST https://api.vettly.dev/v1/check takes content, a policyId, and a contentType (text, image, or video). It returns an action (allow, warn, flag, or block), a decisionId to store with the row, and a categories array of { category, score, triggered }.
The policy decides which action you get. New accounts come with starter policies. moderate blocks hate speech, scams, self-harm, and illegal content, flags harassment, sexual content, and spam, and warns on profanity and violence. You can change any of that in YAML (policy docs) without touching this code.
In this guide the four actions mean:
- allow: the row is written and visible to everyone.
- warn: the row is written and visible. Show it behind a content warning.
- flag: the row is written but hidden from everyone except the author, and it goes into the review queue.
- block: nothing is written.
The table
Store the moderation status on the row itself. An enum keeps typos like aproved out:
create type public.moderation_status as enum ('pending', 'allow', 'warn', 'flag', 'block');create table public.posts (id uuid primary key default gen_random_uuid(),author_id uuid not null default auth.uid() references auth.users (id) on delete cascade,body text not null check (char_length(body) between 1 and 5000),image_path text,moderation_status public.moderation_status not null default 'pending',decision_id uuid,moderated_at timestamptz,created_at timestamptz not null default now());create index posts_feed_idx on public.posts (created_at desc)where moderation_status in ('allow', 'warn');
With the pending default, any row written without a decision starts out hidden. The partial index keeps feed queries fast.
RLS: hide anything that hasn't been approved
Everyone, signed in or not, sees allow and warn rows. Authors also see their own pending and flagged posts, so a post under review doesn't look like it vanished.
alter table public.posts enable row level security;-- Everyone sees approved posts; authors also see their own pending/flagged ones.create policy "read approved or own posts"on public.posts for selectto anon, authenticatedusing (moderation_status in ('allow', 'warn')or author_id = (select auth.uid()));-- Authors can delete their own posts.create policy "authors delete own posts"on public.posts for deleteto authenticatedusing (author_id = (select auth.uid()));-- No insert or update policies: clients cannot write rows or change status.-- The Edge Function writes with the service role, which bypasses RLS.revoke insert, update on public.posts from anon, authenticated;
The revoke is the important part. Hiding unapproved rows means nothing if a client can run update posts set moderation_status = 'allow'. With no insert or update policies and the privileges revoked, the only path to a row is the Edge Function. (Wrapping auth.uid() in a subselect lets Postgres evaluate it once per query rather than per row.)
The review queue
Flagged posts go into a separate queue table that carries reasons and resolution details. Moderators are listed in their own table:
create table public.moderators (user_id uuid primary key references auth.users (id) on delete cascade);alter table public.moderators enable row level security;create function public.is_moderator()returns booleanlanguage sql stable security definer set search_path = ''as $$select exists (select 1 from public.moderators where user_id = (select auth.uid()));$$;create table public.review_queue (post_id uuid primary key references public.posts (id) on delete cascade,reasons text[] not null default '{}',decision_id uuid,created_at timestamptz not null default now(),resolved_at timestamptz,resolved_by uuid references auth.users (id),resolution public.moderation_status);alter table public.review_queue enable row level security;create policy "moderators read queue"on public.review_queue for selectto authenticatedusing ((select public.is_moderator()));create policy "moderators read all posts"on public.posts for selectto authenticatedusing ((select public.is_moderator()));create function public.resolve_review(p_post_id uuid,p_status public.moderation_status)returns voidlanguage plpgsql security definer set search_path = ''as $$beginif not public.is_moderator() thenraise exception 'not a moderator' using errcode = '42501';end if;if p_status not in ('allow', 'warn', 'block') thenraise exception 'resolution must be allow, warn or block';end if;update public.postsset moderation_status = p_status, moderated_at = now()where id = p_post_id;update public.review_queueset resolved_at = now(), resolved_by = auth.uid(), resolution = p_statuswhere post_id = p_post_id;end;$$;revoke execute on function public.resolve_review from public, anon;grant execute on function public.resolve_review to authenticated;
moderators has RLS enabled and no policies, so clients can't read it or add themselves; add moderators from the SQL editor. is_moderator() is security definer so it can read that table for the caller. resolve_review is the only way anyone but the service role can change a post's status, and it checks the caller first. Select policies on the same table are combined with OR, so moderators see every post.
The Edge Function
Create the function, set the secrets, and deploy once the code below is in place:
supabase functions new create-postsupabase secrets set VETTLY_API_KEY=vettly_live_...# optional, defaults to 'moderate'supabase secrets set VETTLY_POLICY_ID=moderatesupabase functions deploy create-post
The Vettly call is a single fetch. Put the helper in _shared so the webhook variant can reuse it:
export type ModerationAction = 'allow' | 'warn' | 'flag' | 'block'export interface VettlyResult {decisionId: stringaction: ModerationActioncategories: Array<{ category: string; score: number; triggered: boolean }>}const API_KEY = Deno.env.get('VETTLY_API_KEY')!const POLICY_ID = Deno.env.get('VETTLY_POLICY_ID') ?? 'moderate'export async function vettlyCheck(content: string,contentType: 'text' | 'image' = 'text',): Promise<VettlyResult> {const res = await fetch('https://api.vettly.dev/v1/check', {method: 'POST',headers: {Authorization: `Bearer ${API_KEY}`,'Content-Type': 'application/json',},body: JSON.stringify({ content, contentType, policyId: POLICY_ID }),signal: AbortSignal.timeout(8000),})if (!res.ok) {throw new Error(`Vettly ${res.status}: ${await res.text()}`)}return await res.json()}const severity: Record<ModerationAction, number> = { allow: 0, warn: 1, flag: 2, block: 3 }export function mostSevere(a: VettlyResult, b: VettlyResult): VettlyResult {return severity[b.action] > severity[a.action] ? b : a}export function triggered(result: VettlyResult): string[] {return result.categories.filter((c) => c.triggered).map((c) => c.category)}
policyId is required; leaving it out gets you a validation error, not a default policy. The timeout makes sure you reach your fallback well before the Edge Function's own wall-clock limit.
The function identifies the user from their JWT, checks the text (and image, if any), then writes the row with the service role:
import { createClient } from 'npm:@supabase/supabase-js@2'import { mostSevere, triggered, vettlyCheck, type VettlyResult } from '../_shared/vettly.ts'const admin = createClient(Deno.env.get('SUPABASE_URL')!,Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,)const cors = {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',}const json = (data: unknown, status = 200) =>new Response(JSON.stringify(data), {status,headers: { ...cors, 'Content-Type': 'application/json' },})Deno.serve(async (req) => {if (req.method === 'OPTIONS') return new Response('ok', { headers: cors })// 1. Who is posting?const token = req.headers.get('Authorization')?.replace('Bearer ', '') ?? ''const { data: { user } } = await admin.auth.getUser(token)if (!user) return json({ error: 'Not signed in' }, 401)const { body, imagePath } = await req.json() as { body?: string; imagePath?: string }const text = body?.trim() ?? ''if (!text || text.length > 5000) return json({ error: 'Post must be 1-5000 characters' }, 400)if (imagePath && !imagePath.startsWith(`${user.id}/`)) {return json({ error: 'Invalid image path' }, 400)}// 2. Ask Vettly. If it is unreachable, keep the post hidden as pending.let result: VettlyResult | null = nulltry {result = await vettlyCheck(text)if (imagePath) {const { data, error } = await admin.storage.from('post-images').createSignedUrl(imagePath, 300)if (error) throw errorresult = mostSevere(result, await vettlyCheck(data.signedUrl, 'image'))}} catch (err) {console.error('moderation unavailable', err)}// 3. Blocked content never reaches the table.if (result?.action === 'block') {if (imagePath) await admin.storage.from('post-images').remove([imagePath])return json({ error: 'blocked', categories: triggered(result) }, 422)}const status = result?.action ?? 'pending'const { data: post, error } = await admin.from('posts').insert({author_id: user.id,body: text,image_path: imagePath ?? null,moderation_status: status,decision_id: result?.decisionId ?? null,moderated_at: result ? new Date().toISOString() : null,}).select('id, moderation_status').single()if (error) return json({ error: error.message }, 500)// 4. Flagged (or unchecked) posts go to the review queue.if (status === 'flag' || status === 'pending') {await admin.from('review_queue').insert({post_id: post.id,reasons: result ? triggered(result) : ['moderation_unavailable'],decision_id: result?.decisionId ?? null,})}return json(post, 201)})
Decisions worth calling out:
- Validate before you moderate. Length checks are free; moderation calls aren't, and the API rejects
contentover 100 KB anyway. - The image path is scoped to the user, so nobody can attach someone else's upload.
- Images go by signed URL. The bucket stays private, and Vettly fetches the file through a URL that expires in five minutes. If the image is worse than the text, its decision wins.
- Failures fail closed. A timeout or 5xx saves the post as
pendingand queues it with the reasonmoderation_unavailable. RLS hides it from everyone but the author until a moderator or retry job clears it. - Blocks aren't stored. Vettly keeps the decision record. If you need an "account strikes" feature, insert blocked rows with
moderation_status = 'block'instead; RLS already hides them.
Storage for images
Create a private bucket where users can only upload into a folder named after their user ID, which the function's path check relies on:
insert into storage.buckets (id, name, public)values ('post-images', 'post-images', false);create policy "users upload to their own folder"on storage.objects for insertto authenticatedwith check (bucket_id = 'post-images'and (storage.foldername(name))[1] = (select auth.uid()::text));
There's no select policy, so nobody reads files directly. Create signed URLs on the server only for posts the viewer can see. The image moderation guide covers visual categories and thresholds.
Calling it from the app
On the client, upload the image (if any), then invoke the function. supabase.functions.invoke sends the user's session token automatically:
import { FunctionsHttpError } from '@supabase/supabase-js'import { supabase } from './supabase'export async function submitPost(body: string, file?: File) {const { data: { user } } = await supabase.auth.getUser()if (!user) throw new Error('Sign in first')let imagePath: string | undefinedif (file) {imagePath = `${user.id}/${crypto.randomUUID()}`const { error } = await supabase.storage.from('post-images').upload(imagePath, file)if (error) throw error}const { data, error } = await supabase.functions.invoke('create-post', {body: { body, imagePath },})if (error instanceof FunctionsHttpError && error.context.status === 422) {const { categories } = await error.context.json()return { ok: false as const, categories: categories as string[] }}if (error) throw error// data.moderation_status is 'allow' | 'warn' | 'flag' | 'pending'return { ok: true as const, post: data }}
allow and warn mean the post is live; flag and pending mean "it'll appear after a quick review". A 422 is a rejection. Showing the triggered categories helps people fix borderline wording, but on a platform that gets targeted abuse it also reveals your thresholds, so decide deliberately.
Feed queries need no status filter, because RLS applies it.
Working the queue
A moderator screen is two calls. RLS restricts the queue to moderators, and resolve_review does the write:
export async function loadQueue() {const { data, error } = await supabase.from('review_queue').select('post_id, reasons, created_at, posts(body, author_id)').is('resolved_at', null).order('created_at')if (error) throw errorreturn data}export async function resolve(postId: string, status: 'allow' | 'warn' | 'block') {const { error } = await supabase.rpc('resolve_review', { p_post_id: postId, p_status: status })if (error) throw error}
The queue row's decision_id opens the decision in the Vettly dashboard, with every category score and the policy version that produced the flag. If one category keeps producing reviews that end in allow, raise that threshold rather than adding moderators.
Variant: keep client inserts, moderate from a Database Webhook
If your app already inserts posts straight from the client and you'd rather not route writes through a function, invert the flow. Clients insert rows that are always pending, and a Database Webhook moderates each new row.
Let clients insert only the content columns. Because the status column isn't in the grant, it always takes its pending default:
grant insert (body, image_path) on public.posts to authenticated;create policy "authors insert own posts"on public.posts for insertto authenticatedwith check (author_id = (select auth.uid()));
Setting moderation_status or another user's author_id now fails with "permission denied". The webhook function:
import { createClient } from 'npm:@supabase/supabase-js@2'import { triggered, vettlyCheck } from '../_shared/vettly.ts'const admin = createClient(Deno.env.get('SUPABASE_URL')!,Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,)Deno.serve(async (req) => {if (req.headers.get('x-webhook-secret') !== Deno.env.get('MODERATION_WEBHOOK_SECRET')) {return new Response('forbidden', { status: 403 })}const { type, record } = await req.json()if (type !== 'INSERT' || record.moderation_status !== 'pending') {return new Response('skipped')}// Throwing returns a 500; the row simply stays pending (hidden).const result = await vettlyCheck(record.body)await admin.from('posts').update({moderation_status: result.action,decision_id: result.decisionId,moderated_at: new Date().toISOString(),}).eq('id', record.id).eq('moderation_status', 'pending')if (result.action === 'flag') {await admin.from('review_queue').insert({post_id: record.id,reasons: triggered(result),decision_id: result.decisionId,})}return new Response('ok')})
Set MODERATION_WEBHOOK_SECRET with supabase secrets set. Then in the dashboard, under Database → Webhooks, create a webhook on INSERT for public.posts that calls moderate-post, with an x-webhook-secret header set to the same value. Without that check, anyone who found the URL could send harmless text with a real post's ID and publish it unchecked. This version checks text only; copy the image check from create-post if you need it.
The trade-off is feedback: the insert succeeds immediately, so you can't tell the user in the same request that the post was blocked. Subscribe to their rows with Supabase Realtime to show the outcome. Blocked rows stay in the table with moderation_status = 'block', hidden by RLS.
Before you ship
- Test RLS as
anon, an author, another user, and a moderator, and confirmupdate posts set moderation_status = 'allow'fails for a normal user. - Edits need moderation too: route them through a function, or reset
moderation_statustopendingwhenbodychanges. - Test your policy with the dry-run endpoint, which evaluates mock scores against a stored policy without sending real content.
- Someone has to own the review queue. Track how long items sit there.
The same design works outside Supabase: Content moderation in Next.js does it with Server Actions. See also the REST reference, the error handling guide, and the playground for trying the moderate policy on your own samples.
Frequently asked questions
Can I moderate with a Postgres trigger instead of an Edge Function?
Not synchronously in a useful way: a trigger would have to make an HTTP call inside the insert transaction. Use an Edge Function that checks first and then writes, or let clients insert rows as pending and moderate them from a Database Webhook. This guide covers both.
Why can't the client just insert with moderation_status = 'allow'?
In this setup it can't. Table-level INSERT and UPDATE are revoked from the anon and authenticated roles, so only the Edge Function (using the service role) writes moderation fields. In the webhook variant, clients get INSERT on the body and image columns only, so the status always takes its 'pending' default.
What happens to a post if the Vettly API is unavailable?
It's stored with moderation_status = 'pending' and added to the review queue with the reason moderation_unavailable. RLS hides pending rows from everyone except the author and moderators, so nothing unchecked is published.
Does this work for images in Supabase Storage?
Yes. Upload to a private bucket, have the Edge Function create a short-lived signed URL, and send it to /v1/check with contentType 'image'. The function takes the more severe of the text and image decisions.
Where do I keep the Vettly API key?
As an Edge Function secret: supabase secrets set VETTLY_API_KEY=... It's read with Deno.env.get and never reaches the browser.