How to Setup Firebase Rules with Firebase tools and cli

How to Setup Firebase Rules with Firebase tools and cli

Setting Up Firestore security rules for a mobile or web app via cli, firebase admin & firebase-tools, a guide for founders, hackers and newbie devs

Muhammad Hassaan
Muhammad HassaanMH Labs
7 min read

Firebase gives you an optional 30 days to setup security rules when you create a firestore database. For development, this is great, but you have to setup the security rules before you go in production or 30 days have passed. This guide walks you through deploying firestore security rules using firebase-tools and npx, directly from your project.

The Firebase Console does have its own version history for rules, and it's fine for quick fixes. But if you're serious about your project — whether it's an expo firebase app, a next firebase webapp, or any other setup — managing rules from your codebase is the way to go. You get git history, local testing, and repeatable deploys.

If you are familiar with firebase setup, skip ahead using table of contents.


Step 1: Download your Google Service Account Key

Before anything else, we need to get the google service account json key from firebase. This key allows your machine to authenticate with your Firebase project.

  1. Go to the Firebase Console.
  2. Click on Project Settings (the gear icon ⚙️) in the sidebar.
  3. Select the Service accounts tab at the top.
  4. Under Firebase Admin SDK, click the blue Generate new private key button.
  5. A .json file will download to your computer.

This is the same google service account key you'd use for eas submit, push notifications (FCM V1), or any firebase-admin operations. One key, many uses.

Handling the Key

Rename the downloaded file to google-service-account-key.json.

  • For standard projects: Place it in your project root directory.
  • For monorepos: Place it in your backend or admin directory, wherever your server-side code lives.

[!CAUTION] Never commit this file to GitHub. It contains private keys with full access to your database. Open your .gitignore and add this line immediately:

google-service-account-key.json

Setting the Path in .env

Create or update your .env file and add the path to the key:

bash
FIREBASE_SERVICE_ACCOUNT_PATH=./google-service-account-key.json

This ensures your scripts and tools know exactly where to find the key.


Step 2: Login via CLI

We use npx to run the firebase CLI without installing it globally. It's cleaner and avoids version conflicts across different machines.

Open your terminal in your project root and run:

bash
npx firebase login

This will open your browser. Log in with the same Google account you use for Firebase.

If you have multiple Firebase projects (staging, production), you can manage them with aliases: npx firebase use --add. Name them staging and production, then switch with npx firebase use staging.

Step 3: Initialize Firestore

Now we tell Firebase that we want to manage our security rules locally from this directory.

bash
npx firebase init firestore

Follow the prompts:

  1. Use spacebar to select Firestore: Deploy rules and create indexes and hit Enter.
  2. Choose Use an existing project and select your project from the list.
  3. For file names (firestore.rules and firestore.indexes.json), just hit Enter to accept the defaults.

After this, you will see two new files in your project:

  • firestore.rules — this is where you write your security rules.
  • firebase.json — this tells the CLI where your rules and indexes live.

For a detailed reference on managing and deploying rules, check the official Firebase Rules Deployment Docs.

Step 4: Writing your First Rule

Let's write a basic set of firestore security rules to get started. Open your firestore.rules file and replace its contents with:

javascript
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Default: Lock everything match /{document=**} { allow read, write: if false; } // System data: readable by all, writable only via Admin SDK match /app_config/{configId} { allow read: if true; allow write: if false; } // User data: only the owner can read/write their own document match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } }

We are using rules_version = '2' which is the latest firestore rules version. It supports collection group queries and other improvements over version 1. Always use version 2 for new projects. See Get Started with Security Rules for more on the rules syntax and language.

This example covers two important patterns — public system data and private user data. For a deeper dive into the firestore security rules language, how to handle authenticated users, and third-party auth providers, check out Mastering Firestore Security Rules.

Step 5: Deploy your Rules

Once you're happy with your firestore.rules, push them to the cloud with the firebase deploy rules command:

bash
npx firebase deploy --only firestore:rules

That's it. Your rules are now live on Cloud Firestore.

Pro Tip: Add this to your package.json scripts for easy future deploys:

json
"scripts": { "deploy:rules": "npx firebase deploy --only firestore:rules" }

Now you can just run npm run deploy:rules whenever you update security rules in firebase.


Safety Notes

  • CLI Overwrites Console: When you deploy from CLI, your local file completely overwrites whatever is in the Firebase Console. If you made a quick fix in the UI, pull it into your local file first.
  • Admin SDK Bypasses Rules: firebase-admin and the CLI bypass all security rules. These rules only protect your database from direct client-side access (your app, your users).
  • Test First: Use the Rules Simulator in the Firebase Console to test your logic before deploying to production. Better to catch errors there than in a crash report.

Automation Prompts for your AI Agent (Cursor / Copilot)

If you want to sit back and let an AI agent handle the setup, copy the right prompt into your editor's chat. Make sure you have your google-service-account-key.json ready in your project root.

Option 1: Starting a NEW Firebase project

text
"I want to setup Firestore Security Rules for a brand new project. Reference guide: https://muhammadhassaan.com/blog/how-to-setup-firestore-rules 1. My `google-service-account-key.json` should be in the project root. Add it to `.gitignore` immediately. 2. Create or update `.env` with `FIREBASE_SERVICE_ACCOUNT_PATH=./google-service-account-key.json`. 3. Run `npx firebase login` and wait for me to authenticate. 4. Create a new Firebase project using the CLI, then run `npx firebase init firestore` to initialize rules and indexes. 5. Write a starter `firestore.rules` file with `rules_version = '2'`, a default deny-all rule, a public `app_config` read rule, and a user-scoped `users/{userId}` rule. 6. Add a `deploy:rules` script to `package.json`: `npx firebase deploy --only firestore:rules`. 7. Run a test deploy using `npm run deploy:rules` to verify everything works. Do this automatically. Only wait for my input during authentication and project naming."

Option 2: Using an EXISTING Firebase project

text
"I want to setup Firestore Security Rules for my existing project. My Firebase project ID is: [INSERT_PROJECT_ID_HERE]. Reference guide: https://muhammadhassaan.com/blog/how-to-setup-firestore-rules 1. My `google-service-account-key.json` should be in the project root. Add it to `.gitignore`. 2. Create or update `.env` with `FIREBASE_SERVICE_ACCOUNT_PATH=./google-service-account-key.json`. 3. Run `npx firebase login`, then `npx firebase use [INSERT_PROJECT_ID_HERE]`. 4. Run `npx firebase init firestore` to initialize local rules and indexes. 5. Write a starter `firestore.rules` with `rules_version = '2'`, default deny, public config read, and user-scoped access rules. 6. Add `deploy:rules` script to `package.json`. 7. Run a test deploy to verify. Do this automatically and let me know when the project is ready."

Next Steps

Now that your deployment workflow is ready, learn how to actually write and structure your security rules in Mastering Firestore Security Rules.

If you don't want to use firebase-tools and prefer managing everything through the Admin SDK directly, check out How to Setup Firebase Rules without Firebase tools using firebase-admin.

Insights, Playbooks, Tips & Kits

Want real patterns from my journey building and selling SaaS & apps. DIY playbooks, code-ready starter kits, and the operational moves that let you scale without the overhead. For builders who learn best from firsthand mistakes, real wins & experience.