6 Supabase RLS Mistakes That Expose Data (Fixed)
Discover the most critical Supabase RLS mistakes that expose sensitive user data. Learn practical SQL fixes and testing patterns to secure your database.

6 Supabase RLS Mistakes That Expose Data (And How to Fix Them)
Supabase makes building backends remarkably fast by exposing PostgreSQL directly to client applications via auto-generated APIs. However, moving database access to the frontend shifts your entire security boundary to Row Level Security (RLS). When configured properly, RLS provides granular, rock-solid authorization right inside the database engine. But when subtle supabase rls mistakes slip into your schema, private user profiles, financial documents, or sensitive tenant data can become instantly readable to anyone with an internet connection and your public anon key.
Modern client-side database queries require an airtight policy configuration. In this guide, we break down the most common Supabase RLS mistakes developers make, demonstrate exactly how they leak information, and show you how to patch them with practical, production-ready SQL.
1. Creating Tables Without Explicitly Enabling RLS
By default in PostgreSQL, creating a table leaves Row Level Security turned off. If you expose a table through the PostgREST API without enabling RLS, anyone holding your public anonymous API key can perform SELECT, INSERT, UPDATE, and DELETE requests directly against that table.
Many developers assume that adding a policy automatically turns on security. It does not. If policies exist on a table where RLS is disabled, Postgres ignores those policies completely.
The Vulnerability
-- Vulnerable: Table created without enabling RLS
CREATE TABLE public.user_notes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
title TEXT,
content TEXT
);
-- This policy does absolutely nothing yet!
CREATE POLICY "Users can only read own notes"
ON public.user_notes
FOR SELECT
USING (auth.uid() = user_id);
The Fix
Always issue an explicit ALTER TABLE ... ENABLE ROW LEVEL SECURITY statement immediately after table creation.
-- Secure: Explicitly enforce RLS
ALTER TABLE public.user_notes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_notes FORCE ROW LEVEL SECURITY;
Pro Tip: Adding
FORCE ROW LEVEL SECURITYensures that table owners and background roles cannot bypass policies accidentally during standard query execution.
2. Neglecting WITH CHECK on UPDATE and INSERT Policies
PostgreSQL RLS policies evaluate conditions using two distinct clauses: USING and WITH CHECK. Confusing these two clauses or omitting WITH CHECK on mutation policies is one of the most widespread Supabase security pitfalls.
USINGdetermines which existing rows are visible for the operation (read, update target, delete target).WITH CHECKvalidates the incoming data row to ensure it complies with your authorization rules after the change is applied.
The Vulnerability
If you define an UPDATE policy with only a USING clause, a user can modify a record they own and change the user_id column to someone else's ID, successfully stealing or transferring ownership.
-- Vulnerable UPDATE policy
CREATE POLICY "Users can update their own profile"
ON public.profiles
FOR UPDATE
TO authenticated
USING (auth.uid() = id);
In the example above, an attacker can send:
PATCH /rest/v1/profiles?id=eq.attacker-uuid
{
"id": "victim-uuid",
"role": "admin"
}
Because the original row matched auth.uid() = id, the USING clause passes. Without a WITH CHECK clause, Postgres does not verify the new record state.
The Fix
Define both USING and WITH CHECK for UPDATE operations, or create an explicit INSERT policy with WITH CHECK.
-- Secure UPDATE policy
CREATE POLICY "Users can update their own profile"
ON public.profiles
FOR UPDATE
TO authenticated
USING (auth.uid() = id)
WITH CHECK (auth.uid() = id);
Alternatively, you can prevent updates to sensitive primary and foreign keys altogether by using PostgreSQL column-level privileges or trigger-based guards.
3. Trusting Unvalidated Client Data Instead of auth.uid()
When users send an insert or update request from a mobile app or frontend framework (like Next.js or React Native), their payload often includes fields like user_id, tenant_id, or organization_id.
A critical vulnerability occurs when an RLS policy relies on values supplied in client request parameters or helper functions that read untrusted JSON rather than Supabase’s built-in cryptographic JWT context.
The Vulnerability
-- Vulnerable: Reading from custom request headers or unverified parameters
CREATE POLICY "Users can insert notes"
ON public.user_notes
FOR INSERT
TO authenticated
WITH CHECK (user_id IS NOT NULL);
Here, an attacker simply passes any valid user UUID in the user_id field. The policy checks only that the field is not null, allowing arbitrary record creation under another user's identity.
The Fix
Bind the authorization constraint directly to auth.uid(), which reads the cryptographically verified sub claim from the user's JSON Web Token (JWT).
-- Secure: Enforce authenticated caller identity
CREATE POLICY "Users can insert notes for themselves"
ON public.user_notes
FOR INSERT
TO authenticated
WITH CHECK (auth.uid() = user_id);
4. Bypassing RLS with SECURITY DEFINER Views and Functions
PostgreSQL allows functions and views to run under one of two execution contexts:
SECURITY INVOKER: Runs with the permissions of the user calling the function or querying the view (respects RLS).SECURITY DEFINER: Runs with the privileges of the user who defined the object—typicallypostgresorsupabase_admin(bypasses RLS).
Developers often reach for SECURITY DEFINER when writing database functions to bypass permission errors. However, exposing a SECURITY DEFINER function or view to public schema APIs without strict internal checks can grant unauthenticated users admin-level access.
The Vulnerability
-- Vulnerable view exposed via PostgREST
CREATE VIEW public.team_members_summary AS
SELECT id, team_id, user_email, role
FROM public.team_members;
-- The view runs as the creator and ignores table-level RLS on team_members!
In Supabase, any view created in the public schema is accessible through PostgREST. Prior to PostgreSQL 15, views automatically ran as SECURITY DEFINER.
The Fix
In modern PostgreSQL versions (15+), set security_invoker = true when creating views to force them to adhere to the caller's RLS permissions:
-- Secure: Force view to respect calling user's RLS
CREATE VIEW public.team_members_summary
WITH (security_invoker = true) AS
SELECT id, team_id, user_email, role
FROM public.team_members;
For custom PL/pgSQL functions that must run as SECURITY DEFINER, pin the search_path to prevent search-path hijacking and manually enforce identity checks:
-- Secure SECURITY DEFINER function
CREATE OR REPLACE FUNCTION public.delete_user_account()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public, auth
AS $$
BEGIN
-- Explicitly verify caller identity
IF auth.uid() IS NULL THEN
RAISE EXCEPTION 'Not authenticated';
END IF;
DELETE FROM public.profiles WHERE id = auth.uid();
END;
$$;
5. Overly Broad Policy Targets (Merging Roles and Operations)
Supabase allows you to write policies for ALL commands and apply them to PUBLIC (which includes both anonymous visitors and authenticated users). While this can save time during prototyping, grouping actions under broad policies often opens unauthorized read or write vectors.
The Vulnerability
-- Vulnerable: Permits both read and write to all authenticated users
CREATE POLICY "Team collaboration policy"
ON public.documents
FOR ALL
TO authenticated
USING (team_id IN (
SELECT team_id FROM public.memberships WHERE user_id = auth.uid()
));
Because this policy applies to FOR ALL and contains only a USING clause, it governs SELECT, INSERT, UPDATE, and DELETE. However, because there is no WITH CHECK, any team member can insert records containing arbitrary data or delete core project documents without role differentiation.
The Fix
Apply the principle of least privilege. Split your policies by specific SQL operation and assign targeted roles (authenticated vs. anon):
-- Secure: Explicit read permissions
CREATE POLICY "Team members can view documents"
ON public.documents
FOR SELECT
TO authenticated
USING (
team_id IN (SELECT team_id FROM public.memberships WHERE user_id = auth.uid())
);
-- Secure: Explicit insert permissions with data validation
CREATE POLICY "Team members can insert documents"
ON public.documents
FOR INSERT
TO authenticated
WITH CHECK (
team_id IN (SELECT team_id FROM public.memberships WHERE user_id = auth.uid())
AND created_by = auth.uid()
);
6. Performance-Induced Policy Disabling (The Unindexed Subquery Trap)
When your application scales, poorly optimized RLS policies cause database latency to skyrocket. When queries slow down, teams sometimes disable RLS temporarily to isolate bottlenecks, inadvertently exposing production data.
The primary culprit is unindexed foreign keys inside RLS subqueries. Every time a row is scanned, PostgreSQL evaluates your policy condition. If that condition triggers a table scan, a query fetching 100 rows can trigger 100 sequential scans on your relations.
Comparison: Common Mistakes vs. Secure Solutions
| Mistake | Threat Vector | Secure Implementation |
|---|---|---|
| Omitting RLS Flag | Total table exposure to anonymous visitors | Run ALTER TABLE ... ENABLE ROW LEVEL SECURITY on every public table |
Missing WITH CHECK |
Attackers modify ownership fields (user_id) |
Include both USING and WITH CHECK clauses on UPDATE / INSERT |
| Client-Side UUIDs | User spoofing and identity impersonation | Enforce server-side evaluation via auth.uid() |
Unrestricted SECURITY DEFINER |
Privilege escalation across views/routines | Set security_invoker = true on views; sanitize function paths |
Blanket FOR ALL Policies |
Read policies accidentally allowing deletes | Split policies across SELECT, INSERT, UPDATE, and DELETE |
| Unindexed Subqueries | Severe CPU spikes leading to policy bypasses | Wrap queries in helper functions and add indexes to foreign keys |
How to Test and Audit Your Supabase Policies
Securing your database is not a one-and-done task; it requires ongoing verification. You can test your policies directly in the Supabase SQL Editor using database transactions that simulate specific users.
Step 1: Impersonate Authenticated Roles in SQL
Run this script in your Supabase SQL editor to test if an authenticated user can access unauthorized data:
BEGIN;
-- Simulate an authenticated user session
SET LOCAL ROLE authenticated;
SET LOCAL "request.jwt.claim.sub" = 'd3b07384-d113-4a41-b844-302efd297a78';
-- Attempt to read records belonging to another user
SELECT * FROM public.user_notes;
-- Attempt an unauthorized insert
INSERT INTO public.user_notes (user_id, title, content)
VALUES ('00000000-0000-0000-0000-000000000000', 'Hacked Title', 'Exploit payload');
-- Always roll back so test mutations don't persist
ROLLBACK;
If the SELECT query returns rows that do not belong to the simulated user ID, or if the INSERT succeeds without error, your policy is leaking access.
Step 2: Run the Supabase CLI Database Linter
The official Supabase CLI contains built-in security linters that flag unprotected tables and broken policies before they reach production. Run this command in your repository:
supabase db lint
The linter scans your migrations and warns you if any table in the public schema lacks enabled RLS or contains permissive policies targeting the anon role.
Summary Checklist for Secure Supabase Policies
- Verify every table: Confirm that every table exposed to PostgREST has RLS enabled.
- Never trust input: Bind all user constraints to
auth.uid(), not incoming request JSON. - Double-check writes: Always supply a
WITH CHECKexpression onUPDATEandINSERTpolicies. - Isolate views: Set
WITH (security_invoker = true)on all public-facing views. - Add foreign key indexes: Ensure any column referenced inside an RLS subquery has a corresponding B-tree index.
FAQ
What happens if I enable RLS on a table but add no policies?
If you enable RLS on a table and do not create any policies, PostgreSQL defaults to an explicit "deny all" rule for all non-superuser roles. Clients querying via the Supabase client library will receive empty arrays for SELECT queries and permission-denied errors for any mutation attempts.
Does Supabase RLS apply when using the Service Role key?
No. The service_role key bypasses all Row Level Security policies completely. It connects as a privileged administrative role. You should only use the service role key in secure, trusted server environments (such as private backend workers or server-side API routes), and never expose it in client-side code.
Can an attacker bypass RLS by modifying headers in their browser?
No, provided your policy relies on auth.uid(). Supabase validates the cryptographic signature of the JWT on incoming requests before setting the internal Postgres context. An attacker cannot forge an arbitrary user UUID unless they possess your project's private JWT secret.
What is the difference between TO public and TO authenticated in a policy?
TO public applies the policy to every database role, including completely unauthenticated visitors using the anon key. TO authenticated applies the rule strictly to users who have logged in and possess a valid JWT issued by Supabase Auth.
Why does my Supabase query work in the Dashboard but fail on the client?
The Supabase Dashboard Table Editor runs queries using the administrative postgres user, which bypasses Row Level Security policies by default. Client applications authenticate as either anon or authenticated, meaning they are bound by the RLS rules you have defined.