/firebase-tutorials

How to test Firestore rules locally?

Follow this step-by-step guide to test Firestore security rules locally. Set up Firebase CLI, run the emulator, write tests, and ensure secure Firestore access.

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 rules locally?

 

Step 1: Set Up Your Firebase Project Locally

 

To start testing Firestore rules locally, ensure you have the Firebase CLI installed. If not, install it using npm:

npm install -g firebase-tools

Log in to your Firebase account:

firebase login

Initialize your Firebase project in the local directory:

firebase init

During initialization, choose Firestore and Functions (if needed) and configure them.

 

Step 2: Install Firebase Emulator

 

In the root of your project directory, ensure you have a package.json file. If not, create one using:

npm init -y

Install the Firebase Emulator Suite:

npm install --save-dev firebase-tools

 

Step 3: Configure Firestore Emulator

 

Modify the firebase.json file to include Firestore in the emulators section:


{
  "emulators": {
    "firestore": {
      "port": 8080
    }
  }
}

 

Step 4: Define Your Firestore Security Rules

 

Create a file named firestore.rules or use the one generated during Firebase initialization. Define your security rules in this file, such as:


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

 

Step 5: Write Your Tests

 

Create a test file, for instance, firestore.test.js. To run tests against your Firestore rules, use a testing framework like Mocha or Jest. Install the dependencies in your project:

npm install --save-dev mocha chai @firebase/testing

Write the test cases in your test file:


const firebase = require("@firebase/testing");
const MY_PROJECT_ID = "your-project-id";

describe("Firestore security rules", () => {
  it("should allow a user to read their own document", async () => {
    const db = firebase.initializeTestApp({
      projectId: MY_PROJECT_ID,
      auth: { uid: "user\_abc" }
    }).firestore();

    const testDoc = db.collection("users").doc("user\_abc");
    await firebase.assertSucceeds(testDoc.get());
  });

  it("should deny a user to read another user's document", async () => {
    const db = firebase.initializeTestApp({
      projectId: MY_PROJECT_ID,
      auth: { uid: "user\_xyz" }
    }).firestore();

    const testDoc = db.collection("users").doc("user\_abc");
    await firebase.assertFails(testDoc.get());
  });
});

 

Step 6: Run the Firebase Emulator and Tests

 

Start the emulators:

firebase emulators:start

In a separate terminal, run your tests using Mocha (or another testing framework of your choice):

npx mocha firestore.test.js

Ensure that all your test cases pass, which signifies that your Firestore rules are working as expected.

 

Step 7: Tear Down After Tests

 

Optionally, clean up the Firebase Emulator environment by shutting down the emulator processes. You can do this by stopping the terminal process running the emulators.

This procedure ensures that you can locally test Firestore security rules reliably before deploying them to production.

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