New Release : PWA VS Code Extension X

Assigning Roles To Users With Cloud Firestore Security Rules In Firebase

This dev doc guide is best suited for anyone who has been using firebase cloud firestore for a while i.e intermediate to expert level of experience.

If you are a beginner or would want to try out the magic with cloud firestore for web, get started in this codelab here 😎

Adding a user in the "users" collection

You may have for example, a cloud function that adds a user into the users collection on first time authentication as shown below;

Tip ; remember to split up your cloud functions // it's safer and good practice to do that.

    // create a users' doc on first authentication
    const addUser = (userData, context) => {
       return db.collection('users').doc(userData.uid).set({
         displayName: userData.displayName,
         isAdmin : false
    module.exports = {
    authOnCreate: functions.auth.user().onCreate(addUser),

The "users" collection created on deploying this function would be as in the image below

cloud firestore
Users Collection

​Allowing Write permission to Admins only

You check the users collection in firebase cloud firestore database if the user's assigned role evaluates to true, i.e isAdmin:true ;

    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read;
          allow write : if get(/databases/$(database)/documents/users/$(request.auth.uid))
          .data.isAdmin == true;

This is a "low-level" showcase on how to implement role-based data access in firebase cloud firestore, assuming there's no an admin ui or panel.

Learn more about firebase cloud firestore security rules in this awesome firebase doc

Note: When you deploy security rules using the Firebase CLI, the rules defined in your project directory overwrite any existing rules in the Firebase console.

Got any question? You wanna have a chat? Hit my inbox on twitter asap 😉