4. Row-Level Security (RLS): Data Access Control
RLS: The Most Important Feature in Supabase
Row-Level Security is a PostgreSQL feature that allows you to define fine-grained access rules directly in the database. When RLS is enabled on a table, every query — regardless of what the application code says — is automatically filtered by the policies you define. This makes it impossible to accidentally expose data through a bug in your API layer.
In Supabase, RLS is the primary mechanism for authorization. The JWT from GoTrue is made available inside the database as auth.uid() and auth.jwt(), letting your policies reference the currently authenticated user. This is a game-changer for security. With RLS, your backend becomes stateless — you don't need to check permissions in your application code. The database handles it all. RLS policies are enforced at the query level, so even if someone bypasses your application and queries the API directly, the policies still apply. This defense-in-depth approach means you can trust that your data is safe even if your application code has bugs. RLS is also efficient — policies are evaluated as part of the query execution, so there's no additional round trip to check permissions.
Enabling RLS & the Default-Deny Model
When you run ALTER TABLE ... ENABLE ROW LEVEL SECURITY, the table immediately becomes inaccessible. All queries return zero rows until you add policies. This is the default-deny model — the safest possible default. You then add policies to allow specific operations. This pattern forces you to think about access control from the start. To check which tables have RLS enabled, query pg_tables. For tables with RLS enabled, you'll see rowsecurity = true. Remember that RLS applies to all operations: SELECT, INSERT, UPDATE, DELETE, and TRUNCATE (though TRUNCATE is not covered by row-level policies). The only exception is the service_role key, which bypasses RLS entirely. Use this for server-side admin operations only.
-- Enable RLS on a table (now NO queries work until you add policies) ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
Writing Policies
A policy has three parts: the command it applies to (SELECT, INSERT, UPDATE, DELETE, or ALL), the USING expression (applied on existing rows), and the WITH CHECK expression (applied on new/modified rows). For SELECT, only USING is needed. For INSERT, only WITH CHECK is needed. For UPDATE, you need both — USING to find the row and WITH CHECK to validate the new state. For DELETE, only USING is needed. Policies are combined with OR logic — if any policy allows access, the operation proceeds. This means you can have multiple policies for different access patterns. For example, a users can see their own posts policy and a admins can see all posts policy can coexist. Write clear, specific policies that enforce your business rules.
-- Policy 1: Users can only see their own posts CREATE POLICY "users_see_own_posts" ON posts FOR SELECT USING (auth.uid() = user_id);
Role-Based Access Control with JWT Claims
Supabase lets you store custom claims in the user's JWT via raw_app_meta_data. You can then reference these claims inside RLS policies for role-based access control without a database roundtrip. This is faster than querying the database because the JWT is already in memory. You can set custom claims using the custom_access_token_hook or by updating raw_app_meta_data. Inside policies, use auth.jwt() ->> role to access custom claims. This pattern is ideal for simple role-based access where performance is critical. For complex permissions that require joining multiple tables, you may still need to query the database. But for common cases like admin can do anything, JWT claims are the way to go.
-- Check the user's role from their JWT claims CREATE POLICY "admins_can_read_all_posts" ON posts FOR SELECT USING ( auth.jwt() ->> 'role' = 'admin' );
USING vs WITH CHECK
USING filters the rows that CAN be seen or acted on. WITH CHECK validates the state of the row AFTER the operation. You need USING for SELECT, UPDATE, DELETE. You need WITH CHECK for INSERT and UPDATE. For UPDATE, you typically need both — USING to find the row, WITH CHECK to validate the new state.
Performance: RLS & Indexes
Every RLS policy adds a condition to every query on that table. If your policy references user_id, make sure user_id is indexed — otherwise every query becomes a full table scan. For complex policies with subqueries, performance can degrade significantly. Use STABLE or IMMUTABLE functions in policies so they can be inlined and optimized by the planner. Avoid subqueries when possible — they run per-row. Use materialized views for complex aggregations that would be expensive in a policy. The most important optimization is indexing columns referenced in your USING clauses. For soft-delete patterns, use a partial index that only includes non-deleted rows. These optimizations ensure your RLS policies don't become a performance bottleneck.
- Use STABLE or IMMUTABLE functions in policies — they can be inlined and optimized by the planner.
- Avoid subqueries in policies when possible — they run per-row.
- Use materialized views for complex aggregations that would be expensive in a policy.
Knowledge Check
Ready to test your understanding of 4. Row-Level Security (RLS): Data Access Control?