Bird
Raised Fist0
Firebasecloud~10 mins

Rule syntax and structure in Firebase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Rule syntax and structure
Start: Define rules block
↓
Specify service (e.g., firestore)
↓
Define match path (document or collection)
↓
Set allow conditions (read, write)
↓
Use expressions to check auth, data
↓
Return true or false
↓
End of rule block
This flow shows how Firebase security rules are structured: start with a rules block, specify the service, match data paths, set allow conditions, and return true or false to permit or deny access.
Execution Sample
Firebase
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}
This rule allows users to read and write only their own user document based on matching userId with their authentication ID.
Process Table
StepRule PartActionEvaluationResult
1rules_version = '2'Set rules versionVersion set to 2Success
2service cloud.firestoreSpecify Firestore serviceService identifiedSuccess
3match /databases/{database}/documentsMatch all documents in databaseWildcard {database} captures database nameSuccess
4match /users/{userId}Match user documentsWildcard {userId} captures user IDSuccess
5allow read, write: if request.auth.uid == userIdCheck if authenticated user ID equals userId in pathIf equal, allow accessAccess granted if true, denied if false
6End of rulesNo more rules to evaluateEvaluation completeRules applied
💡 Rules evaluation ends after checking all defined matches and conditions.
Status Tracker
VariableStartAfter Step 4After Step 5Final
rules_versionundefinedundefined'2''2'
serviceundefined'cloud.firestore''cloud.firestore''cloud.firestore'
databaseundefinedcaptured from pathcaptured from pathcaptured from path
userIdundefinedcaptured from pathcaptured from pathcaptured from path
request.auth.uidundefinedundefinedprovided by user authprovided by user auth
allowundefinedundefinedtrue if request.auth.uid == userIdtrue or false
Key Moments - 3 Insights
Why do we use wildcards like {userId} in match paths?
Wildcards capture parts of the path dynamically, allowing rules to apply to many documents without writing separate rules for each. See execution_table step 4 where {userId} captures the user ID.
What happens if the condition in 'allow' is false?
Access is denied if the condition evaluates to false. In execution_table step 5, if request.auth.uid does not equal userId, the rule returns false and denies access.
Can rules apply to multiple operations at once?
Yes, you can specify multiple operations like 'read, write' together in one allow statement, as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 5, what condition must be true to allow access?
Arequest.auth.uid equals userId
Brequest.auth.uid is undefined
CuserId is empty
Drequest.auth.uid is different from userId
💡 Hint
Check the 'Evaluation' column in step 5 of execution_table.
At which step does the rule capture the userId from the document path?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for 'Wildcard {userId} captures user ID' in execution_table.
If we remove 'write' from the allow statement, what changes in the rule behavior?
AUsers can only write their documents
BUsers can only read their documents
CUsers can read and write their documents
DUsers cannot read or write their documents
💡 Hint
Refer to the 'allow read, write' part in execution_sample and think about removing 'write'.
Concept Snapshot
Firebase rules start with a version and service declaration.
Use match blocks with wildcards to specify document paths.
Allow statements define read/write permissions with conditions.
Conditions use request.auth and path variables.
Rules return true to allow or false to deny access.
Full Transcript
Firebase security rules control access to your database. You start by setting the rules version and specifying the service, like Firestore. Then you define match blocks that point to document paths, using wildcards to capture dynamic parts like user IDs. Inside these matches, you write allow statements that say when read or write is allowed. These statements use conditions comparing the authenticated user's ID to the document's userId. If the condition is true, access is granted; otherwise, it is denied. This structure helps keep your data safe by ensuring users can only access their own documents.

Practice

(1/5)
1. What is the main purpose of a match block in Firebase security rules?
easy
A. To create new collections automatically
B. To define user roles and permissions
C. To write data to the database
D. To specify which data paths the rules apply to

Solution

  1. Step 1: Understand the role of match blocks

    The match block is used to specify the path in the database where the rules apply.
  2. Step 2: Differentiate from other rule parts

    Other parts like allow control access, but match targets the data location.
  3. Final Answer:

    To specify which data paths the rules apply to -> Option D
  4. Quick Check:

    match = data path selector [OK]
Hint: Remember: match points to data location [OK]
Common Mistakes:
  • Confusing match with allow
  • Thinking match defines user roles
  • Assuming match writes data
