0
0
Firebasecloud~30 mins

Custom functions in rules in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Functions in Firebase Security Rules
📖 Scenario: You are building a simple Firebase app where users can read and write their own profile data. To keep the data safe, you want to use Firebase security rules with custom functions to check if a user is allowed to read or write their own data.
🎯 Goal: Build Firebase security rules that use a custom function isOwner() to check if the user is accessing their own profile document. The rules should allow read and write only if the user is the owner.
📋 What You'll Learn
Create a custom function called isOwner() that checks if request.auth.uid matches the document ID
Use the isOwner() function in the allow read, write rules
Apply the rules to the profiles/{userId} document path
Ensure the rules deny access if the user is not authenticated or not the owner
💡 Why This Matters
🌍 Real World
Firebase security rules protect your app's data by controlling who can read or write it. Custom functions help keep rules clean and reusable.
💼 Career
Understanding Firebase security rules and custom functions is essential for backend and full-stack developers working with Firebase to build secure apps.
Progress0 / 4 steps
1
Create the base rules structure
Write the Firebase security rules starting with rules_version = '2'; and service cloud.firestore block. Inside, create a match block for /databases/{database}/documents/profiles/{userId}.
Firebase
Need a hint?

Start by defining the rules version and the Firestore service. Then add a match block for the profiles collection documents.

2
Add the custom function isOwner()
Inside the match block, define a custom function called isOwner() that returns request.auth != null && request.auth.uid == userId.
Firebase
Need a hint?

Define a function inside the match block that checks if the user is authenticated and their UID matches the document ID.

3
Use isOwner() in read and write rules
Add allow read, write: if isOwner(); inside the match block to allow access only if the user is the owner.
Firebase
Need a hint?

Use the custom function in the allow statement to restrict access.

4
Complete the rules with proper closing braces
Ensure the rules end with the correct closing braces for the match and service blocks.
Firebase
Need a hint?

Make sure all blocks are properly closed with braces.