Design Supabase Row-Level Security Around Account Membership
Define membership-based access for documents in a small multi-tenant app and verify each permission role.
Picture a SaaS application that lists documents by account. The browser already adds an account filter. If a staff member from Account A requests a document in Account B, the database still needs its own answer. The application’s client filters help show the right view; membership rules determine which rows a particular reader can access.
This worked example uses a documents table linked to accounts and a membership table connecting account IDs to authenticated users. It’s a generic design example.
Write the permission down before the SQL
A member of the account can read its documents. A member with the editor role can change a document under that account’s rules. Moving a document to another account requires separate authorisation. Decide whether former members should immediately lose access and test that explicitly.
Here is the read policy for the first rule. It assumes the membership table has an appropriate read policy so a signed-in user can see their own membership rows, plus access grants appropriate to the application.
ALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Members read account documents"
ON public.documents FOR SELECT TO authenticated
USING (
EXISTS (
SELECT 1
FROM public.account_members AS membership
WHERE membership.account_id = documents.account_id
AND membership.user_id = (SELECT auth.uid())
)
);
Index the membership lookup keys and inspect the query plan with your expected number of documents. Add policies for the specific write operations you actually support. For an update, check both the existing row and the proposed row. If changing account_id should never be a generic edit, enforce that restriction separately. An editor with access to two accounts may satisfy both membership checks while still being prohibited from moving a record.
Check the permission matrix with normal user sessions
| Actor | Case to try | Expected result |
|---|---|---|
| A member | Reads a document in their account | Visible |
| A member of another account | Reads the same document | No rows returned |
| A viewer | Updates an account document | Denied or no write |
| An editor | Edits document content | Allowed within policy |
| A removed member | Tries to read after removal | No access from the normal user path |
Use two actual test identities for this exercise. A server credential with broad access can bypass the checks you’re trying to validate. Apply the same reasoning to newly added tables and related views. A public export that exposes another account’s document names can break the separation even when the document table’s policy works.
