Row Level Security (RLS): Protecting Data Row by Row
RLS is one of the most important security features in Postgres. It stops one user from reading or changing another user's data.
What you will learn
- If RLS is off, anyone with the public anon key can read every row in the table.
- Always turn on "Enable Row Level Security" for every table in the database.
- Policies: define exactly who may run SELECT, INSERT, UPDATE or DELETE.
- Anonymous users: can, for example, only INSERT into a contact form, but can't read other people's enquiries.
Example security policy for a contact form
Let visitors send enquiries, but don't let them read any:
- Policy name: "Allow anonymous enquiry submissions"
- Allowed operation: INSERT only
- Target role: anon, authenticated
Step by step
SQL command to turn on RLS
ALTER TABLE leads ENABLE ROW LEVEL SECURITY;Locks the table so only the access your policies allow is possible.
Tip from practice
For admin operations in Next.js Server Actions you can use "SUPABASE_SERVICE_ROLE_KEY", which bypasses RLS. That key must NEVER end up in browser code.