Mastering Firestore Security Rules

Mastering Firestore Security Rules: Patterns & Examples

Master Firestore security rules with deny-all defaults, user-scoped access, data validation, Spark quota tips, and Clerk or Supabase auth bridges.

Muhammad Hassaan
Muhammad HassaanMH Labs
•6 min read

Firestore security rules are your database's bouncer. They decide who gets in, what they can see, and what they can change. This guide covers Firestore security rules syntax and real-world patterns you will actually use in production.

Want an AI coding agent to write these rules for your project? Copy the ready-to-use prompt from Firebase & Firestore AI Prompts: Write Firestore Security Rules for Your Project into Cursor, Claude Code, or Copilot and let your agent inspect your collections and generate firestore.rules.

If you have not set up your deployment workflow yet, start with either Method 1: Firebase CLI or Method 2: Firebase Admin SDK first, then come back here.


Understanding the Rules Language

Firestore uses its own declarative security rules language. Every read or write request from your app is evaluated against these rules before anything touches the database. Because the rules run on Google's servers rather than in your client app, they cannot be tampered with.

The basic structure looks like this:

javascript
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // your rules go here } }

Always use rules_version = '2'. It is the latest rules version and supports collection group queries. For a complete reference, see the official Firestore Security Rules docs.

Key Objects You Need to Know

  • request.auth: Contains information about the logged-in user. If no one is logged in, this is null.
  • request.auth.uid: The unique ID of the authenticated user.
  • request.resource.data: The incoming data being sent to the database (for creates and updates).
  • resource.data: The existing data already stored in the database (for reads, updates, and deletes).

1. Default to "Deny All"

The safest way to start is to lock every door in your database and only open the ones you explicitly need.

javascript
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Lock everything by default match /{document=**} { allow read, write: if false; } } }

If you create a new collection tomorrow, it stays locked until you add a matching rule. Deny by default, allow by exception.

2. Public Data (System and App Configs)

Most apps have system-level data that every user needs to read, such as app_config, services, plans, or metadata. This data is managed by you (via Admin SDK or console), not by end users.

javascript
// System data: anyone can read, no one can write from the client match /app_config/{configId} { allow read: if true; allow write: if false; } match /services/{serviceId} { allow read: if true; allow write: if false; }

This allows public reads while locking down client writes. Your backend scripts using the Admin SDK bypass these rules entirely.

To restrict reads to authenticated users only, change if true to if request.auth != null.

3. User Data (Private Access)

Each user should only access their own data. User A should never see User B's profile, orders, or settings.

javascript
match /users/{userId} { // Only the owner can read and write allow read, write: if request.auth != null && request.auth.uid == userId; // Subcollections inherit the same logic match /orders/{orderId} { allow read, write: if request.auth != null && request.auth.uid == userId; } match /settings/{settingId} { allow read, write: if request.auth != null && request.auth.uid == userId; } }

The {userId} in the path is a wildcard matching the document ID. Comparing it against request.auth.uid ensures only the authenticated owner gets access.

Flowchart showing Firestore security rules v2 evaluation for public config, user-owned documents, and default deny

4. A Complete Working Example

Here is a starter firestore.rules file combining all of the patterns above:

javascript
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Default: deny everything match /{document=**} { allow read, write: if false; } // Public system data match /app_config/{configId} { allow read: if true; allow write: if false; } match /services/{serviceId} { allow read: if request.auth != null; allow write: if false; } // Private user data match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; match /todos/{todoId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } } }

5. Third-Party Auth (Clerk, Supabase, and Others)

If you use Clerk or Supabase instead of Firebase Auth, Firestore rules will not recognize your users out of the box. request.auth will remain null because Firestore only validates Firebase Auth tokens.

How to Handle It

  • Option A (Backend Proxy): Do not let your client app talk to Firestore directly. Route requests through a server or Edge Function that validates the Clerk or Supabase token, then uses firebase-admin to read or write Firestore.
  • Option B (Custom Token Bridge): When a user signs in via Clerk, use a backend function to validate their session and mint a Firebase Custom Token. Your app then calls signInWithCustomToken() in the Firebase SDK so request.auth is populated normally.

If you are already using Supabase as your primary database, consider Supabase Row Level Security (RLS) instead of duplicating auth logic across two platforms.


Data Validation in Rules

Security rules are not just for identity; they can also validate incoming payloads to protect data integrity:

javascript
match /products/{productId} { allow create: if request.auth != null && request.resource.data.name is string && request.resource.data.name.size() < 100 && request.resource.data.price is number && request.resource.data.price > 0; }

Best Practices (Including Spark Quota Protection)

  1. Avoid get() and exists() when you can: Every get() or exists() call inside a security rule counts as a database read. On Firebase's free Spark plan (50,000 reads and 20,000 writes per day), heavy get() chains inside rules eat through your daily read quota fast and add latency.
  2. Keep structures flat: Deeply nested collections make rules harder to write and debug.
  3. Test in the Simulator: Always test read and write scenarios in the Firebase Console Rules Simulator before deploying.

For edge cases, see the Firebase Security Rules Reference and Manage & Deploy Rules.


Take the time to master these patterns. They are the foundation of a trustable product, whether you are building an Expo React Native app, a Next.js SaaS, or anything in between.

Insights, Playbooks, Tips & Kits

Want real patterns from my journey building and selling SaaS & apps. DIY playbooks, code-ready starter kits, and the operational moves that let you scale without the overhead. For builders who learn best from firsthand mistakes, real wins & experience.