Skip to main content

Row Level Security (RLS)

Row Level Security (RLS) is a feature of Supabase that allows you to restrict access to rows in a table based on the user's role. This is useful for implementing fine-grained access control in your application.

To enable RLS on a table, you need to define a policy that specifies the conditions under which a user can access a row. The policy is defined using a SQL CREATE POLICY statement.

Performance optimization

It is important to write policies as efficiently as possible, since they are executed for every single query. Here you can find some performance best practices: Supabase Docs

Example

Suppose you have a table called courses that contains information about courses. You want to restrict access to the rows in the courses table based on the owner_id column. Only the owner of a course should be able to access it.

You can define a policy that allows users to access rows in the courses table only if the owner_id column matches the user's ID. The policy is defined using the following SQL statement:

create policy "Enable ALL for users based on owner_id"
on "public"."courses"
to public
using (
(select auth.uid()) = owner_id
)
with check (
(select auth.uid()) = owner_id
);