Firestore Security Rules

Security rules allow you to control access to your documents and collections. They are essential for protecting your data once your app is live.

1. The Basic Structure

Rules match paths in your database and grant allow read or allow write access based on conditions.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /<path>/{document} {
      allow <action>: if <condition>;
    }
  }
}

2. Common Patterns

Public (No Security)

Only for development! Never use this in production.

allow read, write: if true;

Authenticated Users Only

allow read, write: if request.auth != null;

Owner Only

Users can only read/write their own profiles.

match /users/{userId} {
  allow read, write: if request.auth != null && request.auth.uid == userId;
}

3. Granular Actions

Instead of just `read` and `write`, you can be more specific:

  • read: combines `get` and `list`.
  • write: combines `create`, `update`, and `delete`.
Warning: Always test your security rules in the Rules Playground in the Firebase Console before publishing them!