/firebase-tutorials

How to test Firestore security rules?

Learn how to test Firestore security rules step-by-step. Set up Firebase, write rules, use Firebase CLI and testing tools, and run secure test cases for your data.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to test Firestore security rules?

 

Step 1: Set Up Your Firebase Project

 

Before you begin testing Firestore security rules, ensure you have an existing Firebase project. If not, create one via the Firebase Console.

  1. Create a Firebase project:

    Head to Firebase Console, click on "Add project", and follow the instructions to create a new project.

  2. Add Firestore to your project:

    Once your project is created, navigate to Firestore under the "Build" section, and click "Create Database". Choose the test mode (be mindful that this allows open access to your database initially).

 

Step 2: Write Firestore Security Rules

 

Develop rules to govern access to your Firestore database.

Example Rule:

This example allows only authenticated users to read and write their own user data, assuming documents are stored under users/{userId}.


service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Write these rules in the Firestore Rules tab in the Firebase Console.

 

Step 3: Install Firebase CLI

 

To test security rules locally, set up Firebase CLI.

Installation Command:

Use npm to install Firebase CLI globally:


npm install -g firebase-tools

After installation, verify using:


firebase --version

 

Step 4: Initialize Firebase in Your Project

 

Prepare your local project to use Firebase features, including Firestore.

  1. Initialize Firebase in the project directory:

    
    firebase init
    

 

Step 5: Import Firebase Testing Library

 

To test Firestore rules, utilize the Firebase testing library for Node.js.

Add the library to your testing environment:


npm install --save-dev @firebase/rules-unit-testing

 

Step 6: Write Test Cases for Firestore Security Rules

 

Develop test cases using the Firebase Test SDK that test your Firestore rules.

Example Test Code:


const { initializeTestEnvironment, assertFails, assertSucceeds } = require('@firebase/rules-unit-testing');
const { getFirestore, doc, setDoc } = require('firebase/firestore');

const projectId = "my-test-project";

let testEnv;

beforeAll(async () => {
  testEnv = await initializeTestEnvironment({
    projectId: projectId,
    firestore: {
      rules: 'firestore.rules', // Assumed location of your rules file.
    }
  });
});

afterAll(async () => {
  await testEnv.cleanup();
});

describe('Firestore security rules', () => {
  it('allows authenticated user to write to their own document', async () => {
    const auth = { uid: 'user\_abc' };
    const firestore = testEnv.authenticatedContext('user\_abc').firestore();

    const testDoc = doc(firestore, 'users/user\_abc');
    await assertSucceeds(setDoc(testDoc, { foo: 'bar' }));
  });

  it('denies write to other user document', async () => {
    const firestore = testEnv.authenticatedContext('user\_abc').firestore();

    const testDoc = doc(firestore, 'users/other\_user');
    await assertFails(setDoc(testDoc, { foo: 'bar' }));
  });
});

 

Step 7: Run Your Tests

 

Test your Firestore security rules via a Node.js test runner like Jest or Mocha.

Example Command with Jest:


npm run test

Ensure you have configured Jest or Mocha in your project to recognize Firebase testing properly.

By following these steps, you can effectively test your Firebase Firestore security rules, ensuring they properly enforce data access according to your specifications.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022