Row-Level Security (RLS) is a database engine feature that restricts which records are returned or modified based on the authenticated user's session variables. In Supabase, configuration policies ensure that users can only access data they own.
1. RLS Execution flow
When RLS is enabled on a table, all queries are intercepted by the database engine. PostgreSQL verifies each row against the defined query constraints before returning data:
-- Enable security policies on the posts table
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
Without explicit policies, enabling RLS blocks all client queries by default, protecting data from unauthorized access.
2. Writing Security Policies
Policies use the auth.uid() or auth.email() session variables to restrict table actions:
-- Allow users to update only their own profile records
CREATE POLICY "Users can edit own profile"
ON profiles
FOR UPDATE
TO authenticated
USING (id = auth.uid());
This policy ensures updates only execute when the record ID matches the active session ID.