
On this page
Table of Contents
Supabase Row Level Security (RLS) Explained with Practical SQL Examples
Your application might show users only their own data. But what happens if someone skips your interface and sends a query directly to the Supabase API?
If access control exists only in your frontend code, that query may return data the user should never see.
Consider a simple todo application. Your interface fetches tasks using:
const { data, error } = await supabase
.from("todos")
.select("*")
.eq("user_id", user.id);This query filters tasks for the current user.
But the filter itself is not a security boundary.
A user who can access your Supabase project through its public client credentials can construct a different query without that filter.
Supabase Row Level Security (RLS) addresses this problem by enforcing access rules in PostgreSQL, independently of your application's interface.
In this guide, we'll cover practical RLS examples for personal data, blog posts, team membership, and admin access. We'll also explain the mistakes that can accidentally expose data.
Before you begin: These SQL examples demonstrate separate authorization patterns. They are not one combined migration. Test them in a disposable Supabase project and adapt their permissions to your schema before deploying them.
1. What Is Row Level Security in Supabase?
Row Level Security is a PostgreSQL feature that controls which rows a database role can access or modify.
Without RLS, a table permission such as SELECT can allow access to every row in that table.
With RLS enabled, PostgreSQL evaluates applicable policies to decide which rows are available.
For example:
create policy "Users read their own todos"
on public.todos
for select
to authenticated
using (
(select auth.uid()) = user_id
);This policy means an authenticated user can read rows where user_id matches their Supabase Auth user ID.
Even if they omit the filter in their JavaScript query, PostgreSQL still enforces the policy.
How does auth.uid() work?
Supabase provides the auth.uid() helper, which identifies the authenticated user associated with the current request.
For a request without a valid authenticated session, it returns null.
A policy such as:
using ((select auth.uid()) = user_id)will therefore not grant access to another user's rows merely because a request uses the public Supabase key.
Important: RLS is not the only permission layer
PostgreSQL uses both privileges and policies.
Table grants decide whether a database role can perform an operation at all.
RLS policies decide which rows the operation may affect.
For example, a role needs the appropriate table permission before an applicable RLS policy can permit it to read a row.
Also remember that privileged roles, table owners in normal configurations, and roles with BYPASSRLS may bypass row security.
That's why RLS should be described as strong database-enforced access control, not as a rule that nobody can ever bypass.
2. Enable RLS and Understand the Default Behavior
You enable RLS separately for each table:
alter table public.todos
enable row level security;For ordinary roles subject to RLS, enabling it without an applicable policy produces a default-deny result.
But don't confuse this with revoking existing privileges.
A table can still have grants that are broader than your application needs.
As a general setup pattern, review and restrict privileges before adding policies.
For example, for a new personal-todo table:
revoke all on table public.todos
from anon, authenticated;
grant select, insert, update, delete
on table public.todos
to authenticated;The authenticated role now has permission to attempt these operations.
The policies in the next section determine which rows that role can actually access.
These commands assume a new table with no additional column-level or inherited privilege requirements. For an existing table, audit its effective grants instead of copying a generic REVOKE and assuming all access paths are covered.
3. Example 1: Secure Personal Todos
Let's build a small table where each user manages only their own tasks.
Create the table
create table public.todos (
id uuid primary key default gen_random_uuid(),
user_id uuid not null
references auth.users(id),
title text not null
check (char_length(title) between 1 and 200),
completed boolean not null default false,
created_at timestamptz not null default now()
);
create index todos_user_id_idx
on public.todos(user_id);
alter table public.todos
enable row level security;
revoke all on table public.todos
from anon, authenticated;
grant select, insert, update, delete
on table public.todos
to authenticated;We'll define four policies.
Policy 1: Read your own todos
create policy "Read own todos"
on public.todos
for select
to authenticated
using (
(select auth.uid()) = user_id
);A signed-in user can read their own rows.
Other users' rows are not visible through ordinary queries governed by this policy.
Policy 2: Insert your own todos
create policy "Insert own todos"
on public.todos
for insert
to authenticated
with check (
(select auth.uid()) = user_id
);This prevents an ordinary authenticated client from inserting a task owned by someone else.
For example, if User A submits a user_id belonging to User B, the operation should be denied by this policy.
Policy 3: Update your own todos
create policy "Update own todos"
on public.todos
for update
to authenticated
using (
(select auth.uid()) = user_id
)
with check (
(select auth.uid()) = user_id
);The two clauses serve different purposes:
USINGdetermines which existing rows may be updated.WITH CHECKdetermines which resulting rows are allowed.
This prevents User A from changing their task's ownership to User B.
For Supabase update operations, an appropriate SELECT policy is also important.
Policy 4: Delete your own todos
create policy "Delete own todos"
on public.todos
for delete
to authenticated
using (
(select auth.uid()) = user_id
);Now the basic personal-todo example has separate policies for reading, inserting, updating, and deleting.
Test it with two users
Create two test accounts.
Insert a task belonging to User A and another belonging to User B using a trusted fixture setup.
Then authenticate as User A and query:
const { data, error } = await supabase
.from("todos")
.select("id, title, user_id");Expected result: only the rows User A is allowed to read.
Repeat with User B.
Also attempt to create or modify a row belonging to the other account.
Do not treat an empty response alone as proof that every policy is correct. Confirm the seeded rows exist and that you are testing with real authenticated sessions.
4. Understand USING vs. WITH CHECK
This distinction matters when building RLS policies.
USING: Can the user access the existing row?
For example:
using (
(select auth.uid()) = user_id
)The condition checks the existing row against the user's identity.
It is commonly used for SELECT, UPDATE, and DELETE.
WITH CHECK: Is the new row state allowed?
For example:
with check (
(select auth.uid()) = user_id
)This checks the data being inserted or the resulting data after an update.
It is used with INSERT and UPDATE.
For a typical ownership-based update, explicitly specifying both conditions improves clarity.
Important: WITH CHECK validates a row condition. It does not automatically restrict which individual columns a user may change.
If a user must never modify a privilege-related field such as is_admin, use proper column privileges, a controlled function, or another independently enforced design.
5. Example 2: Public Blog Posts and Private Drafts
Blog applications often need two different visibility rules:
- Everyone can read published posts.
- Authors can also read their own unpublished drafts.
Writing permissions are different from reading permissions.
Example table
create table public.posts (
id uuid primary key default gen_random_uuid(),
author_id uuid not null
references auth.users(id),
title text not null,
content text not null,
published boolean not null default false,
created_at timestamptz not null default now()
);
create index posts_author_id_idx
on public.posts(author_id);
alter table public.posts
enable row level security;
revoke all on table public.posts
from anon, authenticated;
grant select on public.posts to anon;
grant select, insert, update, delete
on public.posts to authenticated;This example allows authors to publish their own posts. A platform requiring editorial approval needs a different publishing-permission model.
Everyone can read published posts
create policy "Read published posts"
on public.posts
for select
to anon, authenticated
using (
published = true
);Authors can read their own posts
create policy "Authors read own posts"
on public.posts
for select
to authenticated
using (
(select auth.uid()) = author_id
);These policies work together.
Signed-out visitors can read published posts.
Authenticated authors can read their own drafts as well as published posts.
Authors can create posts
create policy "Authors create posts"
on public.posts
for insert
to authenticated
with check (
(select auth.uid()) = author_id
);Authors can edit their own posts
create policy "Authors update own posts"
on public.posts
for update
to authenticated
using (
(select auth.uid()) = author_id
)
with check (
(select auth.uid()) = author_id
);Authors can delete their own posts
create policy "Authors delete own posts"
on public.posts
for delete
to authenticated
using (
(select auth.uid()) = author_id
);This pattern is easier to audit than a single broad FOR ALL policy.
How do multiple policies combine?
By default, PostgreSQL policies are permissive.
When multiple applicable permissive policies exist, they are combined using OR.
That means a published post may pass the public-read policy even if the viewer isn't its author.
PostgreSQL also supports restrictive policies, which combine differently. Don't assume every policy you add always behaves as another permissive OR condition.
A common blog security mistake
Suppose your application lets authors create posts but only administrators approve them for publication.
An author-controlled published boolean would undermine that workflow if the author can simply set it to true.
In that case, use column-level permissions or a controlled publishing operation that validates the administrator role.
RLS ownership checks alone do not implement editorial approval.
6. Example 3: Team-Based Access in a Multi-Tenant App
Personal ownership is straightforward.
Team-based applications are more complicated because multiple users may need access to the same records.
Imagine a project management application with:
- Teams
- Team members
- Projects belonging to teams
A project should be visible only to members of its team.
Example schema
create table public.teams (
id uuid primary key default gen_random_uuid(),
name text not null
);
create table public.team_members (
team_id uuid not null
references public.teams(id),
user_id uuid not null
references auth.users(id),
primary key (team_id, user_id)
);
create table public.projects (
id uuid primary key default gen_random_uuid(),
team_id uuid not null
references public.teams(id),
name text not null
);
create index team_members_user_idx
on public.team_members(user_id);
create index projects_team_idx
on public.projects(team_id);The team membership table determines which users belong to each team.
Enable RLS:
alter table public.team_members
enable row level security;
alter table public.projects
enable row level security;Restrict application access for this read-only example:
revoke all on
public.team_members,
public.projects
from anon, authenticated;
grant select on
public.team_members,
public.projects
to authenticated;Users can read their own memberships
create policy "Read own memberships"
on public.team_members
for select
to authenticated
using (
(select auth.uid()) = user_id
);Team members can read team projects
create policy "Members read team projects"
on public.projects
for select
to authenticated
using (
team_id in (
select tm.team_id
from public.team_members as tm
where tm.user_id = (select auth.uid())
)
);This example checks team membership before allowing access to a project.
The membership policy is simple and only reads the current user's membership rows.
That avoids the direct self-referencing pattern that can cause recursive RLS policies.
Where does membership data come from?
This example deliberately does not provide a client-side membership-creation policy.
Membership changes should be handled through a separate, authorized invitation or administration workflow.
If ordinary users can insert arbitrary records into team_members, they could grant themselves access to teams they don't belong to.
RLS rules for membership creation are just as important as the rules protecting projects.
7. Why Supabase RLS Policies Sometimes Cause Infinite Recursion
A common PostgreSQL error is:
infinite recursion detected in policy
for relation "team_members"This can happen when a policy on a table queries that same table through a path that triggers the policy again.
For example, imagine a policy on team_members that reads team_members to determine whether the caller is a team member.
PostgreSQL attempts to evaluate the policy, but the lookup causes the same policy to be evaluated again.
That recursive evaluation cannot finish.
How to avoid it
Start with a simpler policy that doesn't recursively reference the protected table.
Where the authorization design requires more complicated membership checks, a carefully reviewed SECURITY DEFINER function can sometimes break the recursion by performing the membership lookup using a trusted function owner.
But that introduces a new security boundary.
A SECURITY DEFINER function must use a controlled search path, restricted execution permissions, and carefully defined access rules.
It should generally be created in a private, non-API-exposed schema for this kind of authorization helper.
Do not add an unrestricted privileged helper just to make a recursion error disappear.
If an RLS design becomes difficult to reason about, simplify the membership model before introducing more privileged functions.
8. Example 4: Secure Admin-Only Access
Some applications need administrators to view records that ordinary users cannot access.
For example, an administrator may need to review every order, while regular users can read only their own orders.
A common mistake is placing an is_admin flag in an ordinary profile and allowing users to update every field in that profile.
If users can change their own is_admin value, the authorization system becomes vulnerable.
Use a protected role table
For this example, assume a trusted administrator provisions the role records.
create table public.user_roles (
user_id uuid primary key
references auth.users(id),
is_admin boolean not null default false
);
alter table public.user_roles
enable row level security;
revoke all on public.user_roles
from anon, authenticated;Do not provide ordinary users with direct insert or update privileges on this table.
Create a private role-check helper
create schema if not exists private;
create or replace function private.is_current_user_admin()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.user_roles as r
where r.user_id = (select auth.uid())
and r.is_admin = true
);
$$;
revoke all on function
private.is_current_user_admin()
from public, anon, authenticated;
grant usage on schema private
to authenticated;
grant execute on function
private.is_current_user_admin()
to authenticated;This function should be owned by a trusted database role and must be reviewed before use.
Keep the private schema out of Supabase's exposed API schemas.
The function returns only a boolean indicating whether the caller has a trusted admin record.
Use the helper in an orders policy
Assume an existing public.orders table has an owner_id UUID column and appropriate table grants.
alter table public.orders
enable row level security;
create policy "Owners and admins read orders"
on public.orders
for select
to authenticated
using (
owner_id = (select auth.uid())
or
(select private.is_current_user_admin())
);A regular user can read their own orders.
A verified administrator can read additional records according to the policy.
This example covers SELECT only.
Creating, updating, approving, and deleting orders need their own authorization design.
Security warning
Do not use user-editable profile metadata as the source of administrative authority.
Also, review the function owner, schema access, function grants, table grants, and every other policy on the orders table.
Another permissive policy can grant broader access than this example intends.
The public.orders reference above is an illustrative table name. Adapt the policy only after confirming the actual schema and existing permissions.
9. How to Test Supabase RLS Policies
Writing policies is only half the task.
You must check whether they enforce the intended behavior.
A reliable test includes at least two authenticated users and an unauthenticated request.
Test 1: Read your own records
Authenticate as User A.
Query the protected table.
Expected outcome: User A can read their authorized records.
Test 2: Attempt cross-user access
Authenticate as User B.
Try to read User A's records.
Expected outcome: User B does not receive records they lack permission to access.
Test 3: Attempt unauthorized writes
Try to insert or update a row with another user's ID.
Expected outcome: The write is rejected or affects no unauthorized rows, depending on the operation and policy.
Test 4: Test anonymous access
Use a public Supabase client without an authenticated user session.
Try to read private data.
Expected outcome: Private records are not returned.
Test 5: Verify administrative boundaries
Test one admin and one ordinary user.
Confirm that only the admin can access administrator-restricted information.
Also confirm that ordinary users cannot assign themselves an admin role.
Use real authenticated clients
For Supabase JavaScript clients, use separate signed-in sessions:
const { data, error } = await supabase
.from("todos")
.select("id, title, user_id");
if (error) {
console.error(error);
} else {
console.log(data);
}Execute the same query under different identities.
The returned rows should match the applicable policies.
Automated SQL testing
Supabase also supports database testing using pgTAP.
Its CLI provides a command for running database tests:
supabase test dbYou can create tests that verify policies, expected access, and denied operations.
A manual SQL Editor query running as a privileged database owner is not equivalent to a request from an ordinary authenticated user.
Verification note: The examples above describe intended behavior and test scenarios. They have been reviewed against PostgreSQL and Supabase documentation, but have not been independently executed against a real Supabase database for this article.
10. Common Supabase RLS Mistakes
Mistake 1: Forgetting to enable RLS
Creating a policy is not a substitute for ensuring the table is protected.
Enable RLS and review effective table privileges.
Mistake 2: Exposing secret keys in the browser
Public or publishable Supabase credentials are designed for client-side use with appropriate database permissions and RLS.
Secret keys and legacy service-role credentials are privileged.
Never include them in browser code or NEXT_PUBLIC_ environment variables.
Mistake 3: Assuming every policy is restrictive
Multiple permissive policies can grant access through OR conditions.
Always review all policies on a table, not just the newest one.
Mistake 4: Trusting user-editable role information
User-controlled metadata should not determine whether someone is an administrator.
Use trusted role records or server-managed authorization claims.
Mistake 5: Ignoring views
Views can behave differently from ordinary tables and may expose rows that underlying RLS policies would otherwise hide.
For supported PostgreSQL versions, security_invoker views can help ensure that access follows the calling user's permissions.
Audit views separately.
Mistake 6: Forgetting the update check
Use both USING and WITH CHECK when the existing and resulting row must satisfy ownership rules.
Remember that a SELECT policy may also be required for update operations.
Mistake 7: Treating a successful client query as a complete security test
A query that returns expected rows for one user doesn't prove that another user is blocked.
Always test unauthorized identities and write operations.
11. Optimize RLS Performance
RLS is evaluated as part of database queries.
A policy that repeatedly performs expensive lookups can affect performance, particularly on large tables.
Index the columns used for filtering
If a policy frequently checks:
user_id = (select auth.uid())an index on user_id may improve query performance:
create index todos_user_id_idx
on public.todos(user_id);Avoid creating duplicate indexes when the required leading-column index already exists.
Use the SELECT wrapper appropriately
Supabase recommends patterns such as:
using (
(select auth.uid()) = user_id
)For a helper function whose result is independent of the current row, this can allow PostgreSQL to evaluate the value efficiently rather than recomputing it unnecessarily for every candidate row.
Do not apply this technique blindly to functions whose result depends on row-specific values.
Measure instead of guessing
Use PostgreSQL query plans and representative test data to identify performance problems.
Indexing and query structure often matter more than clever-looking SQL.
Avoid claiming a specific speed improvement unless you have actual before-and-after measurements.
12. A Supabase RLS Security Checklist
Before using a protected table in production, verify:
- RLS is enabled.
- Table grants allow only intended operations.
- Policies explicitly target the appropriate database roles.
- Users cannot read other users' private records.
- Users cannot insert or modify records they don't own.
- Privilege-related columns cannot be edited by ordinary users.
- Privileged functions are carefully reviewed.
- Secret credentials remain server-side.
- Related views are audited.
- Authorized and unauthorized access tests pass.
For multi-tenant applications, add tests for team invitations, membership removal, organization ownership, and administrative actions.
Security should be verified at the database boundary rather than inferred from what the interface displays.
Final Thoughts
Supabase Row Level Security is one of the most important features to understand when building applications that store user-specific data.
It shifts row-access decisions into PostgreSQL, where they can apply consistently to queries made through your application and other permitted database access paths.
But enabling RLS is only the beginning.
A secure implementation also needs correct grants, appropriately scoped policies, trusted authorization data, carefully controlled privileged functions, and tests using real user identities.
Start with a simple ownership policy.
Understand the difference between USING and WITH CHECK.
Then move toward more complex patterns, such as team membership and administrator access, only when your application requires them.
The goal isn't to write the most complicated RLS policy. It's to make unauthorized data access reliably fail.
Related CodeWithLogs Guides
- Supabase Production Errors and Fixes
- Build an Inventory Management System with Next.js and Supabase
- Next.js Authentication Without NextAuth
- Debug Production Errors in Next.js
- Error Decoder Tool
Official Documentation
Keep the conversation useful
Found a different result?
Include your framework version, the error, and the steps to reproduce it. Specific details help improve the article for the next reader.
Send a correction or question

