How to Setup Firebase Rules without Firebase tools using firebase-admin

Deploy Firestore Rules With Firebase Admin SDK (No CLI)

Deploy Firestore security rules using the Node.js Firebase Admin SDK without firebase-tools. Includes TypeScript deployment script and ruleset limits.

Muhammad Hassaan
Muhammad HassaanMH Labs
•5 min read

Method 2 for deploying Firestore security rules. You do not need firebase-tools installed for this approach: you deploy directly from a Node.js TypeScript script using the Firebase Admin SDK, which is ideal for projects with an admin/ directory or custom backend scripts.

Want an AI coding agent to handle this setup for you? Copy the ready-to-use prompt from Firebase & Firestore AI Prompts: Deploy Firestore Rules With Firebase Admin SDK into Cursor, Claude Code, or Copilot and let your agent follow this exact process.

In Method 1: Firebase CLI, we used npx firebase to deploy rules. Some monorepos and backend services avoid firebase-tools altogether and manage everything through firebase-admin. If that fits your stack, this guide is for you.


Step 1: Get Your Google Service Account Key

Just like Method 1, you need a Google Service Account JSON key to authenticate your script.

  1. Go to the Firebase Console.
  2. Click Project Settings (the gear icon) and open the Service accounts tab.
  3. Under Firebase Admin SDK, click Generate new private key.
  4. Download the .json file.

This is the same Service Account key used for EAS submit, push notifications, and other admin tasks. If you already have it, reuse it.

Place the Key and Configure .env (Local vs. GitHub Actions and Servers)

For local development, move the downloaded file into your admin/ directory, rename it to google-service-keys.json, and immediately add google-service-keys.json to .gitignore. Then set the path in admin/.env:

bash
FIREBASE_SERVICE_ACCOUNT_PATH=./google-service-keys.json

If your key sits in the project root instead, use a relative path such as ../google-service-keys.json.

For GitHub Actions and server environments (not Expo), avoid storing the raw JSON string directly in a secret or .env variable. A raw multiline JSON string might work in some setups or fail due to \n newline escaping inside private_key, shell quoting, or multiline secret masking quirks. Instead, base64-encode the JSON string into a single line so it stays intact across CI runners and servers:

bash
# Linux (single-line output) base64 -w 0 google-service-keys.json # macOS base64 -i google-service-keys.json | tr -d '\n'

Store that single-line string in a GitHub Actions secret or server environment variable named FIREBASE_SERVICE_ACCOUNT_BASE64. For background on why multiline JSON secrets cause issues in CI and why Base64 encoding is recommended, see the GitHub Actions Secrets documentation, GitHub Community multiline secrets guidance, and GitHub Actions Runner issue #1942.


Step 2: Install Dependencies and Initialize firebase-admin

Navigate to your admin/ directory and install firebase-admin:

bash
cd admin npm install firebase-admin

Make sure you have an Admin SDK initializer at admin/lib/firebase.ts that supports FIREBASE_SERVICE_ACCOUNT_BASE64 in CI/server environments and falls back to FIREBASE_SERVICE_ACCOUNT_PATH locally:

typescript
import admin from 'firebase-admin'; import fs from 'fs'; if (!admin.apps.length) { const base64Key = process.env.FIREBASE_SERVICE_ACCOUNT_BASE64; const serviceAccount = base64Key ? JSON.parse(Buffer.from(base64Key, 'base64').toString('utf8')) : JSON.parse( fs.readFileSync( process.env.FIREBASE_SERVICE_ACCOUNT_PATH || './google-service-keys.json', 'utf8' ) ); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), }); } export default admin;

Step 3: Write the Deployment Script

Create admin/scripts/deploy-rules.ts. This script reads your local firestore.rules file and pushes it to your live project using admin.securityRules().

typescript
import admin from '../lib/firebase'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); async function deployRules() { try { console.log('Reading Firestore rules...'); const rulesPath = path.join(__dirname, '../firebase/firestore.rules'); if (!fs.existsSync(rulesPath)) { throw new Error(`Rules file not found at ${rulesPath}`); } const rulesContent = fs.readFileSync(rulesPath, 'utf8'); console.log('Deploying Firestore rules to project...'); const securityRules = admin.securityRules(); const ruleset = await securityRules.releaseFirestoreRulesetFromSource(rulesContent); console.log(`Successfully deployed ruleset: ${ruleset.name}`); console.log('Rules are now active on Cloud Firestore.'); } catch (error: any) { console.error('Error deploying rules:', error.message || error); process.exit(1); } } deployRules();

releaseFirestoreRulesetFromSource validates the rules string, creates a new ruleset on Google's servers, and releases it to Firestore in one call. See the Firebase Rules Management docs for API details.


Step 4: Write Your Rules File

Create admin/firebase/firestore.rules with your security logic:

javascript
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Default: deny everything match /{document=**} { allow read, write: if false; } // System data: publicly readable match /app_config/{configId} { allow read: if true; allow write: if false; } // User data: only the owner match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } }

For deeper syntax patterns, validation, and third-party auth strategies, check out Mastering Firestore Security Rules.


Step 5: Add a Package Script and Watch Two Operational Gotchas

Update admin/package.json:

json
"scripts": { "deploy:rules": "ts-node scripts/deploy-rules.ts" }

Deploy your rules with:

bash
npm run deploy:rules

Keep two Firebase operational limits in mind when deploying programmatically:

  • 2,500-ruleset cap per project: Every releaseFirestoreRulesetFromSource() call creates a new ruleset version. If you deploy frequently in CI, periodically list and delete old rulesets so you do not hit Firebase's 2,500-ruleset limit.
  • Brief propagation delay: Newly released rulesets can take up to a few minutes to propagate across all Cloud Firestore edge nodes.

Comparison diagram of Firebase CLI deployment versus programmatic Admin SDK deployment with 2500 ruleset cap


When to Use Method 1 vs. Method 2

Method 1 (Firebase CLI)Method 2 (Admin SDK)
Best forProjects already using firebase-toolsCustom admin tools, monorepos
Requiresnpx firebase or global installfirebase-admin npm package
Deploy commandnpx firebase deploy --only firestore:rulesnpm run deploy:rules (custom script)
GuideFirebase tools and CLIThis article

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.