# How to Use Firebase CLI for Deployment

- Tool: Firebase
- Difficulty: Intermediate
- Time required: 15-20 min
- Compatibility: Firebase CLI v13+, Node.js 18+, all Firebase plans
- Last updated: March 2026

## TL;DR

The Firebase CLI lets you deploy hosting, functions, Firestore rules, and other services from your terminal. Install it with npm install -g firebase-tools, authenticate with firebase login, initialize your project with firebase init, and deploy with firebase deploy. Use the --only flag for selective deployment and .firebaserc for managing multiple project environments like staging and production.

## Deploying with the Firebase CLI

The Firebase CLI is the primary tool for deploying Firebase Hosting, Cloud Functions, Firestore and RTDB rules, and Storage rules from your local development environment. This tutorial walks you through installing the CLI, logging in, initializing your project configuration, deploying individual services, using preview channels for staging, and setting up multiple project aliases for environment management.

## Before you start

- Node.js 18 or later installed on your machine
- A Firebase project created in the Firebase Console
- A web app or Cloud Functions ready to deploy
- Terminal or command-line access

## Step-by-step guide

### 1. Install the Firebase CLI

Install the Firebase CLI globally using npm. This gives you the firebase command in your terminal. After installation, verify it works by checking the version. The CLI is regularly updated with new features and bug fixes, so keep it current. If you previously installed an older version, the same command upgrades it.

```
# Install or update the Firebase CLI
npm install -g firebase-tools

# Verify installation
firebase --version

# Expected output: 13.x.x or later
```

**Expected result:** The firebase command is available in your terminal and shows the current version number.

### 2. Authenticate with Firebase

Run firebase login to authenticate with your Google account. This opens a browser window where you sign in and authorize the CLI to access your Firebase projects. The CLI stores the auth token locally so you only need to log in once per machine. For CI/CD environments where no browser is available, use firebase login:ci to generate a token that can be used with the FIREBASE_TOKEN environment variable.

```
# Interactive login (opens browser)
firebase login

# Verify you're logged in and see available projects
firebase projects:list

# For CI/CD: generate a CI token
firebase login:ci
# Then use: FIREBASE_TOKEN=your-token firebase deploy
```

**Expected result:** You are authenticated and firebase projects:list shows your Firebase projects.

### 3. Initialize Firebase in your project directory

Navigate to your project directory and run firebase init. The CLI walks you through selecting which Firebase features to configure: Hosting, Functions, Firestore Rules, Realtime Database Rules, Storage Rules, and Emulators. For each feature, it creates the necessary configuration files. Choose an existing Firebase project or create a new one. The command creates firebase.json (deployment config) and .firebaserc (project aliases).

```
# Navigate to your project directory
cd your-project

# Initialize Firebase (interactive wizard)
firebase init

# Or initialize specific features only
firebase init hosting
firebase init functions
firebase init firestore
firebase init emulators
```

**Expected result:** Your project directory contains firebase.json and .firebaserc with your selected features configured.

### 4. Configure firebase.json for deployment

The firebase.json file controls what gets deployed and how. For Hosting, it specifies the public directory (where your build output goes), rewrites for SPAs, custom headers, and redirects. For Functions, it points to the functions directory. For Firestore and RTDB, it specifies the rules files. Review and customize this file to match your project structure.

```
{
  "hosting": {
    "public": "dist",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      { "source": "**", "destination": "/index.html" }
    ],
    "headers": [
      {
        "source": "**/*.@(js|css)",
        "headers": [
          { "key": "Cache-Control", "value": "max-age=31536000" }
        ]
      }
    ]
  },
  "functions": {
    "source": "functions",
    "runtime": "nodejs20"
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "database": {
    "rules": "database.rules.json"
  },
  "storage": {
    "rules": "storage.rules"
  }
}
```

**Expected result:** firebase.json is configured with the correct public directory, rewrites, and paths to rules files.

### 5. Deploy all services or select specific ones

Run firebase deploy to deploy all configured services at once, or use the --only flag to deploy specific services. Selective deployment is faster and safer because it only changes what you intend to update. You can deploy multiple specific targets by separating them with commas. Always build your frontend project before deploying Hosting.

```
# Deploy everything
firebase deploy

# Deploy only hosting
npm run build && firebase deploy --only hosting

# Deploy only Cloud Functions
firebase deploy --only functions

# Deploy a specific function
firebase deploy --only functions:myFunction

# Deploy only Firestore rules and indexes
firebase deploy --only firestore

# Deploy multiple targets
firebase deploy --only hosting,functions

# Deploy with a message for version tracking
firebase deploy --only hosting -m "v2.1.0 - Added user profiles"
```

**Expected result:** The selected services are deployed to your Firebase project and the CLI shows the deployment URL.

### 6. Use preview channels for staging

Firebase Hosting preview channels let you deploy to temporary URLs for testing before going to production. Each channel gets a unique URL that expires after 7 days by default. Share these URLs with your team for review. When ready, deploy to production with the standard deploy command.

```
# Deploy to a preview channel
firebase hosting:channel:deploy staging

# Deploy with a custom expiration (30 days)
firebase hosting:channel:deploy staging --expires 30d

# List all active channels
firebase hosting:channel:list

# Delete a preview channel
firebase hosting:channel:delete staging
```

**Expected result:** A temporary preview URL is generated where your team can test the deployment before going to production.

### 7. Set up project aliases for multiple environments

Use .firebaserc to define aliases for different Firebase projects, such as development, staging, and production. Switch between environments with firebase use and deploy to the correct project each time. This prevents accidental deployments to production. Each alias maps to a different Firebase project ID.

```
// .firebaserc
{
  "projects": {
    "default": "my-app-dev",
    "staging": "my-app-staging",
    "production": "my-app-prod"
  }
}

// Switch between environments
// firebase use staging
// firebase deploy --only hosting

// Or deploy to a specific alias without switching
// firebase deploy --only hosting --project production
```

**Expected result:** You can switch between project environments and deploy to the correct Firebase project using aliases.

## Complete code example

File: `deploy.sh`

```bash
#!/bin/bash
# Firebase deployment script with environment support
# Usage: ./deploy.sh [environment] [service]
# Examples:
#   ./deploy.sh production hosting
#   ./deploy.sh staging functions
#   ./deploy.sh production all

ENV=${1:-"staging"}
SERVICE=${2:-"all"}

echo "Deploying to: $ENV"
echo "Service: $SERVICE"

# Validate environment
if [[ "$ENV" != "staging" && "$ENV" != "production" ]]; then
  echo "Error: Environment must be 'staging' or 'production'"
  exit 1
fi

# Production safety check
if [[ "$ENV" == "production" ]]; then
  read -p "Are you sure you want to deploy to PRODUCTION? (y/n) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Deployment cancelled."
    exit 0
  fi
fi

# Build frontend if deploying hosting
if [[ "$SERVICE" == "hosting" || "$SERVICE" == "all" ]]; then
  echo "Building frontend..."
  npm run build
  if [ $? -ne 0 ]; then
    echo "Build failed. Aborting deployment."
    exit 1
  fi
fi

# Deploy
if [[ "$SERVICE" == "all" ]]; then
  firebase deploy --project "$ENV"
else
  firebase deploy --only "$SERVICE" --project "$ENV"
fi

if [ $? -eq 0 ]; then
  echo "Deployment to $ENV ($SERVICE) complete!"
else
  echo "Deployment failed."
  exit 1
fi
```

## Common mistakes

- **Deploying hosting without running the build command first, resulting in stale or missing files** — undefined Fix: Always run your build command (npm run build) before firebase deploy --only hosting. Add it to your deployment script to automate this.
- **Deploying all services when only one changed, which is slow and risky** — undefined Fix: Use firebase deploy --only hosting or firebase deploy --only functions to deploy only what changed. This is faster and reduces the risk of unintended changes.
- **Deploying to production instead of staging because the wrong project alias is active** — undefined Fix: Always use the --project flag explicitly in CI/CD: firebase deploy --project my-app-staging. Check the active project with firebase use before deploying interactively.
- **Running firebase init in a directory that already has a firebase.json, accidentally overwriting configuration** — undefined Fix: The CLI warns before overwriting existing files, but always back up your firebase.json before running firebase init again. Use firebase init [feature] to add a single feature without touching existing config.

## Best practices

- Use the --only flag to deploy specific services instead of deploying everything at once
- Always build your frontend before deploying hosting: npm run build && firebase deploy --only hosting
- Set up project aliases in .firebaserc for development, staging, and production environments
- Use preview channels for staging deployments with firebase hosting:channel:deploy
- Add a deployment script that includes build steps, environment selection, and confirmation prompts
- Keep the Firebase CLI updated with npm install -g firebase-tools for the latest features and fixes
- Use firebase login:ci and FIREBASE_TOKEN for automated CI/CD deployments
- Deploy Cloud Functions in batches of 10 or fewer to avoid API rate limits

## Frequently asked questions

### Do I need to install the Firebase CLI globally?

No. You can use npx firebase-tools to run CLI commands without a global install. However, global installation (npm install -g firebase-tools) is more convenient for frequent use and avoids re-downloading on every command.

### How do I deploy to a different Firebase project?

Use the --project flag: firebase deploy --project my-other-project. Or set up aliases in .firebaserc and switch with firebase use my-alias. This is essential for managing staging and production environments.

### Can I deploy from a CI/CD pipeline?

Yes. Generate a CI token with firebase login:ci and set it as the FIREBASE_TOKEN environment variable in your CI/CD system. Then run firebase deploy --project your-project in your pipeline. Most CI systems like GitHub Actions, CircleCI, and GitLab CI have Firebase deployment templates.

### What does firebase deploy --only functions:myFunction do?

It deploys only the specific function named myFunction instead of all functions. This is faster and safer for making changes to a single function in production without affecting others.

### How long does a hosting deployment take?

Typically 30 seconds to 2 minutes depending on the size of your build output and network speed. The Firebase CDN propagates changes globally within a few minutes after deployment completes.

### What happens if a deployment fails halfway through?

Firebase deploys services atomically. If hosting deployment fails, your previous version remains live. If function deployment fails, already-deployed functions from that batch may have been updated, but other batches remain unchanged. Always deploy functions selectively to minimize risk.

### Can RapidDev help set up a CI/CD pipeline for Firebase deployment?

Yes. RapidDev can configure automated deployment pipelines with GitHub Actions, staging preview channels, production approval gates, and rollback strategies for your Firebase project.

---

Source: https://www.rapidevelopers.com/firebase-tutorial/how-to-use-firebase-cli-for-deployment
© RapidDev — https://www.rapidevelopers.com/firebase-tutorial/how-to-use-firebase-cli-for-deployment
