We Audited 145 AI-Built Next.js + Supabase Apps. 16 Left Their Databases Wide Open.
We recently audited 145 public Next.js + Supabase projects built with AI coding assistants. Sixteen of them had completely wide-open database permissions. Anyone grabbing the public frontend key straight out of the brows
We recently audited 145 public Next.js + Supabase projects built with AI coding assistants. Sixteen of them had completely wide-open database permissions. Anyone grabbing the public frontend key straight out of the browser could read all the data.
How we checked them was boring on purpose. Every Next.js + Supabase app ships its project URL and public anon key to the browser by design. Using only that public key, without logging in or running exploits, we checked what the PostgREST API returned and looked at the public code and config patterns around auth, storage, API routes, and database policies. When one curl call against /rest/v1/<table>?select=* dumps live rows, there is nothing theoretical left to argue about.
A few failure patterns stood out right away.
In Supabase, a table ends up wide open to the public anon key in two familiar ways: either Row Level Security was never enabled on a public table, or RLS was switched on alongside a USING (true) policy pasted in so the prototype would stop returning empty arrays. Even TO authenticated USING (true) looks careful in a migration file, yet it still lets any signed-in user read and edit every other user's rows.
Even when table policies look decent, quiet RLS bypasses keep showing up next to them. Putting SUPABASE_SERVICE_ROLE_KEY behind a NEXT_PUBLIC_ prefix tells Next.js to inline full database access into client JavaScript. In Postgres, standard views execute with the view owner's privileges by default, skipping base-table RLS unless you set security_invoker = true (or keep the view out of exposed schemas).
The same shortcuts carry straight into Next.js server routes: endpoints calling paid AI APIs with no auth, rate limit, or usage cap (an open wallet waiting for a curl loop), Stripe webhooks calling req.json() without checking stripe-signature, and routes authorizing off supabase.auth.getSession() cookies or trusting userId and price fields from the browser.
None of this happens because models haven't heard of RLS or HMAC signatures. It happens because of the feedback loop we put them in. When you tell Cursor or Claude Code "build the dashboard and fix why the table returns []," the model optimizes for making the screen work on the next reload. RLS blocking a query looks like friction to clear, so the quickest patch is USING (true) or reaching for service_role. getSession() passes local happy-path testing. Public storage buckets make image previews show up on the first try. Add training data full of short quickstarts that skip rate limits and webhook verification for readability, and assistants happily ship demo defaults unless you spell out hard boundaries.
We turned our audit notes into 12 practical rules. Even if you never install a rule file, checking your app against these twelve points before launch catches most of the painful mistakes:
-
Require owner-scoped RLS on every
publictable. Enable RLS in the same migration that creates the table, scoped toauth.uid() = user_id(or tenant membership). Never shipUSING (true)orWITH CHECK (true)as a general policy, including forauthenticated. -
Keep server secrets out of client code and
NEXT_PUBLIC_vars. Only the Supabaseanonkey and Stripe publishable key (pk_...) belong in the browser. Keepservice_role, database passwords, Stripe secrets, and AI keys strictly server-side. -
Make storage buckets private by default. Set
public = false, scopestorage.objectspolicies by user folder ((storage.foldername(name))[1] = auth.uid()::text), and serve private files through short-lived signed URLs. Leave public buckets strictly for world-readable assets like product images. - Add auth, rate limits, and spend caps to every paid-API route. Before calling OpenAI, Anthropic, Replicate, or ElevenLabs, verify the user, enforce per-user/IP rate limits, cap input size, and check a daily or monthly usage ceiling. Uncapped metered endpoints leave your provider balance exposed to any script.
-
Verify webhook signatures against the raw body. For Stripe, read
await req.text()and validatestripe-signatureviastripe.webhooks.constructEvent()usingSTRIPE_WEBHOOK_SECRET, returning400on failure. Never trustreq.json()directly, and handle retries idempotently. -
Authenticate and check ownership in every API route. Resolve the caller server-side at the top of every Route Handler and Server Action, then confirm they own the target record before reading or writing it. Ignore client-sent
userId,role,isAdmin, andpricefields; load roles from your database and prices from your server catalog. -
Keep real secrets out of git. Store credentials in
.env.localor your host's env panel, ignore.env*with!.env.example, and commit only placeholders. If a real key ever hits a commit, rotate it immediately; deleting it later leaves it in git history. -
Keep internals out of responses and secrets out of logs. Return plain messages (
Something went wrong,Not found,Unauthorized) instead of stack traces or SQL errors, and return404rather than revealing another user owns an ID. Strip tokens,Authorizationheaders, and sensitive auth or payment payloads before logging. -
Revalidate server-side auth with
getUser(), notgetSession(). In Route Handlers, Server Actions, andmiddleware.ts, callsupabase.auth.getUser(), fail closed onerror || !user, and never fall back togetSession(). Cookie-onlygetSession()is fine for non-authoritative browser UI, not server authorization, and you still need to scope queries byuser.id. -
Lock down Postgres views and
SECURITY DEFINERfunctions. Setwith (security_invoker = true)on exposed views (Postgres 15+) or move server-only and private materialized views to a non-exposedprivateschema with client privileges revoked. PreferSECURITY INVOKERfor functions; whenSECURITY DEFINERis genuinely needed, pinset search_path = '', schema-qualify all objects, enforceauth.uid(), and revoke defaultPUBLICandanonEXECUTE. -
Validate uploaded file content, size, and encoding server-side. Private buckets only restrict downloads. Pair host-aware size caps with a three-way check across extension, declared MIME, and magic bytes (
file-type), reject.html/.svg/scripts on image endpoints, re-encode images to strip EXIF/GPS metadata, store under random keys (<user_id>/<uuid>.<ext>), and serve withX-Content-Type-Options: nosniff(plusContent-Disposition: attachmentfor PDFs and other non-reencoded files). -
Commit lockfiles, run frozen installs, verify new packages, and gate on high-severity audits. Track your lockfile in git and run frozen CI installs (
npm ci,pnpm install --frozen-lockfile, etc.) without fallback. Verify unfamiliar packages in official docs andnpm viewbefore installing (AI tools invent plausible names attackers can register, known as "slopsquatting"), and fail builds onhighorcriticaladvisories without swallowing errors via|| true.
Repeating all twelve rules in every prompt gets old fast, so we packaged them as a free skill pack called Vibe Security Rules (v2). It includes ready-to-use files for Cursor (cursor-rules.mdc) and Claude Code (claude-code-rules.md), a 12-item pre-launch self-check for your own app, and 39 verification cases testing broken and safe code.
It is free, and our first real user has already run it on their project. If you try it on your repo and spot an edge case we missed, open an issue.
- Agensi skill pack: https://www.agensi.io/skills/vibe-security-rules-next-js-supabase-stripe
- GitHub (source + Cursor / Claude Code files): https://github.com/shisanyue950901-beep/vibe-security-rules
- Free 12-item pre-launch self-check: https://shisanyue950901-beep.github.io/security-checkup/selfcheck.html
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.