2. Which of the following is the correct syntax to allow read access to all users in a Firebase rule?
easy
A. allow read { true }
B. allow read: if true;
C. allow read = true;
D. allow read if (true)

Solution

  1. Step 1: Recall correct allow syntax

    The correct syntax uses a colon and condition: allow read: if true;
  2. Step 2: Check other options for syntax errors

    Options A, B, and D use incorrect symbols or missing keywords.
  3. Final Answer:

    allow read: if true; -> Option B
  4. Quick Check:

    Correct allow syntax uses colon and if [OK]
Hint: Use colon and 'if' for conditions in allow [OK]
Common Mistakes:
  • Using '=' instead of ':'
  • Omitting 'if' keyword
  • Using braces instead of semicolon
3. Given the rule snippet:
match /posts/{postId} {
  allow read: if request.auth != null;
  allow write: if request.auth.uid == resource.data.authorId;
}

What happens if a logged-in user tries to write to a post they did NOT create?
medium
A. Write is denied because user is not the author
B. Write is allowed because user is logged in
C. Write is allowed only if postId matches user ID
D. Write is denied because read access is restricted

Solution

  1. Step 1: Analyze write condition

    Write is allowed only if request.auth.uid == resource.data.authorId, meaning user must be the author.
  2. Step 2: Apply condition to user not author

    If user is logged in but not the author, condition fails, so write is denied.
  3. Final Answer:

    Write is denied because user is not the author -> Option A
  4. Quick Check:

    Write allowed only for author = A [OK]
Hint: Check if user ID matches author ID for write [OK]
Common Mistakes:
  • Assuming any logged-in user can write
  • Confusing read and write conditions
  • Ignoring resource data in condition
4. Identify the error in this Firebase rule snippet:
match /users/{userId} {
  allow read if request.auth.uid == userId;
  allow write: if request.auth.uid == userId;
}
medium
A. Missing colon after 'allow read'
B. Incorrect variable name 'userId'
C. Missing semicolon after 'allow write' condition
D. Using '==' instead of '=' in conditions

Solution

  1. Step 1: Check syntax for 'allow' statements

    Each allow must have a colon before the condition, e.g., allow read: if ...;
  2. Step 2: Identify missing colon

    The first line misses colon after allow read, causing syntax error.
  3. Final Answer:

    Missing colon after 'allow read' -> Option A
  4. Quick Check:

    Colon required after allow keyword [OK]
Hint: Always put colon after allow before condition [OK]
Common Mistakes:
  • Omitting colon after allow
  • Confusing '=' and '=='
  • Forgetting semicolon at line end
5. You want to write a rule that allows users to read their own profile data but only write if their profile contains a non-empty 'name' field. Which rule snippet correctly enforces this?
hard
A. match /profiles/{userId} { allow read: if request.auth.uid == userId; allow write: if request.resource.data.name != ""; }
B. match /profiles/{userId} { allow read: if request.auth.uid == userId; allow write: if request.auth.uid == userId || request.resource.data.name != ""; }
C. match /profiles/{userId} { allow read: if request.auth.uid == userId; allow write: if request.auth.uid == userId && request.resource.data.name != ""; }
D. match /profiles/{userId} { allow read: if true; allow write: if request.auth.uid == userId && request.resource.data.name == ""; }

Solution

  1. Step 1: Understand read condition

    Users can read only their own profile: request.auth.uid == userId.
  2. Step 2: Understand write condition

    Write allowed only if user owns profile AND 'name' field is not empty: request.auth.uid == userId && request.resource.data.name != "".
  3. Step 3: Check options for correct logic

    match /profiles/{userId} { allow read: if request.auth.uid == userId; allow write: if request.auth.uid == userId && request.resource.data.name != ""; } matches both conditions correctly; others use wrong logic or allow too much.
  4. Final Answer:

    match /profiles/{userId} { allow read: if request.auth.uid == userId; allow write: if request.auth.uid == userId && request.resource.data.name != ""; } -> Option C
  5. Quick Check:

    Use AND for ownership and non-empty name [OK]
Hint: Use AND (&&) to combine ownership and data checks [OK]
Common Mistakes:
  • Using OR (||) instead of AND (&&)
  • Allowing write without ownership check
  • Checking for empty string incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard