Справочник по интерфейсу командной строки Firebase

Интерфейс командной строки Firebase ( GitHub ) предоставляет множество инструментов для управления, просмотра и развертывания проектов Firebase.

Перед использованием Firebase CLI необходимо настроить проект Firebase .

Настройте или обновите интерфейс командной строки.

Установите Firebase CLI.

Вы можете установить Firebase CLI, используя способ, соответствующий вашей операционной системе, уровню опыта и/или сценарию использования. Независимо от способа установки CLI, вы получите доступ к тем же функциям и команде firebase .

Windows macOS Linux

Windows

Установить Firebase CLI для Windows можно одним из следующих способов:

Вариант Описание Рекомендуется для...
автономный бинарный Загрузите автономный исполняемый файл для CLI. Затем вы сможете получить доступ к исполняемому файлу, чтобы открыть оболочку, в которой можно выполнить команду firebase . Новые разработчики

Разработчики, не использующие Node.js или незнакомые с ним.
npm Используйте npm (менеджер пакетов Node) для установки CLI и включения глобально доступной команды firebase . Разработчики, использующие Node.js

автономный бинарный

Чтобы загрузить и запустить исполняемый файл Firebase CLI, выполните следующие действия:

  1. Загрузите исполняемый файл Firebase CLI для Windows .

  2. Получите доступ к исполняемому файлу, чтобы открыть оболочку, в которой вы сможете выполнить команду firebase .

  3. Продолжайте входить в систему и тестируйте интерфейс командной строки .

npm

Чтобы установить Firebase CLI с помощью npm (менеджера пакетов Node), выполните следующие действия:

  1. Установите Node.js с помощью nvm-windows (менеджера версий Node). Установка Node.js автоматически устанавливает инструменты команды npm .

  2. Установите Firebase CLI через npm , выполнив следующую команду:

    npm install -g firebase-tools

    Эта команда активирует глобально доступную команду firebase .

  3. Продолжайте входить в систему и тестируйте интерфейс командной строки .

macOS или Linux

Установить Firebase CLI для macOS или Linux можно одним из следующих способов:

Вариант Описание Рекомендуется для...
скрипт автоматической установки Выполните одну команду, которая автоматически определит вашу операционную систему, загрузит последнюю версию CLI, а затем активирует глобально доступную команду firebase . Новые разработчики

Разработчики, не использующие Node.js или незнакомые с ним.

Автоматизированное развертывание в среде CI/CD
автономный бинарный Загрузите автономный исполняемый файл для интерфейса командной строки. Затем вы можете настроить и запустить исполняемый файл в соответствии с вашими рабочими процессами. Полностью настраиваемые рабочие процессы с помощью интерфейса командной строки.
npm Используйте npm (менеджер пакетов Node) для установки CLI и включения глобально доступной команды firebase . Разработчики, использующие Node.js

скрипт автоматической установки

Для установки Firebase CLI с помощью скрипта автоматической установки выполните следующие действия:

  1. Выполните следующую команду cURL:

    curl -sL https://firebase.tools | bash

    Этот скрипт автоматически определяет вашу операционную систему, загружает последнюю версию Firebase CLI, а затем активирует глобально доступную команду firebase .

  2. Продолжайте входить в систему и тестируйте интерфейс командной строки .

Дополнительные примеры и подробности о скрипте автоматической установки см. в исходном коде скрипта по адресу firebase.tools .

автономный бинарный

Чтобы загрузить и запустить исполняемый файл Firebase CLI, предназначенный для вашей операционной системы, выполните следующие действия:

  1. Загрузите исполняемый файл Firebase CLI для вашей ОС: macOS | Linux

  2. (Необязательно) Настройте глобально доступную команду firebase .

    1. Сделайте исполняемый файл исполняемым, выполнив команду chmod +x ./firebase_tools .`.
    2. Добавьте путь к исполняемому файлу в переменную PATH.
  3. Продолжайте входить в систему и тестируйте интерфейс командной строки .

npm

Чтобы установить Firebase CLI с помощью npm (менеджера пакетов Node), выполните следующие действия:

  1. Установите Node.js с помощью nvm (менеджера версий Node).
    Установка Node.js автоматически устанавливает инструменты команды npm .

  2. Установите Firebase CLI через npm , выполнив следующую команду:

    npm install -g firebase-tools

    Эта команда активирует глобально доступную команду firebase .

  3. Продолжайте входить в систему и тестируйте интерфейс командной строки .

Войдите в систему и протестируйте Firebase CLI.

После установки CLI необходимо пройти аутентификацию. Затем вы можете подтвердить аутентификацию, перечислив свои проекты Firebase.

  1. Войдите в Firebase, используя свою учетную запись Google, выполнив следующую команду:

    firebase login

    Эта команда подключает ваш локальный компьютер к Firebase и предоставляет вам доступ к вашим проектам Firebase.

  2. Проверьте правильность установки CLI и его доступ к вашей учетной записи, выведя список ваших проектов Firebase. Выполните следующую команду:

    firebase projects:list

    Отображаемый список должен совпадать со списком проектов Firebase, отображаемым в консоли Firebase .

Обновите CLI до последней версии.

Как правило, рекомендуется использовать самую актуальную версию Firebase CLI.

Способ обновления версии CLI зависит от вашей операционной системы и способа установки CLI.

Windows

  • Автономный исполняемый файл : Загрузите новую версию , а затем замените ею существующую в вашей системе.
  • npm : Выполните команду npm install -g firebase-tools

macOS

  • скрипт автоматической установки : Запустите curl -sL https://firebase.tools | upgrade=true bash

  • Автономный исполняемый файл : Загрузите новую версию , а затем замените ею существующую в вашей системе.

  • npm : Выполните команду npm install -g firebase-tools

Linux

  • скрипт автоматической установки : Запустите curl -sL https://firebase.tools | upgrade=true bash

  • Автономный исполняемый файл : Загрузите новую версию , а затем замените ею существующую в вашей системе.

  • npm : Выполните команду npm install -g firebase-tools

Удалите Firebase CLI.

Способ удаления CLI зависит от вашей операционной системы и способа установки CLI.

Windows

  • Автономный исполняемый файл : Удалите загруженный вами исполняемый файл firebase.exe .
  • npm : Выполните команду npm uninstall -g firebase-tools

macOS

  • скрипт автоматической установки : Запустите curl -sL https://firebase.tools | uninstall=true bash

  • Автономный исполняемый файл : Удалите загруженный вами исполняемый файл firebase . Если вы добавили его местоположение в переменную среды PATH , обязательно удалите его.

  • npm : Выполните команду npm uninstall -g firebase-tools

Linux

  • скрипт автоматической установки : Запустите curl -sL https://firebase.tools | uninstall=true bash

  • Автономный исполняемый файл : Удалите загруженный вами исполняемый файл firebase . Если вы добавили его местоположение в переменную среды PATH , обязательно удалите его.

  • npm : Выполните команду npm uninstall -g firebase-tools

Используйте интерфейс командной строки с системами непрерывной интеграции.

Мы рекомендуем использовать учетные данные приложения по умолчанию при работе с CLI в системах CI для аутентификации.

(Рекомендуется) Использовать учетные данные приложения по умолчанию.

Интерфейс командной строки Firebase обнаружит и будет использовать учетные данные приложения по умолчанию, если они заданы. Самый простой способ аутентификации CLI в CI и других средах без графического интерфейса — это настройка учетных данных приложения по умолчанию .

(Устаревшая версия) Используйте FIREBASE_TOKEN

В качестве альтернативы можно использовать аутентификацию с помощью FIREBASE_TOKEN . Этот способ менее безопасен, чем использование учетных данных приложения по умолчанию, и больше не рекомендуется.

  1. На компьютере с установленным браузером установите Firebase CLI .

  2. Чтобы начать процесс входа в систему, выполните следующую команду:

    firebase login:ci
  3. Перейдите по указанной ссылке, затем войдите в систему, используя учетную запись Google.

  4. Вывести новый токен обновления . Текущая сессия CLI останется без изменений.

  5. Сохраните выходной токен безопасным, но доступным способом в вашей системе CI.

  6. Используйте этот токен при выполнении команд firebase . Вы можете использовать один из следующих двух вариантов:

    • Вариант 1: Сохраните токен в качестве переменной среды FIREBASE_TOKEN . Ваша система автоматически будет использовать этот токен.

    • Вариант 2: Запускайте все команды firebase с флагом --token TOKEN в вашей системе CI.
      Порядок приоритета загрузки токенов следующий: флаг, переменная окружения, желаемый проект Firebase.

Инициализация проекта Firebase

Многие распространенные задачи, выполняемые с помощью CLI, например, развертывание в проекте Firebase, требуют наличия каталога проекта . Каталог проекта создается с помощью команды firebase init . Обычно каталог проекта совпадает с корневым каталогом вашей системы контроля версий, и после выполнения firebase init в этом каталоге находится конфигурационный файл firebase.json .

Для инициализации нового проекта Firebase выполните следующую команду из каталога вашего приложения:

firebase init

Команда firebase init шаг за шагом настраивает каталог проекта и некоторые продукты Firebase. Во время инициализации проекта Firebase CLI запрашивает выполнение следующих задач:

  • Выберите проект Firebase по умолчанию.

    На этом этапе текущая директория проекта связывается с проектом Firebase, чтобы команды, специфичные для проекта (например, firebase deploy ), выполнялись для соответствующего проекта Firebase.

    Также можно связать несколько проектов Firebase (например, тестовый проект и производственный проект) с одним и тем же каталогом проекта.

  • Выберите продукты Firebase для настройки в вашем проекте Firebase.

    На этом шаге вам будет предложено настроить параметры файлов для выбранных продуктов или функций. Для получения более подробной информации об этих параметрах обратитесь к документации конкретного продукта (например, Hosting или Authentication »). Обратите внимание, что вы всегда можете запустить firebase init позже, чтобы настроить другие продукты Firebase.

По завершении инициализации Firebase автоматически создаёт следующие два файла в корневом каталоге вашего локального приложения:

  • Конфигурационный файл firebase.json , содержащий список параметров вашего проекта.

  • Файл .firebaserc , в котором хранятся псевдонимы вашего проекта.

Файл firebase.json

Команда firebase init создает конфигурационный файл firebase.json в корневом каталоге вашего проекта.

Файл firebase.json необходим для развертывания ресурсов с помощью Firebase CLI , поскольку он определяет, какие файлы и настройки из каталога вашего проекта будут развернуты в вашем проекте Firebase (например, настройки Hosting , конфигурации поставщика Authentication , правила безопасности и конфигурация Cloud Functions ). Поскольку некоторые настройки могут быть определены как в каталоге вашего проекта, так и в консоли Firebase , убедитесь, что вы разрешили все потенциальные конфликты развертывания .

Большинство параметров Firebase Hosting можно настроить непосредственно в файле firebase.json . Однако для других сервисов Firebase, которые можно развернуть с помощью Firebase CLI , команда firebase init создает специальные файлы, где можно определить настройки для этих сервисов, например, файл index.js для Cloud Functions . Вы также можете настроить хуки predeploy или postdeploy в файле firebase.json .

Приведенный ниже файл firebase.json представляет собой подробный пример, демонстрирующий параметры конфигурации для множества сервисов Firebase. Он также демонстрирует такие функции, как многобазовые Cloud Functions , Local Emulator Suite и шаблон Remote Config . Обратите внимание, что файл firebase.json для любого проекта будет содержать только конфигурации для сервисов Firebase, настроенных для этого конкретного проекта (например, только Firebase Hosting и Cloud Functions ). Добавление ключа $schema включает проверку и автозавершение кода во многих редакторах кода.

    {
      "$schema": "https://raw.githubusercontent.com/firebase/firebase-tools/master/schema/firebase-config.json",
      "hosting": {
        "public": "public",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "cleanUrls": true,
        "trailingSlash": false
      },
      "apphosting": {
        "backendId": "my-app",
        "rootDir": "backend",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ]
      },
      "firestore": {
        "rules": "firestore.rules",
        "indexes": "firestore.indexes.json"
      },
      "storage": {
        "rules": "storage.rules"
      },
      "database": {
        "rules": "database.rules.json"
      },
      "dataconnect": {
        "source": "dataconnect",
        "location": "us-central1"
      },
      "functions": [
        {
          "source": "functions",
          "codebase": "default",
          "ignore": [
            "**/.*",
            "**/node_modules/**"
          ],
          "predeploy": [
            "npm --prefix \"$RESOURCE_DIR\" run lint",
            "npm --prefix \"$RESOURCE_DIR\" run build"
          ]
        }
      ],
      "emulators": {
        "auth": {
          "port": 9099
        },
        "functions": {
          "port": 5001
        },
        "firestore": {
          "port": 8080
        },
        "hosting": {
          "port": 5000
        },
        "storage": {
          "port": 9199
        },
        "ui": {
          "enabled": true,
          "port": 4000
        },
        "singleProjectMode": true
      },
      "extensions": {
        "my-storage-resizer": "firebase/storage-resize-images@^0.1.0"
      },
      "auth": {
        "providers": {
          "anonymous": true,
          "emailPassword": true,
          "googleSignIn": {
            "oAuthBrandDisplayName": "My App",
            "supportEmail": "support@myapp.com"
          }
        }
      },
      "remoteconfig": {
        "template": "remoteconfig.template.json"
      }
    }

Хотя по умолчанию используется файл firebase.json , вы можете передать флаг --config PATH , чтобы указать альтернативный конфигурационный файл.

Настройка для нескольких баз данных Cloud Firestore

При выполнении firebase init ваш файл firebase.json будет содержать единственный ключ firestore , соответствующий базе данных по умолчанию вашего проекта, как показано в предыдущем примере.

Если ваш проект содержит несколько баз данных Cloud Firestore , отредактируйте файл firebase.json , чтобы связать разные Cloud Firestore Security Rules и исходные файлы индексов баз данных с каждой базой данных. Измените файл, добавив в него массив JSON с одной записью для каждой базы данных.

      "firestore": [
        {
          "database": "(default)",
          "rules": "firestore.default.rules",
          "indexes": "firestore.default.indexes.json"
        },
        {
          "database": "ecommerce",
          "rules": "firestore.ecommerce.rules",
          "indexes": "firestore.ecommerce.indexes.json"
        }
      ],

Файлы Cloud Functions , которые следует игнорировать при развертывании.

Во время развертывания функции CLI автоматически указывает список файлов в каталоге functions , которые следует игнорировать. Это предотвращает развертывание в бэкэнде лишних файлов, которые могут увеличить размер данных развертывания.

Список файлов, игнорируемых по умолчанию, представлен в формате JSON:

"ignore": [
  ".git",
  ".runtimeconfig.json",
  "firebase-debug.log",
  "firebase-debug.*.log",
  "node_modules"
]

Если вы добавляете собственные значения для параметра ignore в firebase.json , убедитесь, что вы сохраняете (или добавляете, если он отсутствует) список файлов, показанный в предыдущем списке.

Управление псевдонимами проекта

Вы можете связать несколько проектов Firebase с одним и тем же каталогом проекта. Например, вы можете использовать один проект Firebase для тестовой среды, а другой — для производственной. Используя разные среды проекта, вы можете проверять изменения перед развертыванием в производственной среде. Команда firebase use позволяет переключаться между псевдонимами, а также создавать новые псевдонимы.

Добавить псевдоним проекта

При выборе проекта Firebase во время инициализации проекта ему автоматически присваивается псевдоним default . Однако, чтобы команды, специфичные для проекта, могли выполняться в другом проекте Firebase, но при этом использовался тот же каталог проекта, выполните следующую команду из каталога вашего проекта:

firebase use --add

Эта команда предложит вам выбрать другой проект Firebase и назначить ему псевдоним. Назначения псевдонимов записываются в файл .firebaserc , расположенный в каталоге вашего проекта.

Используйте псевдонимы проектов

Чтобы использовать назначенные псевдонимы проектов Firebase, выполните любую из следующих команд из каталога вашего проекта.

Командование Описание
firebase use Просмотрите список определенных псевдонимов для каталога вашего проекта.
firebase use \
PROJECT_ID|ALIAS
Направляет все команды на выполнение в указанном проекте Firebase.
Интерфейс командной строки использует этот проект в качестве «активного проекта».
firebase use --clear Сбрасывает активный проект.

Перед выполнением других команд CLI запустите команду `run firebase use PROJECT_ID|ALIAS , чтобы установить новый активный проект.

firebase use \
--unalias PROJECT_ALIAS
Удаляет псевдоним из каталога вашего проекта.

Вы можете переопределить используемый в качестве активного проекта, передав флаг --project в любой команде CLI. Например: вы можете настроить CLI для работы с проектом Firebase, которому вы присвоили псевдоним staging . Если вы хотите выполнить одну команду для проекта Firebase, которому вы присвоили псевдоним prod , то вы можете выполнить, например, firebase deploy --project=prod .

Системы контроля версий и псевдонимы проектов

Как правило, файл .firebaserc следует добавлять в систему контроля версий, чтобы ваша команда могла совместно использовать псевдонимы проекта. Однако для проектов с открытым исходным кодом или стартовых шаблонов обычно не следует добавлять файл .firebaserc в систему контроля версий.

Если у вас есть проект для разработки, предназначенный только для вашего личного использования, вы можете либо передавать флаг --project с каждой командой, либо запустить firebase use PROJECT_ID не назначая псевдоним проекту Firebase.

Развертывайте и тестируйте свой проект Firebase локально.

Вы можете просмотреть и протестировать свой проект Firebase на локально размещенных URL-адресах перед развертыванием в продакшене. Если вы хотите протестировать только отдельные функции, вы можете использовать список, разделенный запятыми, в качестве флага в команде firebase serve .

Для выполнения одной из следующих задач выполните следующую команду из корневого каталога вашего локального проекта:

  • Просмотрите статическое содержимое вашего приложения, размещенного на Firebase.
  • Вы используете Cloud Functions для генерации динамического контента для Firebase Hosting и хотите использовать свои развернутые в рабочей среде HTTP-функции для эмуляции Hosting на локальном URL-адресе.
firebase serve --only hosting

Эмулируйте свой проект, используя локальные HTTP-функции.

Выполните любую из следующих команд из каталога вашего проекта, чтобы эмулировать ваш проект с использованием локальных HTTP-функций.

  • Для эмуляции HTTP-функций и хостинга для тестирования на локальных URL-адресах используйте одну из следующих команд:

    firebase serve
    firebase serve --only functions,hosting // uses a flag
  • Для эмуляции только HTTP-функций используйте следующую команду:

    firebase serve --only functions

Тестирование с других локальных устройств.

По умолчанию firebase serve отвечает только на запросы с localhost . Это означает, что вы сможете получить доступ к размещенному контенту с веб-браузера вашего компьютера, но не с других устройств в вашей сети. Если вы хотите протестировать с других локальных устройств, используйте флаг --host , например, так:

firebase serve --host 0.0.0.0  // accepts requests to any host

Развернуть в проекте Firebase

Интерфейс командной строки Firebase управляет развертыванием кода и ресурсов в вашем проекте Firebase, включая:

  • Новые версии ваших сайтов Firebase Hosting
  • Новые, обновленные или существующие Cloud Functions for Firebase
  • Новые или обновленные схемы и коннекторы для Firebase SQL Connect
  • Security Rules для Firebase Realtime Database
  • Security Rules для Cloud Storage for Firebase
  • Security Rules для Cloud Firestore
  • Индексы для Cloud Firestore
  • Настройка Authentication

Для развертывания в проекте Firebase выполните следующую команду из каталога вашего проекта:

firebase deploy

При желании вы можете добавить комментарий к каждому из ваших развертываний. Этот комментарий будет отображаться вместе с остальной информацией о развертывании на странице Firebase Hosting вашего проекта. Например:

firebase deploy -m "Deploying the best new feature ever."

При использовании команды firebase deploy следует учитывать следующее:

  • Для развертывания ресурсов из каталога проекта необходимо наличие файла firebase.json в этом каталоге. Этот файл автоматически создается командой firebase init .

  • По умолчанию firebase deploy создает релиз для всех развертываемых ресурсов в каталоге вашего проекта. Для развертывания определенных сервисов или функций Firebase используйте частичное развертывание .

Развертывание отдельных служб Firebase

Если вам нужно развернуть только определенные сервисы или функции Firebase, вы можете использовать список, разделенный запятыми, в качестве флага в команде firebase deploy . Например, следующая команда развертывает контент Firebase Hosting и Cloud Storage Security Rules .

firebase deploy --only hosting,storage

В таблице ниже перечислены сервисы и функции, доступные для частичного развертывания. Названия флагов соответствуют ключам в вашем конфигурационном файле firebase.json .

Синтаксис флагов Развернута служба или функция.
--only auth Конфигурация поставщика Authentication
--only database Firebase Realtime Database Security Rules
--only dataconnect Схемы и коннекторы Firebase SQL Connect
--only firestore Security Rules и индексы Cloud Firestore для всех настроенных баз данных
--only functions Cloud Functions for Firebase
--only hosting Содержимое Firebase Hosting
--only storage Cloud Storage for Firebase Security Rules Firebase

Конфликты развертывания Security Rules

Для Firebase Realtime Database , Cloud Storage for Firebase и Cloud Firestore Security Rules можно определить либо в локальном каталоге проекта, либо в консоли Firebase .

Ещё один способ избежать конфликтов при развертывании — использовать частичное развертывание и определять Security Rules только в консоли Firebase .

Настройте скриптовые задачи до и после развертывания.

Вы можете подключить скрипты оболочки к команде firebase deploy для выполнения задач до или после развертывания. Например, скрипт до развертывания может транспилировать код TypeScript в JavaScript, а хук после развертывания может уведомлять администраторов о развертывании нового контента сайта в Firebase Hosting .

Для настройки хуков predeploy или postdeploy добавьте bash-скрипты в конфигурационный файл firebase.json . Вы можете определить короткие скрипты непосредственно в файле firebase.json или сослаться на другие файлы, находящиеся в каталоге вашего проекта.

Например, следующий скрипт представляет собой выражение в firebase.json для задачи postdeploy, которая отправляет сообщение в Slack после успешного развертывания на Firebase Hosting .

"hosting": {
  // ...

  "postdeploy": "./messageSlack.sh 'Just deployed to Firebase Hosting'",
  "public": "public"
}

Файл скрипта messageSlack.sh находится в каталоге проекта и выглядит следующим образом:

curl -X POST -H 'Content-type: application/json' --data '{"text":"$1"}'
     \https://SLACK_WEBHOOK_URL

Вы можете настроить хуки predeploy и postdeploy для любого из развертываемых ресурсов . Обратите внимание, что запуск firebase deploy запускает все задачи predeploy и postdeploy, определенные в файле firebase.json . Чтобы запустить только те задачи, которые связаны с конкретной службой Firebase, используйте команды частичного развертывания .

Как хуки predeploy так и postdeploy выводят в терминал стандартный поток вывода и потоки ошибок скриптов. В случае сбоя обратите внимание на следующее:

  • Если проверка перед развертыванием не завершится должным образом, развертывание будет отменено.
  • Если развертывание по какой-либо причине не удается, обработчики событий postdeploy не срабатывают.

переменные окружающей среды

В скриптах, запускаемых в рамках обработчиков predeploy и postdeploy, доступны следующие переменные среды:

  • $GCLOUD_PROJECT : Идентификатор проекта активного проекта
  • $PROJECT_DIR : Корневой каталог, содержащий файл firebase.json
  • $RESOURCE_DIR : (Только для скриптов hosting и functions ) Расположение каталога, содержащего ресурсы Hosting или Cloud Functions которые необходимо развернуть.

Квоты на развертывание

Вполне возможно (хотя и маловероятно), что вы превысите квоту, ограничивающую скорость или объем операций развертывания Firebase. Например, при развертывании очень большого количества функций вы можете получить сообщение об ошибке HTTP 429 Quota . Для решения таких проблем попробуйте использовать частичное развертывание .

Откат развертывания

Вы можете откатить развертывание Firebase Hosting со страницы Firebase Hosting вашего проекта, выбрав действие «Откат» для выбранного релиза.

Откатить обновления Security Rules for Firebase Realtime Database , Cloud Storage for Firebase или Cloud Firestore невозможно.

Справочник команд

Административные команды CLI

Командование Описание
помощь Отображается справочная информация о интерфейсе командной строки или конкретных командах.
инициализация Эта команда связывает и создает новый проект Firebase в текущем каталоге. Она также создает конфигурационный файл firebase.json в текущем каталоге.
авторизоваться Аутентификация интерфейса командной строки с помощью вашей учетной записи Google. Требуется доступ к веб-браузеру.
Для входа в командную строку в удаленных средах, где доступ к localhost запрещен, используйте команду: --no-localhost flag.
вход:ci Генерирует токен аутентификации для использования в неинтерактивных средах.
login:add Входит в систему с дополнительной учетной записью Google.
вход:список Отображает список всех авторизованных учетных записей Google.
вход:использовать Устанавливает активный аккаунт Google.
выйти Выходит из своей учетной записи Google через командную строку.
открыть Открывает браузер для доступа к соответствующим ресурсам проекта.
проекты:список Отображает список всех проектов Firebase, к которым у вас есть доступ.
использовать Устанавливает активный проект Firebase для CLI.
Управляет псевдонимами проекта .

Команды управления проектами

Командование Описание
Управление проектами Firebase
проекты:addfirebase Добавляет ресурсы Firebase и включает сервисы Firebase в существующем проекте Google Cloud .
проекты:создать Создает новый проект Google Cloud , а затем добавляет в него ресурсы Firebase.
проекты:список Отображает список всех проектов Firebase, к которым у вас есть доступ.
Управление приложениями Firebase (iOS, Android, Web)
приложения:создать Создает новое приложение Firebase в активном проекте.
приложения:список Отображает список зарегистрированных приложений Firebase в активном проекте.
apps:sdkconfig Выводит конфигурацию Firebase приложения.
настройка: веб Устарело. Вместо этого используйте apps:sdkconfig и укажите web в качестве аргумента платформы.
Выводит конфигурацию Firebase веб-приложения.
Управление хэшами сертификатов SHA (только для Android)
apps:android:sha:create \
FIREBASE_APP_ID SHA_HASH
Добавляет указанный хэш SHA-сертификата в указанное приложение Firebase для Android.
apps:android:sha:delete \
FIREBASE_APP_ID SHA_HASH
Удаляет указанный хэш SHA-сертификата из указанного приложения Firebase для Android.
apps:android:sha:list \
FIREBASE_APP_ID
Выводит хеши SHA-сертификатов для указанного приложения Firebase для Android.

Развертывание и локальное развитие

Эти команды позволяют развертывать ваш сайт Firebase Hosting и взаимодействовать с ним.

Командование Описание
развертывать Развертывает код и ресурсы из каталога вашего проекта в активный проект. Для Firebase Hosting требуется конфигурационный файл firebase.json .
служить Запускает локальный веб-сервер с конфигурацией Firebase Hosting . Для Firebase Hosting требуется конфигурационный файл firebase.json .

Команды App Distribution

Командование Описание
appdistribution:distribute \
--app FIREBASE_APP_ID
Предоставляет доступ к сборке тестировщикам.
appdistribution:testers:add Добавляет тестировщиков в проект.
appdistribution:testers:remove Удаляет тестировщиков из проекта.
appdistribution:testers:list Содержит список тестировщиков, участвующих в проекте.
appdistribution:groups:create Создает группу тестировщиков.
appdistribution:groups:delete Удаляет группу тестировщиков.
appdistribution:groups:list Отображает список групп тестировщиков в проекте.

Команды App Hosting

Командование Описание
apphosting:backends:create \
--project PROJECT_ID \
--location REGION --app APP_ID
Создает набор управляемых ресурсов, связанных с единой кодовой базой, которая составляет бэкэнд App Hosting . При желании можно указать существующее веб-приложение Firebase по его идентификатору приложения Firebase.
apphosting:backends:get \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Получает конкретные сведения, включая публичный URL-адрес, бэкэнда.
apphosting:backends:list \
--project PROJECT_ID
Получает список всех активных бэкэндов, связанных с проектом.
firebase apphosting:backends:delete \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Удаляет бэкэнд из проекта.
firebase apphosting:config:export \
--project PROJECT_ID \
--secrets ENVIRONMENT_NAME
Экспортирует секретные данные для использования в эмуляции приложений.
По умолчанию используются секреты, хранящиеся в файле apphosting.yaml , или же параметр --secrets позволяет указать любую среду, для которой существует соответствующий файл apphosting. ENVIRONMENT_NAME .yaml .
firebase apphosting:rollouts:create \
BACKEND_ID \
--git_branch BRANCH_NAME \
--git_commit COMMIT_ID
Создает развертывание, запускаемое вручную.
При желании можно указать последний коммит в ветке или конкретный коммит. Если параметры не указаны, предлагается выбрать коммит из списка веток.
apphosting:secrets:set KEY --project PROJECT_ID \
--location REGION \
--data-file DATA_FILE_PATH
Хранит секретные материалы в Secret Manager.
При желании укажите путь для чтения секретных данных. Установите значение _ для чтения секретных данных из стандартного ввода.
apphosting:secrets:grantaccess KEY \
--backend BACKEND_ID \
--emails EMAILS \
--project PROJECT_ID \
--location REGION
Предоставляет права доступа к предоставленному секрету (секретам) учетным записям служб , пользователям или группам, чтобы обеспечить доступ к нему со стороны App Hosting во время сборки или выполнения. Можно передать один или несколько секретов, разделенных запятой.
apphosting:secrets:describe KEY \
--project PROJECT_ID
Получает метаданные секрета и его версий.
firebase apphosting:secrets:access \
KEY[@version] \
--project PROJECT_ID
Осуществляет доступ к секретному значению, зная сам секрет и его версию. По умолчанию используется последняя версия.

Команды Authentication (управления пользователями)

Командование Описание
auth:export Экспортирует учетные записи пользователей активного проекта в файл JSON или CSV. Для получения более подробной информации см. страницу auth:import и auth:export .
auth:import Импортирует учетные записи пользователей из JSON- или CSV-файла в активный проект. Для получения более подробной информации см. страницу auth:import и auth:export .

Команды Cloud Firestore

Командование Описание
firestore:locations

Перечислите доступные места для размещения вашей базы данных Cloud Firestore .

firestore:databases:create DATABASE_ID

Создайте экземпляр базы данных в нативном режиме в вашем проекте Firebase.

Команда принимает следующие флаги:

  • --location <имя региона> для указания места развертывания базы данных. Обратите внимание, что вы можете запустить firebase firestore:locations , чтобы получить список доступных мест. Обязательно .
  • Параметр --delete-protection <deleteProtectionState> разрешает или запрещает удаление указанной базы данных. Допустимые значения: ENABLED или DISABLED . По умолчанию — DISABLED .
  • --point-in-time-recovery <PITRState> — параметр , определяющий, включено ли восстановление на определенный момент времени. Допустимые значения: ENABLED или DISABLED . По умолчанию — DISABLED . Необязательный параметр.
  • --edition <edition> — для указания уровня базы данных. Для функций Enterprise установите значение enterprise .
  • --firestore-data-access <ENABLED|DISABLED> (только для корпоративных пользователей) для управления доступностью API Firestore. По умолчанию — ENABLED .
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (только для корпоративных пользователей) для управления доступностью API, совместимого с MongoDB. По умолчанию — DISABLED .
  • --realtime-updates <ENABLED|DISABLED> (только для корпоративных версий) позволяет включить или отключить функцию "Отслеживание" (в режиме реального времени). Требуется, чтобы --firestore-data-access был ENABLED . По умолчанию — ENABLED .
firestore:databases:list

Перечислите базы данных в вашем проекте Firebase.

firestore:databases:get DATABASE_ID

Получите конфигурацию базы данных для указанной базы данных в вашем проекте Firebase.

Для корпоративных баз данных выходные данные включают в себя информацию Edition , Firestore Data Access , MongoDB Compatible Data Access , и статусе Realtime Updates .

firestore:databases:update DATABASE_ID

Обновите конфигурацию указанной базы данных в вашем проекте Firebase.

Требуется как минимум один флаг. Команда принимает следующие флаги:

  • Параметр --delete-protection <deleteProtectionState> разрешает или запрещает удаление указанной базы данных. Допустимые значения: ENABLED или DISABLED . По умолчанию — DISABLED .
  • --point-in-time-recovery <PITRState> — параметр , определяющий, включено ли восстановление на определенный момент времени. Допустимые значения: ENABLED или DISABLED . По умолчанию — DISABLED . Необязательный параметр.
  • --firestore-data-access <ENABLED|DISABLED> (только для корпоративных клиентов) для управления доступностью API Firestore.
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (только для корпоративных клиентов) для управления доступностью API, совместимого с MongoDB.
  • --realtime-updates <ENABLED|DISABLED> (только для корпоративных версий) позволяет включить или отключить функцию "Отслеживание" (в режиме реального времени). Требуется ENABLED --firestore-data-access .
firestore:databases:delete DATABASE_ID

Удалите базу данных в своем проекте Firebase.

firestore:indexes

Вывести список индексов для базы данных в вашем проекте Firebase.

Команда принимает следующий флаг:

  • --database DATABASE_ID — укажите имя базы данных, для которой нужно вывести список индексов. Если не указано, индексы будут выведены для базы данных по умолчанию.
firestore:delete

Удаляет документы из базы данных активного проекта. С помощью командной строки можно рекурсивно удалить все документы в коллекции.

Note that deleting Cloud Firestore data with the CLI incurs read and delete costs. For more information, see Understand Cloud Firestore billing .

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database from which documents are deleted. If not specified, documents are deleted from the default database. Optional.

Cloud Functions for Firebase commands

Командование Описание
functions:config:clone Устарело.
Clones another project's environment into the active Firebase project.
functions:config:export Exports the active project's runtime configuration to Google Cloud Secret Manager .
functions:config:get Устарело.
Retrieves existing configuration values of the active project's Cloud Functions .
functions:config:set Устарело.
Stores runtime configuration values of the active project's Cloud Functions .
functions:config:unset Устарело.
Removes values from the active project's runtime configuration.
functions:delete \
FUNCTION_NAME
Deletes the specified function.
functions:list Lists deployed functions.
functions:log Reads logs from deployed Cloud Functions .
functions:secrets:access \
SECRET_NAME
Accesses a secret value given the secret and its version.
functions:secrets:destroy \
SECRET_NAME
Destroys a secret.
functions:secrets:get \
SECRET_NAME
Gets the metadata for a secret and its versions.
functions:secrets:prune Destroys unused secrets.
functions:secrets:set \
SECRET_NAME
Creates or updates a secret.
functions:shell Starts a local interactive shell for testing functions.

For more information, refer to the environment configuration documentation .

Crashlytics commands

Командование Описание
crashlytics:mappingfile:generateid \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML
Generates a unique mapping file ID in the specified Android resource (XML) file.
crashlytics:mappingfile:upload \
--app= FIREBASE_APP_ID \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML \
PATH/TO/MAPPING_FILE.TXT
Uploads a Proguard-compatible mapping (TXT) file for this app, and associates it with the mapping file ID declared in the specified Android resource (XML) file.
crashlytics:symbols:upload \
--app= FIREBASE_APP_ID \
PATH/TO/SYMBOLS
Generates a Crashlytics -compatible symbol file for native library crashes on Android and uploads it to Firebase servers.

SQL Connect commands

These commands and their use cases are covered in more detail in the SQL Connect CLI reference guide .

Командование Описание
dataconnect:services:list Lists all deployed SQL Connect services in your Firebase project.
dataconnect:sql:diff \
SERVICE_ID
For the specified service, displays the differences between a local SQL Connect schema and your Cloud SQL database schema.
dataconnect:sql:migrate \
--сила \
SERVICE_ID
Migrates your Cloud SQL database's schema to match your local SQL Connect schema.
dataconnect:sql:grant\
--role= ROLE \
--email= EMAIL \
SERVICE_ID
Grants the SQL role to the specified user or service account email.
For the --role flag, the SQL role to grant is one of: owner , writer , or reader .
For the --email flag, provide the email address of the user or service account to grant the role to.
dataconnect:sdk:generate Generates typed SDKs for your SQL Connect connectors.

Extensions commands

Командование Описание
наружный Displays information on how to use Firebase Extensions commands.
Lists the extension instances installed in the active project.
ext:configure \
EXTENSION_INSTANCE_ID
Reconfigures the parameter values of an extension instance in your extension manifest .
ext:info \
PUBLISHER_ID/EXTENSION_ID
Prints detailed information about an extension.
ext:install \
PUBLISHER_ID/EXTENSION_ID
Adds a new instance of an extension into your extension manifest .
ext:sdk:install Installs SDKs for defining extensions in functions.
ext:list Lists all the extension instances installed in a Firebase project.
Prints the instance ID for each extension.
ext:uninstall \
EXTENSION_INSTANCE_ID
Removes an extension instance from your extension manifest .
ext:update \
EXTENSION_INSTANCE_ID
Updates an extension instance to the latest version in your extension manifest .
ext:export Exports all installed extension instances from your project to your extension manifest .

Extensions publisher commands

Командование Описание
ext:dev:init Initializes a skeleton codebase for a new extension in the current directory.
ext:dev:list \
PUBLISHER_ID
Prints a list of all extensions uploaded by a publisher.
ext:dev:register Registers a Firebase project as an extensions publisher project .
ext:dev:deprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Deprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, deprecates all versions of that extension.
ext:dev:undeprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Undeprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, undeprecates all versions of that extension.
ext:dev:upload \
PUBLISHER_ID/EXTENSION_ID
Uploads a new version of an extension.
ext:dev:usage \
PUBLISHER_ID
Displays install counts and usage metrics for extensions uploaded by a publisher.

Hosting commands

Командование Описание
hosting:disable

Stops serving Firebase Hosting traffic for the active Firebase project.

Your project's Hosting URL will display a "Site Not Found" message after running this command.

Management of Hosting sites
firebase hosting:sites:create \
SITE_ID

Creates a new Hosting site in the active Firebase project using the specified SITE_ID

(Optional) Specify an existing Firebase Web App to associate with the new site by passing the following flag: --app FIREBASE_APP_ID

firebase hosting:sites:delete \
SITE_ID

Deletes the specified Hosting site

The CLI displays a confirmation prompt before deleting the site.

(Optional) Skip the confirmation prompt by passing the following flags: -f or --force

firebase hosting:sites:get \
SITE_ID

Retrieves information about the specified Hosting site

firebase hosting:sites:list

Lists all Hosting sites for the active Firebase project

Management of preview channels
firebase hosting:channel:create \
CHANNEL_ID

Creates a new preview channel in the default Hosting site using the specified CHANNEL_ID

This command doesn't deploy to the channel.

firebase hosting:channel:delete \
CHANNEL_ID

Deletes the specified preview channel

You cannot delete a site's live channel.

firebase hosting:channel:deploy \
CHANNEL_ID

Deploys your Hosting content and config to the specified preview channel

If the preview channel doesn't yet exist, this command creates the channel in the default Hosting site before deploying to the channel.

firebase hosting:channel:list Lists all channels (including the "live" channel) in the default Hosting site
firebase hosting:channel:open \
CHANNEL_ID
Opens a browser to the specified channel's URL or returns the URL if opening in a browser isn't possible
Version cloning
firebase hosting:clone \
SOURCE_SITE_ID : SOURCE_CHANNEL_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the most recently deployed version on the specified "source" channel to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

firebase hosting:clone \
SOURCE_SITE_ID :@ VERSION_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the specified version to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

You can find the VERSION_ID in the Hosting dashboard of the Firebase console.

Realtime Database commands

Note that you can create your initial, default Realtime Database instance in the Firebase console or by using the general firebase init workflow or the specific firebase init database flow.

Once instances are created, you can manage them as described in Manage and interact with specific instances using the CLI .

Командование Описание
database:get Fetches data from the active project's database and displays it as JSON. Supports querying on indexed data.
database:instances:create Creates a database instance with a specified instance name. Accepts the --location option for creating a database in a specified region. For region names to use with this option, see select locations for your project . If no database instance exists for the current project, you are prompted to run the firebase init flow to create an instance.
database:instances:list List all database instances for this project. Accepts the --location option for listing databases in a specified region. For region names to use with this option see select locations for your project .
database:profile Builds a profile of operations on the active project's database. For more details, refer to Realtime Database operation types .
database:push Pushes new data to a list at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:remove Deletes all data at a specified location in the active project's database.
database:set Replaces all data at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:update Performs a partial update at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.

Remote Config commands

Командование Описание
remoteconfig:versions:list \
--limit NUMBER_OF_VERSIONS
Lists the most recent ten versions of the template. Specify 0 to return all existing versions, or optionally pass the --limit option to limit the number of versions being returned.
remoteconfig:get \
--v, version_number VERSION_NUMBER
--o, output FILENAME
Gets the template by version (defaults to the latest version) and outputs the parameter groups, parameters, and condition names and version into a table. Optionally, you can write the output to a specified file with -o, FILENAME .
remoteconfig:rollback \
--v, version_number VERSION_NUMBER
--сила
Rolls back Remote Config template to a specified previous version number or defaults to the immediate previous version (current version -1). Unless --force is passed, prompts Y/N before proceeding to rollback.
remoteconfig:experiments:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config experiments for a project, with optional filtering, number of experiments to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:experiments:get \
EXPERIMENT_ID
Gets the details of the specified Remote Config experiment.
remoteconfig:experiments:delete \
EXPERIMENT_ID
Deletes the specified Remote Config experiment.
remoteconfig:rollouts:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config rollouts for a project, with optional filtering, number of rollouts to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:rollouts:get \
ROLLOUT_ID
Gets the details of the specified Remote Config rollout.
remoteconfig:rollouts:delete \
ROLLOUT_ID
Deletes the specified Remote Config rollout.
,

The Firebase CLI ( GitHub ) provides a variety of tools for managing, viewing, and deploying to Firebase projects.

Before using the Firebase CLI, set up a Firebase project .

Set up or update the CLI

Install the Firebase CLI

You can install the Firebase CLI using a method that matches your operating system, experience level, and/or use case. Regardless of how you install the CLI, you have access to the same functionality and the firebase command.

Windows macOS Linux

Windows

You can install the Firebase CLI for Windows using one of the following options:

Вариант Описание Recommended for...
standalone binary Download the standalone binary for the CLI. Then, you can access the executable to open a shell where you can run the firebase command. New developers

Developers not using or unfamiliar with Node.js
npm Use npm (the Node Package Manager) to install the CLI and enable the globally available firebase command. Developers using Node.js

standalone binary

To download and run the binary for the Firebase CLI, follow these steps:

  1. Download the Firebase CLI binary for Windows .

  2. Access the binary to open a shell where you can run the firebase command.

  3. Continue to log in and test the CLI .

npm

To use npm (the Node Package Manager) to install the Firebase CLI, follow these steps:

  1. Install Node.js using nvm-windows (the Node Version Manager). Installing Node.js automatically installs the npm command tools.

  2. Install the Firebase CLI via npm by running the following command:

    npm install -g firebase-tools

    This command enables the globally available firebase command.

  3. Continue to log in and test the CLI .

macOS or Linux

You can install the Firebase CLI for macOS or Linux using one of the following options:

Вариант Описание Recommended for...
automatic install script Run a single command that automatically detects your operating system, downloads the latest CLI release, then enables the globally available firebase command. New developers

Developers not using or unfamiliar with Node.js

Automated deploys in a CI/CD environment
standalone binary Download the standalone binary for the CLI. Then, you can configure and run the binary to suit your workflow. Fully customizable workflows using the CLI
npm Use npm (the Node Package Manager) to install the CLI and enable the globally available firebase command. Developers using Node.js

auto install script

To install the Firebase CLI using the automatic install script, follow these steps:

  1. Run the following cURL command:

    curl -sL https://firebase.tools | bash

    This script automatically detects your operating system, downloads the latest Firebase CLI release, then enables the globally available firebase command.

  2. Continue to log in and test the CLI .

For more examples and details about the automatic install script, refer to the script's source code at firebase.tools .

standalone binary

To download and run the binary for the Firebase CLI that's specific for your OS, follow these steps:

  1. Download the Firebase CLI binary for your OS: macOS | Linux

  2. (Optional) Set up the globally available firebase command.

    1. Make the binary executable by running chmod +x ./firebase_tools .
    2. Add the binary's path to your PATH.
  3. Continue to log in and test the CLI .

npm

To use npm (the Node Package Manager) to install the Firebase CLI, follow these steps:

  1. Install Node.js using nvm (the Node Version Manager).
    Installing Node.js automatically installs the npm command tools.

  2. Install the Firebase CLI via npm by running the following command:

    npm install -g firebase-tools

    This command enables the globally available firebase command.

  3. Continue to log in and test the CLI .

Log in and test the Firebase CLI

After installing the CLI, you must authenticate. Then you can confirm authentication by listing your Firebase projects.

  1. Log into Firebase using your Google account by running the following command:

    firebase login

    This command connects your local machine to Firebase and grants you access to your Firebase projects.

  2. Test that the CLI is properly installed and accessing your account by listing your Firebase projects. Run the following command:

    firebase projects:list

    The displayed list should be the same as the Firebase projects listed in the Firebase console .

Update to the latest CLI version

Generally, you want to use the most up-to-date Firebase CLI version.

How you update the CLI version depends on your operating system and how you installed the CLI.

Windows

macOS

  • automatic install script : Run curl -sL https://firebase.tools | upgrade=true bash

  • standalone binary : Download the new version , then replace it on your system

  • npm : Run npm install -g firebase-tools

Linux

  • automatic install script : Run curl -sL https://firebase.tools | upgrade=true bash

  • standalone binary : Download the new version , then replace it on your system

  • npm : Run npm install -g firebase-tools

Uninstall the Firebase CLI

How you uninstall the CLI depends on your operating system and how you installed the CLI.

Windows

  • standalone binary : Delete the firebase.exe binary that you downloaded.
  • npm : Run npm uninstall -g firebase-tools

macOS

  • automatic install script : Run curl -sL https://firebase.tools | uninstall=true bash

  • standalone binary : Delete the firebase binary that you downloaded. If you added its location to your PATH environment variable, be sure to remove it.

  • npm : Run npm uninstall -g firebase-tools

Linux

  • automatic install script : Run curl -sL https://firebase.tools | uninstall=true bash

  • standalone binary : Delete the firebase binary that you downloaded. If you added its location to your PATH environment variable, be sure to remove it.

  • npm : Run npm uninstall -g firebase-tools

Use the CLI with CI systems

We recommend that you authenticate using Application Default Credentials when using the CLI with CI systems.

(Recommended) Use Application Default Credentials

The Firebase CLI will detect and use Application Default Credentials if they're set. The simplest way to authenticate the CLI in CI and other headless environments is to set up Application Default Credentials .

(Legacy) Use FIREBASE_TOKEN

Alternatively, you can authenticate using FIREBASE_TOKEN . This is less secure than Application Default Credentials and is no longer recommended.

  1. On a machine with a browser, install the Firebase CLI .

  2. Start the signin process by running the following command:

    firebase login:ci
  3. Visit the URL provided, then log in using a Google account.

  4. Print a new refresh token . The current CLI session will not be affected.

  5. Store the output token in a secure but accessible way in your CI system.

  6. Use this token when running firebase commands. You can use either of the following two options:

    • Option 1: Store the token as the environment variable FIREBASE_TOKEN . Your system will automatically use the token.

    • Option 2: Run all firebase commands with the --token TOKEN flag in your CI system.
      This is the order of precedence for token loading: flag, environment variable, desired Firebase project.

Initialize a Firebase project

Many common tasks performed using the CLI, such as deploying to a Firebase project, require a project directory . You establish a project directory using the firebase init command. A project directory is usually the same directory as your source control root, and after running firebase init , the directory contains a firebase.json configuration file.

To initialize a new Firebase project, run the following command from within your app's directory:

firebase init

The firebase init command steps you through setting up your project directory and some Firebase products. During project initialization, the Firebase CLI asks you to complete the following tasks:

  • Select a default Firebase project.

    This step associates the current project directory with a Firebase project so that project-specific commands (like firebase deploy ) run against the appropriate Firebase project.

    It's also possible to associate multiple Firebase projects (such as a staging project and a production project) with the same project directory.

  • Select Firebase products to set up in your Firebase project.

    This step prompts you to set configurations for specific files for the selected products or features. For more details on these configurations, refer to the specific product's documentation (for example, Hosting or Authentication ). Note that you can always run firebase init later to set up more Firebase products.

At the end of initialization, Firebase automatically creates the following two files at the root of your local app directory:

  • A firebase.json configuration file that lists your project configuration.

  • A .firebaserc file that stores your project aliases .

The firebase.json file

The firebase init command creates a firebase.json configuration file in the root of your project directory.

The firebase.json file is required to deploy assets with the Firebase CLI because it specifies which files and settings from your project directory are deployed to your Firebase project (like Hosting settings, Authentication provider configurations, security rules, and Cloud Functions configuration). Since some settings can be defined in either your project directory or the Firebase console, make sure that you resolve any potential deployment conflicts .

You can configure most Firebase Hosting options directly in the firebase.json file. However, for other Firebase services that can be deployed with the Firebase CLI , the firebase init command creates specific files where you can define settings for those services, such as an index.js file for Cloud Functions . You can also set up predeploy or postdeploy hooks in the firebase.json file.

The following firebase.json file is a comprehensive example showing configuration options for many Firebase services. It also demonstrates features like multi-codebase Cloud Functions , Local Emulator Suite setup, and a Remote Config template. Note that a firebase.json file for any given project will only contain configurations for the Firebase services set up for that specific project (for example, only Firebase Hosting and Cloud Functions ). Adding the $schema key enables validation and autocompletion in many code editors.

    {
      "$schema": "https://raw.githubusercontent.com/firebase/firebase-tools/master/schema/firebase-config.json",
      "hosting": {
        "public": "public",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "cleanUrls": true,
        "trailingSlash": false
      },
      "apphosting": {
        "backendId": "my-app",
        "rootDir": "backend",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ]
      },
      "firestore": {
        "rules": "firestore.rules",
        "indexes": "firestore.indexes.json"
      },
      "storage": {
        "rules": "storage.rules"
      },
      "database": {
        "rules": "database.rules.json"
      },
      "dataconnect": {
        "source": "dataconnect",
        "location": "us-central1"
      },
      "functions": [
        {
          "source": "functions",
          "codebase": "default",
          "ignore": [
            "**/.*",
            "**/node_modules/**"
          ],
          "predeploy": [
            "npm --prefix \"$RESOURCE_DIR\" run lint",
            "npm --prefix \"$RESOURCE_DIR\" run build"
          ]
        }
      ],
      "emulators": {
        "auth": {
          "port": 9099
        },
        "functions": {
          "port": 5001
        },
        "firestore": {
          "port": 8080
        },
        "hosting": {
          "port": 5000
        },
        "storage": {
          "port": 9199
        },
        "ui": {
          "enabled": true,
          "port": 4000
        },
        "singleProjectMode": true
      },
      "extensions": {
        "my-storage-resizer": "firebase/storage-resize-images@^0.1.0"
      },
      "auth": {
        "providers": {
          "anonymous": true,
          "emailPassword": true,
          "googleSignIn": {
            "oAuthBrandDisplayName": "My App",
            "supportEmail": "support@myapp.com"
          }
        }
      },
      "remoteconfig": {
        "template": "remoteconfig.template.json"
      }
    }

While firebase.json is used by default, you can pass the --config PATH flag to specify an alternate configuration file.

Configuration for multiple Cloud Firestore databases

When you run firebase init , your firebase.json file will contain a single firestore key corresponding to your project's default database, as shown in the preceding example.

If your project contains multiple Cloud Firestore databases, edit your firebase.json file to associate different Cloud Firestore Security Rules and database index source files with each database. Modify the file with a JSON array, with one entry for each database.

      "firestore": [
        {
          "database": "(default)",
          "rules": "firestore.default.rules",
          "indexes": "firestore.default.indexes.json"
        },
        {
          "database": "ecommerce",
          "rules": "firestore.ecommerce.rules",
          "indexes": "firestore.ecommerce.indexes.json"
        }
      ],

Cloud Functions files to ignore on deploy

At function deployment time, the CLI automatically specifies a list of files in the functions directory to ignore. This prevents deploying to the backend extraneous files that could increase the data size of your deployment.

The list of files ignored by default, shown in JSON format, is:

"ignore": [
  ".git",
  ".runtimeconfig.json",
  "firebase-debug.log",
  "firebase-debug.*.log",
  "node_modules"
]

If you add your own custom values for ignore in firebase.json , make sure that you keep (or add, if it is missing) the list of files shown in the preceding list.

Manage project aliases

You can associate multiple Firebase projects with the same project directory. For example, you might want to use one Firebase project for staging and another for production. By using different project environments, you can verify changes before deploying to production. The firebase use command lets you switch between aliases as well as create new aliases.

Add a project alias

When you select a Firebase project during project initialization , the project is automatically assigned the alias of default . However, to allow project-specific commands to run against a different Firebase project but still use the same project directory, run the following command from within your project directory:

firebase use --add

This command prompts you to select another Firebase project and assign the project as alias. Alias assignments are written to a .firebaserc file inside your project directory.

Use project aliases

To use assigned Firebase project aliases, run any of the following commands from within your project directory.

Командование Описание
firebase use View a list of defined aliases for your project directory
firebase use \
PROJECT_ID|ALIAS
Directs all commands to run against the specified Firebase project.
The CLI uses this project as the "active project".
firebase use --clear Clears the active project.

Run firebase use PROJECT_ID|ALIAS to set a new active project before running other CLI commands.

firebase use \
--unalias PROJECT_ALIAS
Removes an alias from your project directory.

You can override what's being used as the active project by passing the --project flag with any CLI command. As an example: You can set your CLI to run against a Firebase project that you've assigned the staging alias. If you want to run a single command against the Firebase project that you've assigned the prod alias, then you can run, for example, firebase deploy --project=prod .

Source control and project aliases

In general, you should check your .firebaserc file into source control to allow your team to share project aliases. However, for open source projects or starter templates, you should generally not check in your .firebaserc file.

If you have a development project that's for your use only, you can either pass the --project flag with each command or run firebase use PROJECT_ID without assigning an alias to the Firebase project.

Serve and test your Firebase project locally

You can view and test your Firebase project on locally hosted URLs before deploying to production. If you only want to test select features, you can use a comma-separated list in a flag on the firebase serve command.

Run the following command from the root of your local project directory if you want to do either of the following tasks:

firebase serve --only hosting

Emulate your project using local HTTP functions

Run any of the following commands from your project directory to emulate your project using local HTTP functions.

  • To emulate HTTP functions and hosting for testing on local URLs, use either of the following commands:

    firebase serve
    firebase serve --only functions,hosting // uses a flag
  • To emulate HTTP functions only, use the following command:

    firebase serve --only functions

Test from other local devices

By default, firebase serve only responds to requests from localhost . This means that you'll be able to access your hosted content from your computer's web browser but not from other devices on your network. If you'd like to test from other local devices, use the --host flag, like so:

firebase serve --host 0.0.0.0  // accepts requests to any host

Deploy to a Firebase project

The Firebase CLI manages deployment of code and assets to your Firebase project, including:

  • New releases of your Firebase Hosting sites
  • New, updated, or existing Cloud Functions for Firebase
  • New or updated schemas and connectors for Firebase SQL Connect
  • Security Rules for Firebase Realtime Database
  • Security Rules for Cloud Storage for Firebase
  • Security Rules for Cloud Firestore
  • Indexes for Cloud Firestore
  • Configuration for Authentication

To deploy to a Firebase project, run the following command from your project directory:

firebase deploy

You can optionally add a comment to each of your deployments. This comment will display with the other deployment information on your project's Firebase Hosting page . For example:

firebase deploy -m "Deploying the best new feature ever."

When you use the firebase deploy command, be aware of the following:

  • To deploy resources from a project directory, the project directory must have a firebase.json file. This file is automatically created for you by the firebase init command.

  • By default, firebase deploy creates a release for all deployable resources in your project directory. To deploy specific Firebase services or features, use partial deployment .

Deploy specific Firebase services

If you only want to deploy specific Firebase services or features, you can use a comma-separated list in a flag on the firebase deploy command. For example, the following command deploys Firebase Hosting content and Cloud Storage Security Rules .

firebase deploy --only hosting,storage

The following table lists the services and features available for partial deployment. The names in the flags correspond to the keys in your firebase.json configuration file.

Flag syntax Service or feature deployed
--only auth Authentication provider configuration
--only database Firebase Realtime Database Security Rules
--only dataconnect Firebase SQL Connect schemas and connectors
--only firestore Cloud Firestore Security Rules and indexes for all configured databases
--only functions Cloud Functions for Firebase
--only hosting Firebase Hosting content
--only storage Cloud Storage for Firebase Security Rules

Deployment conflicts for Security Rules

For Firebase Realtime Database , Cloud Storage for Firebase , and Cloud Firestore , you can define Security Rules either in your local project directory or in the Firebase console .

Another option to avoid deployment conflicts is to use partial deployment and only define Security Rules in the Firebase console.

Set up predeploy and postdeploy scripted tasks

You can connect shell scripts to the firebase deploy command to perform predeploy or postdeploy tasks. For example, a predeploy script could transpile TypeScript code into JavaScript, and a postdeploy hook could notify administrators of new site content deploys to Firebase Hosting .

To set up predeploy or postdeploy hooks, add bash scripts to your firebase.json configuration file. You can define brief scripts directly in the firebase.json file, or you can reference other files that are in your project directory.

For example, the following script is the firebase.json expression for a postdeploy task that sends a Slack message upon successful deployment to Firebase Hosting .

"hosting": {
  // ...

  "postdeploy": "./messageSlack.sh 'Just deployed to Firebase Hosting'",
  "public": "public"
}

The messageSlack.sh script file resides in the project directory and looks like this:

curl -X POST -H 'Content-type: application/json' --data '{"text":"$1"}'
     \https://SLACK_WEBHOOK_URL

You can set up predeploy and postdeploy hooks for any of the assets that you can deploy . Note that running firebase deploy triggers all the predeploy and postdeploy tasks defined in your firebase.json file. To run only those tasks associated with a specific Firebase service, use partial deployment commands .

Both predeploy and postdeploy hooks print the standard output and error streams of the scripts to the terminal. For failure cases, note the following:

  • If a predeploy hook fails to complete as expected, deployment is canceled.
  • If deployment fails for any reason, postdeploy hooks are not triggered.

переменные окружающей среды

Within scripts running in the predeploy and postdeploy hooks, the following environment variables are available:

  • $GCLOUD_PROJECT : The active project's project ID
  • $PROJECT_DIR : The root directory containing the firebase.json file
  • $RESOURCE_DIR : (For hosting and functions scripts only) The location of the directory that contains the Hosting or Cloud Functions resources to be deployed

Deployment quotas

It's possible (though unlikely) that you might exceed a quota that limits the rate or volume of your Firebase deployment operations. For example, when deploying very large numbers of functions, you might receive an HTTP 429 Quota error message. To solve such issues, try using partial deployment .

Roll back a deployment

You can roll back a Firebase Hosting deployment from your project's Firebase Hosting page by selecting the Rollback action for the chosen release.

It's not possible to roll back releases of Security Rules for Firebase Realtime Database , Cloud Storage for Firebase , or Cloud Firestore .

Справочник команд

CLI administrative commands

Командование Описание
помощь Displays help information about the CLI or specific commands.
инициализация Associates and sets up a new Firebase project in the current directory. This command creates a firebase.json configuration file in the current directory.
авторизоваться Authenticates the CLI with your Google Account. Requires access to a web browser.
To log into the CLI in remote environments that don't allow access to localhost , use the --no-localhost flag.
login:ci Generates an authentication token for use in non-interactive environments.
login:add Logs in an additional Google Account.
login:list Lists all authenticated Google Accounts.
login:use Sets the active Google Account.
выйти Signs out your Google Account from the CLI.
открыть Opens a browser to relevant project resources.
projects:list Lists all the Firebase projects to which you have access.
использовать Sets the active Firebase project for the CLI.
Manages project aliases .

Project management commands

Командование Описание
Management of Firebase projects
projects:addfirebase Adds Firebase resources and enables Firebase services in an existing Google Cloud project.
projects:create Creates a new Google Cloud project, then adds Firebase resources to the new project.
projects:list Lists all the Firebase projects to which you have access.
Management of Firebase Apps (iOS, Android, Web)
apps:create Creates a new Firebase App in the active project.
apps:list Lists the registered Firebase Apps in the active project.
apps:sdkconfig Prints the Firebase configuration of a Firebase App.
setup:web Deprecated. Instead, use apps:sdkconfig and specify web as the platform argument.
Prints the Firebase configuration of a Firebase Web App.
Management of SHA certificate hashes (Android only)
apps:android:sha:create \
FIREBASE_APP_ID SHA_HASH
Adds the specified SHA certificate hash to the specified Firebase Android App.
apps:android:sha:delete \
FIREBASE_APP_ID SHA_HASH
Deletes the specified SHA certificate hash from the specified Firebase Android App.
apps:android:sha:list \
FIREBASE_APP_ID
Lists the SHA certificate hashes for the specified Firebase Android App.

Deployment and local development

These commands let you deploy and interact with your Firebase Hosting site.

Командование Описание
развертывать Deploys code and assets from your project directory to the active project. For Firebase Hosting , a firebase.json configuration file is required.
служить Starts a local web server with your Firebase Hosting configuration. For Firebase Hosting , a firebase.json configuration file is required.

App Distribution commands

Командование Описание
appdistribution:distribute \
--app FIREBASE_APP_ID
Makes the build available to testers.
appdistribution:testers:add Adds testers to the project.
appdistribution:testers:remove Removes testers from the project.
appdistribution:testers:list Lists testers in the project.
appdistribution:groups:create Creates a tester group.
appdistribution:groups:delete Deletes a tester group.
appdistribution:groups:list Lists tester groups in the project.

App Hosting commands

Командование Описание
apphosting:backends:create \
--project PROJECT_ID \
--location REGION --app APP_ID
Creates the collection of managed resources linked to a single codebase that comprises an App Hosting backend. Optionally specify an existing Firebase Web app by its Firebase app ID.
apphosting:backends:get \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Retrieves specific details, including the public URL, of a backend.
apphosting:backends:list \
--project PROJECT_ID
Retrieves a list of all active backends associated with a project.
firebase apphosting:backends:delete \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Deletes a backend from the project.
firebase apphosting:config:export \
--project PROJECT_ID \
--secrets ENVIRONMENT_NAME
Exports secrets for use in app emulation.
Defaults to secrets stored in apphosting.yaml , or takes --secrets to specify any environment that has a corresponding apphosting. ENVIRONMENT_NAME .yaml file.
firebase apphosting:rollouts:create \
BACKEND_ID \
--git_branch BRANCH_NAME \
--git_commit COMMIT_ID
Creates a manually triggered rollout.
Optionally specify the latest commit to a branch or a specific commit. If no options are provided, prompts selection from a list of branches.
apphosting:secrets:set KEY --project PROJECT_ID \
--location REGION \
--data-file DATA_FILE_PATH
Stores secret material in Secret Manager.
Optionally provide a path from which to read secret data. Set to _ to read secret data from standard input.
apphosting:secrets:grantaccess KEY \
--backend BACKEND_ID \
--emails EMAILS \
--project PROJECT_ID \
--location REGION
Grants permissions to the provided secret(s) to service accounts , users, or groups, so that it can be accessed by App Hosting at build or run time. Can pass one or more secrets, separated by a comma.
apphosting:secrets:describe KEY \
--project PROJECT_ID
Gets the metadata for a secret and its versions.
firebase apphosting:secrets:access \
KEY[@version] \
--project PROJECT_ID
Accesses a secret value given the secret and its version. Defaults to accessing the latest version.

Authentication (user management) commands

Командование Описание
auth:export Exports the active project's user accounts to a JSON or CSV file. For more details, refer to the auth:import and auth:export page .
auth:import Imports the user accounts from a JSON or CSV file into the active project. For more details, refer to the auth:import and auth:export page .

Cloud Firestore commands

Командование Описание
firestore:locations

List available locations for your Cloud Firestore database.

firestore:databases:create DATABASE_ID

Create a database instance in native mode in your Firebase project.

The command takes the following flags:

  • --location <region name> to specify the deployment location for the database. Note you can run firebase firestore:locations to list available locations. Required .
  • --delete-protection <deleteProtectionState> to allow or prevent deletion of the specified database. Valid values are ENABLED or DISABLED . Defaults to DISABLED .
  • --point-in-time-recovery <PITRState> to set whether point-in-time recovery is enabled. Valid values are ENABLED or DISABLED . Defaults to DISABLED . Optional.
  • --edition <edition> to specify the database tier. For Enterprise features, set to enterprise .
  • --firestore-data-access <ENABLED|DISABLED> (Enterprise only) to control Firestore API availability. Defaults to ENABLED .
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (Enterprise only) to control MongoDB-compatible API availability. Defaults to DISABLED .
  • --realtime-updates <ENABLED|DISABLED> (Enterprise only) to enable or disable the "Watch" (realtime) feature. Requires --firestore-data-access to be ENABLED . Defaults to ENABLED .
firestore:databases:list

List databases in your Firebase project.

firestore:databases:get DATABASE_ID

Get database configuration for a specified database in your Firebase project.

For Enterprise databases, the output includes Edition , Firestore Data Access , MongoDB Compatible Data Access , and Realtime Updates status.

firestore:databases:update DATABASE_ID

Update database configuration of a specified database in your Firebase project.

At least one flag is required. The command takes the following flags:

  • --delete-protection <deleteProtectionState> to allow or prevent deletion of the specified database. Valid values are ENABLED or DISABLED . Defaults to DISABLED .
  • --point-in-time-recovery <PITRState> to set whether point-in-time recovery is enabled. Valid values are ENABLED or DISABLED . Defaults to DISABLED . Optional.
  • --firestore-data-access <ENABLED|DISABLED> (Enterprise only) to control Firestore API availability.
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (Enterprise only) to control MongoDB-compatible API availability.
  • --realtime-updates <ENABLED|DISABLED> (Enterprise only) to enable or disable the "Watch" (realtime) feature. Requires --firestore-data-access to be ENABLED .
firestore:databases:delete DATABASE_ID

Delete a database in your Firebase project.

firestore:indexes

List indexes for a database in your Firebase project.

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database for which to list indexes. If not provided, indexes are listed for the default database.
firestore:delete

Deletes documents in the active project's database. Using the CLI, you can recursively delete all the documents in a collection.

Note that deleting Cloud Firestore data with the CLI incurs read and delete costs. For more information, see Understand Cloud Firestore billing .

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database from which documents are deleted. If not specified, documents are deleted from the default database. Optional.

Cloud Functions for Firebase commands

Командование Описание
functions:config:clone Устарело.
Clones another project's environment into the active Firebase project.
functions:config:export Exports the active project's runtime configuration to Google Cloud Secret Manager .
functions:config:get Устарело.
Retrieves existing configuration values of the active project's Cloud Functions .
functions:config:set Устарело.
Stores runtime configuration values of the active project's Cloud Functions .
functions:config:unset Устарело.
Removes values from the active project's runtime configuration.
functions:delete \
FUNCTION_NAME
Deletes the specified function.
functions:list Lists deployed functions.
functions:log Reads logs from deployed Cloud Functions .
functions:secrets:access \
SECRET_NAME
Accesses a secret value given the secret and its version.
functions:secrets:destroy \
SECRET_NAME
Destroys a secret.
functions:secrets:get \
SECRET_NAME
Gets the metadata for a secret and its versions.
functions:secrets:prune Destroys unused secrets.
functions:secrets:set \
SECRET_NAME
Creates or updates a secret.
functions:shell Starts a local interactive shell for testing functions.

For more information, refer to the environment configuration documentation .

Crashlytics commands

Командование Описание
crashlytics:mappingfile:generateid \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML
Generates a unique mapping file ID in the specified Android resource (XML) file.
crashlytics:mappingfile:upload \
--app= FIREBASE_APP_ID \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML \
PATH/TO/MAPPING_FILE.TXT
Uploads a Proguard-compatible mapping (TXT) file for this app, and associates it with the mapping file ID declared in the specified Android resource (XML) file.
crashlytics:symbols:upload \
--app= FIREBASE_APP_ID \
PATH/TO/SYMBOLS
Generates a Crashlytics -compatible symbol file for native library crashes on Android and uploads it to Firebase servers.

SQL Connect commands

These commands and their use cases are covered in more detail in the SQL Connect CLI reference guide .

Командование Описание
dataconnect:services:list Lists all deployed SQL Connect services in your Firebase project.
dataconnect:sql:diff \
SERVICE_ID
For the specified service, displays the differences between a local SQL Connect schema and your Cloud SQL database schema.
dataconnect:sql:migrate \
--сила \
SERVICE_ID
Migrates your Cloud SQL database's schema to match your local SQL Connect schema.
dataconnect:sql:grant\
--role= ROLE \
--email= EMAIL \
SERVICE_ID
Grants the SQL role to the specified user or service account email.
For the --role flag, the SQL role to grant is one of: owner , writer , or reader .
For the --email flag, provide the email address of the user or service account to grant the role to.
dataconnect:sdk:generate Generates typed SDKs for your SQL Connect connectors.

Extensions commands

Командование Описание
наружный Displays information on how to use Firebase Extensions commands.
Lists the extension instances installed in the active project.
ext:configure \
EXTENSION_INSTANCE_ID
Reconfigures the parameter values of an extension instance in your extension manifest .
ext:info \
PUBLISHER_ID/EXTENSION_ID
Prints detailed information about an extension.
ext:install \
PUBLISHER_ID/EXTENSION_ID
Adds a new instance of an extension into your extension manifest .
ext:sdk:install Installs SDKs for defining extensions in functions.
ext:list Lists all the extension instances installed in a Firebase project.
Prints the instance ID for each extension.
ext:uninstall \
EXTENSION_INSTANCE_ID
Removes an extension instance from your extension manifest .
ext:update \
EXTENSION_INSTANCE_ID
Updates an extension instance to the latest version in your extension manifest .
ext:export Exports all installed extension instances from your project to your extension manifest .

Extensions publisher commands

Командование Описание
ext:dev:init Initializes a skeleton codebase for a new extension in the current directory.
ext:dev:list \
PUBLISHER_ID
Prints a list of all extensions uploaded by a publisher.
ext:dev:register Registers a Firebase project as an extensions publisher project .
ext:dev:deprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Deprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, deprecates all versions of that extension.
ext:dev:undeprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Undeprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, undeprecates all versions of that extension.
ext:dev:upload \
PUBLISHER_ID/EXTENSION_ID
Uploads a new version of an extension.
ext:dev:usage \
PUBLISHER_ID
Displays install counts and usage metrics for extensions uploaded by a publisher.

Hosting commands

Командование Описание
hosting:disable

Stops serving Firebase Hosting traffic for the active Firebase project.

Your project's Hosting URL will display a "Site Not Found" message after running this command.

Management of Hosting sites
firebase hosting:sites:create \
SITE_ID

Creates a new Hosting site in the active Firebase project using the specified SITE_ID

(Optional) Specify an existing Firebase Web App to associate with the new site by passing the following flag: --app FIREBASE_APP_ID

firebase hosting:sites:delete \
SITE_ID

Deletes the specified Hosting site

The CLI displays a confirmation prompt before deleting the site.

(Optional) Skip the confirmation prompt by passing the following flags: -f or --force

firebase hosting:sites:get \
SITE_ID

Retrieves information about the specified Hosting site

firebase hosting:sites:list

Lists all Hosting sites for the active Firebase project

Management of preview channels
firebase hosting:channel:create \
CHANNEL_ID

Creates a new preview channel in the default Hosting site using the specified CHANNEL_ID

This command doesn't deploy to the channel.

firebase hosting:channel:delete \
CHANNEL_ID

Deletes the specified preview channel

You cannot delete a site's live channel.

firebase hosting:channel:deploy \
CHANNEL_ID

Deploys your Hosting content and config to the specified preview channel

If the preview channel doesn't yet exist, this command creates the channel in the default Hosting site before deploying to the channel.

firebase hosting:channel:list Lists all channels (including the "live" channel) in the default Hosting site
firebase hosting:channel:open \
CHANNEL_ID
Opens a browser to the specified channel's URL or returns the URL if opening in a browser isn't possible
Version cloning
firebase hosting:clone \
SOURCE_SITE_ID : SOURCE_CHANNEL_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the most recently deployed version on the specified "source" channel to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

firebase hosting:clone \
SOURCE_SITE_ID :@ VERSION_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the specified version to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

You can find the VERSION_ID in the Hosting dashboard of the Firebase console.

Realtime Database commands

Note that you can create your initial, default Realtime Database instance in the Firebase console or by using the general firebase init workflow or the specific firebase init database flow.

Once instances are created, you can manage them as described in Manage and interact with specific instances using the CLI .

Командование Описание
database:get Fetches data from the active project's database and displays it as JSON. Supports querying on indexed data.
database:instances:create Creates a database instance with a specified instance name. Accepts the --location option for creating a database in a specified region. For region names to use with this option, see select locations for your project . If no database instance exists for the current project, you are prompted to run the firebase init flow to create an instance.
database:instances:list List all database instances for this project. Accepts the --location option for listing databases in a specified region. For region names to use with this option see select locations for your project .
database:profile Builds a profile of operations on the active project's database. For more details, refer to Realtime Database operation types .
database:push Pushes new data to a list at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:remove Deletes all data at a specified location in the active project's database.
database:set Replaces all data at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:update Performs a partial update at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.

Remote Config commands

Командование Описание
remoteconfig:versions:list \
--limit NUMBER_OF_VERSIONS
Lists the most recent ten versions of the template. Specify 0 to return all existing versions, or optionally pass the --limit option to limit the number of versions being returned.
remoteconfig:get \
--v, version_number VERSION_NUMBER
--o, output FILENAME
Gets the template by version (defaults to the latest version) and outputs the parameter groups, parameters, and condition names and version into a table. Optionally, you can write the output to a specified file with -o, FILENAME .
remoteconfig:rollback \
--v, version_number VERSION_NUMBER
--сила
Rolls back Remote Config template to a specified previous version number or defaults to the immediate previous version (current version -1). Unless --force is passed, prompts Y/N before proceeding to rollback.
remoteconfig:experiments:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config experiments for a project, with optional filtering, number of experiments to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:experiments:get \
EXPERIMENT_ID
Gets the details of the specified Remote Config experiment.
remoteconfig:experiments:delete \
EXPERIMENT_ID
Deletes the specified Remote Config experiment.
remoteconfig:rollouts:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config rollouts for a project, with optional filtering, number of rollouts to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:rollouts:get \
ROLLOUT_ID
Gets the details of the specified Remote Config rollout.
remoteconfig:rollouts:delete \
ROLLOUT_ID
Deletes the specified Remote Config rollout.
,

The Firebase CLI ( GitHub ) provides a variety of tools for managing, viewing, and deploying to Firebase projects.

Before using the Firebase CLI, set up a Firebase project .

Set up or update the CLI

Install the Firebase CLI

You can install the Firebase CLI using a method that matches your operating system, experience level, and/or use case. Regardless of how you install the CLI, you have access to the same functionality and the firebase command.

Windows macOS Linux

Windows

You can install the Firebase CLI for Windows using one of the following options:

Вариант Описание Recommended for...
standalone binary Download the standalone binary for the CLI. Then, you can access the executable to open a shell where you can run the firebase command. New developers

Developers not using or unfamiliar with Node.js
npm Use npm (the Node Package Manager) to install the CLI and enable the globally available firebase command. Developers using Node.js

standalone binary

To download and run the binary for the Firebase CLI, follow these steps:

  1. Download the Firebase CLI binary for Windows .

  2. Access the binary to open a shell where you can run the firebase command.

  3. Continue to log in and test the CLI .

npm

To use npm (the Node Package Manager) to install the Firebase CLI, follow these steps:

  1. Install Node.js using nvm-windows (the Node Version Manager). Installing Node.js automatically installs the npm command tools.

  2. Install the Firebase CLI via npm by running the following command:

    npm install -g firebase-tools

    This command enables the globally available firebase command.

  3. Continue to log in and test the CLI .

macOS or Linux

You can install the Firebase CLI for macOS or Linux using one of the following options:

Вариант Описание Recommended for...
automatic install script Run a single command that automatically detects your operating system, downloads the latest CLI release, then enables the globally available firebase command. New developers

Developers not using or unfamiliar with Node.js

Automated deploys in a CI/CD environment
standalone binary Download the standalone binary for the CLI. Then, you can configure and run the binary to suit your workflow. Fully customizable workflows using the CLI
npm Use npm (the Node Package Manager) to install the CLI and enable the globally available firebase command. Developers using Node.js

auto install script

To install the Firebase CLI using the automatic install script, follow these steps:

  1. Run the following cURL command:

    curl -sL https://firebase.tools | bash

    This script automatically detects your operating system, downloads the latest Firebase CLI release, then enables the globally available firebase command.

  2. Continue to log in and test the CLI .

For more examples and details about the automatic install script, refer to the script's source code at firebase.tools .

standalone binary

To download and run the binary for the Firebase CLI that's specific for your OS, follow these steps:

  1. Download the Firebase CLI binary for your OS: macOS | Linux

  2. (Optional) Set up the globally available firebase command.

    1. Make the binary executable by running chmod +x ./firebase_tools .
    2. Add the binary's path to your PATH.
  3. Continue to log in and test the CLI .

npm

To use npm (the Node Package Manager) to install the Firebase CLI, follow these steps:

  1. Install Node.js using nvm (the Node Version Manager).
    Installing Node.js automatically installs the npm command tools.

  2. Install the Firebase CLI via npm by running the following command:

    npm install -g firebase-tools

    This command enables the globally available firebase command.

  3. Continue to log in and test the CLI .

Log in and test the Firebase CLI

After installing the CLI, you must authenticate. Then you can confirm authentication by listing your Firebase projects.

  1. Log into Firebase using your Google account by running the following command:

    firebase login

    This command connects your local machine to Firebase and grants you access to your Firebase projects.

  2. Test that the CLI is properly installed and accessing your account by listing your Firebase projects. Run the following command:

    firebase projects:list

    The displayed list should be the same as the Firebase projects listed in the Firebase console .

Update to the latest CLI version

Generally, you want to use the most up-to-date Firebase CLI version.

How you update the CLI version depends on your operating system and how you installed the CLI.

Windows

macOS

  • automatic install script : Run curl -sL https://firebase.tools | upgrade=true bash

  • standalone binary : Download the new version , then replace it on your system

  • npm : Run npm install -g firebase-tools

Linux

  • automatic install script : Run curl -sL https://firebase.tools | upgrade=true bash

  • standalone binary : Download the new version , then replace it on your system

  • npm : Run npm install -g firebase-tools

Uninstall the Firebase CLI

How you uninstall the CLI depends on your operating system and how you installed the CLI.

Windows

  • standalone binary : Delete the firebase.exe binary that you downloaded.
  • npm : Run npm uninstall -g firebase-tools

macOS

  • automatic install script : Run curl -sL https://firebase.tools | uninstall=true bash

  • standalone binary : Delete the firebase binary that you downloaded. If you added its location to your PATH environment variable, be sure to remove it.

  • npm : Run npm uninstall -g firebase-tools

Linux

  • automatic install script : Run curl -sL https://firebase.tools | uninstall=true bash

  • standalone binary : Delete the firebase binary that you downloaded. If you added its location to your PATH environment variable, be sure to remove it.

  • npm : Run npm uninstall -g firebase-tools

Use the CLI with CI systems

We recommend that you authenticate using Application Default Credentials when using the CLI with CI systems.

(Recommended) Use Application Default Credentials

The Firebase CLI will detect and use Application Default Credentials if they're set. The simplest way to authenticate the CLI in CI and other headless environments is to set up Application Default Credentials .

(Legacy) Use FIREBASE_TOKEN

Alternatively, you can authenticate using FIREBASE_TOKEN . This is less secure than Application Default Credentials and is no longer recommended.

  1. On a machine with a browser, install the Firebase CLI .

  2. Start the signin process by running the following command:

    firebase login:ci
  3. Visit the URL provided, then log in using a Google account.

  4. Print a new refresh token . The current CLI session will not be affected.

  5. Store the output token in a secure but accessible way in your CI system.

  6. Use this token when running firebase commands. You can use either of the following two options:

    • Option 1: Store the token as the environment variable FIREBASE_TOKEN . Your system will automatically use the token.

    • Option 2: Run all firebase commands with the --token TOKEN flag in your CI system.
      This is the order of precedence for token loading: flag, environment variable, desired Firebase project.

Initialize a Firebase project

Many common tasks performed using the CLI, such as deploying to a Firebase project, require a project directory . You establish a project directory using the firebase init command. A project directory is usually the same directory as your source control root, and after running firebase init , the directory contains a firebase.json configuration file.

To initialize a new Firebase project, run the following command from within your app's directory:

firebase init

The firebase init command steps you through setting up your project directory and some Firebase products. During project initialization, the Firebase CLI asks you to complete the following tasks:

  • Select a default Firebase project.

    This step associates the current project directory with a Firebase project so that project-specific commands (like firebase deploy ) run against the appropriate Firebase project.

    It's also possible to associate multiple Firebase projects (such as a staging project and a production project) with the same project directory.

  • Select Firebase products to set up in your Firebase project.

    This step prompts you to set configurations for specific files for the selected products or features. For more details on these configurations, refer to the specific product's documentation (for example, Hosting or Authentication ). Note that you can always run firebase init later to set up more Firebase products.

At the end of initialization, Firebase automatically creates the following two files at the root of your local app directory:

  • A firebase.json configuration file that lists your project configuration.

  • A .firebaserc file that stores your project aliases .

The firebase.json file

The firebase init command creates a firebase.json configuration file in the root of your project directory.

The firebase.json file is required to deploy assets with the Firebase CLI because it specifies which files and settings from your project directory are deployed to your Firebase project (like Hosting settings, Authentication provider configurations, security rules, and Cloud Functions configuration). Since some settings can be defined in either your project directory or the Firebase console, make sure that you resolve any potential deployment conflicts .

You can configure most Firebase Hosting options directly in the firebase.json file. However, for other Firebase services that can be deployed with the Firebase CLI , the firebase init command creates specific files where you can define settings for those services, such as an index.js file for Cloud Functions . You can also set up predeploy or postdeploy hooks in the firebase.json file.

The following firebase.json file is a comprehensive example showing configuration options for many Firebase services. It also demonstrates features like multi-codebase Cloud Functions , Local Emulator Suite setup, and a Remote Config template. Note that a firebase.json file for any given project will only contain configurations for the Firebase services set up for that specific project (for example, only Firebase Hosting and Cloud Functions ). Adding the $schema key enables validation and autocompletion in many code editors.

    {
      "$schema": "https://raw.githubusercontent.com/firebase/firebase-tools/master/schema/firebase-config.json",
      "hosting": {
        "public": "public",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "cleanUrls": true,
        "trailingSlash": false
      },
      "apphosting": {
        "backendId": "my-app",
        "rootDir": "backend",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ]
      },
      "firestore": {
        "rules": "firestore.rules",
        "indexes": "firestore.indexes.json"
      },
      "storage": {
        "rules": "storage.rules"
      },
      "database": {
        "rules": "database.rules.json"
      },
      "dataconnect": {
        "source": "dataconnect",
        "location": "us-central1"
      },
      "functions": [
        {
          "source": "functions",
          "codebase": "default",
          "ignore": [
            "**/.*",
            "**/node_modules/**"
          ],
          "predeploy": [
            "npm --prefix \"$RESOURCE_DIR\" run lint",
            "npm --prefix \"$RESOURCE_DIR\" run build"
          ]
        }
      ],
      "emulators": {
        "auth": {
          "port": 9099
        },
        "functions": {
          "port": 5001
        },
        "firestore": {
          "port": 8080
        },
        "hosting": {
          "port": 5000
        },
        "storage": {
          "port": 9199
        },
        "ui": {
          "enabled": true,
          "port": 4000
        },
        "singleProjectMode": true
      },
      "extensions": {
        "my-storage-resizer": "firebase/storage-resize-images@^0.1.0"
      },
      "auth": {
        "providers": {
          "anonymous": true,
          "emailPassword": true,
          "googleSignIn": {
            "oAuthBrandDisplayName": "My App",
            "supportEmail": "support@myapp.com"
          }
        }
      },
      "remoteconfig": {
        "template": "remoteconfig.template.json"
      }
    }

While firebase.json is used by default, you can pass the --config PATH flag to specify an alternate configuration file.

Configuration for multiple Cloud Firestore databases

When you run firebase init , your firebase.json file will contain a single firestore key corresponding to your project's default database, as shown in the preceding example.

If your project contains multiple Cloud Firestore databases, edit your firebase.json file to associate different Cloud Firestore Security Rules and database index source files with each database. Modify the file with a JSON array, with one entry for each database.

      "firestore": [
        {
          "database": "(default)",
          "rules": "firestore.default.rules",
          "indexes": "firestore.default.indexes.json"
        },
        {
          "database": "ecommerce",
          "rules": "firestore.ecommerce.rules",
          "indexes": "firestore.ecommerce.indexes.json"
        }
      ],

Cloud Functions files to ignore on deploy

At function deployment time, the CLI automatically specifies a list of files in the functions directory to ignore. This prevents deploying to the backend extraneous files that could increase the data size of your deployment.

The list of files ignored by default, shown in JSON format, is:

"ignore": [
  ".git",
  ".runtimeconfig.json",
  "firebase-debug.log",
  "firebase-debug.*.log",
  "node_modules"
]

If you add your own custom values for ignore in firebase.json , make sure that you keep (or add, if it is missing) the list of files shown in the preceding list.

Manage project aliases

You can associate multiple Firebase projects with the same project directory. For example, you might want to use one Firebase project for staging and another for production. By using different project environments, you can verify changes before deploying to production. The firebase use command lets you switch between aliases as well as create new aliases.

Add a project alias

When you select a Firebase project during project initialization , the project is automatically assigned the alias of default . However, to allow project-specific commands to run against a different Firebase project but still use the same project directory, run the following command from within your project directory:

firebase use --add

This command prompts you to select another Firebase project and assign the project as alias. Alias assignments are written to a .firebaserc file inside your project directory.

Use project aliases

To use assigned Firebase project aliases, run any of the following commands from within your project directory.

Командование Описание
firebase use View a list of defined aliases for your project directory
firebase use \
PROJECT_ID|ALIAS
Directs all commands to run against the specified Firebase project.
The CLI uses this project as the "active project".
firebase use --clear Clears the active project.

Run firebase use PROJECT_ID|ALIAS to set a new active project before running other CLI commands.

firebase use \
--unalias PROJECT_ALIAS
Removes an alias from your project directory.

You can override what's being used as the active project by passing the --project flag with any CLI command. As an example: You can set your CLI to run against a Firebase project that you've assigned the staging alias. If you want to run a single command against the Firebase project that you've assigned the prod alias, then you can run, for example, firebase deploy --project=prod .

Source control and project aliases

In general, you should check your .firebaserc file into source control to allow your team to share project aliases. However, for open source projects or starter templates, you should generally not check in your .firebaserc file.

If you have a development project that's for your use only, you can either pass the --project flag with each command or run firebase use PROJECT_ID without assigning an alias to the Firebase project.

Serve and test your Firebase project locally

You can view and test your Firebase project on locally hosted URLs before deploying to production. If you only want to test select features, you can use a comma-separated list in a flag on the firebase serve command.

Run the following command from the root of your local project directory if you want to do either of the following tasks:

firebase serve --only hosting

Emulate your project using local HTTP functions

Run any of the following commands from your project directory to emulate your project using local HTTP functions.

  • To emulate HTTP functions and hosting for testing on local URLs, use either of the following commands:

    firebase serve
    firebase serve --only functions,hosting // uses a flag
  • To emulate HTTP functions only, use the following command:

    firebase serve --only functions

Test from other local devices

By default, firebase serve only responds to requests from localhost . This means that you'll be able to access your hosted content from your computer's web browser but not from other devices on your network. If you'd like to test from other local devices, use the --host flag, like so:

firebase serve --host 0.0.0.0  // accepts requests to any host

Deploy to a Firebase project

The Firebase CLI manages deployment of code and assets to your Firebase project, including:

  • New releases of your Firebase Hosting sites
  • New, updated, or existing Cloud Functions for Firebase
  • New or updated schemas and connectors for Firebase SQL Connect
  • Security Rules for Firebase Realtime Database
  • Security Rules for Cloud Storage for Firebase
  • Security Rules for Cloud Firestore
  • Indexes for Cloud Firestore
  • Configuration for Authentication

To deploy to a Firebase project, run the following command from your project directory:

firebase deploy

You can optionally add a comment to each of your deployments. This comment will display with the other deployment information on your project's Firebase Hosting page . For example:

firebase deploy -m "Deploying the best new feature ever."

When you use the firebase deploy command, be aware of the following:

  • To deploy resources from a project directory, the project directory must have a firebase.json file. This file is automatically created for you by the firebase init command.

  • By default, firebase deploy creates a release for all deployable resources in your project directory. To deploy specific Firebase services or features, use partial deployment .

Deploy specific Firebase services

If you only want to deploy specific Firebase services or features, you can use a comma-separated list in a flag on the firebase deploy command. For example, the following command deploys Firebase Hosting content and Cloud Storage Security Rules .

firebase deploy --only hosting,storage

The following table lists the services and features available for partial deployment. The names in the flags correspond to the keys in your firebase.json configuration file.

Flag syntax Service or feature deployed
--only auth Authentication provider configuration
--only database Firebase Realtime Database Security Rules
--only dataconnect Firebase SQL Connect schemas and connectors
--only firestore Cloud Firestore Security Rules and indexes for all configured databases
--only functions Cloud Functions for Firebase
--only hosting Firebase Hosting content
--only storage Cloud Storage for Firebase Security Rules

Deployment conflicts for Security Rules

For Firebase Realtime Database , Cloud Storage for Firebase , and Cloud Firestore , you can define Security Rules either in your local project directory or in the Firebase console .

Another option to avoid deployment conflicts is to use partial deployment and only define Security Rules in the Firebase console.

Set up predeploy and postdeploy scripted tasks

You can connect shell scripts to the firebase deploy command to perform predeploy or postdeploy tasks. For example, a predeploy script could transpile TypeScript code into JavaScript, and a postdeploy hook could notify administrators of new site content deploys to Firebase Hosting .

To set up predeploy or postdeploy hooks, add bash scripts to your firebase.json configuration file. You can define brief scripts directly in the firebase.json file, or you can reference other files that are in your project directory.

For example, the following script is the firebase.json expression for a postdeploy task that sends a Slack message upon successful deployment to Firebase Hosting .

"hosting": {
  // ...

  "postdeploy": "./messageSlack.sh 'Just deployed to Firebase Hosting'",
  "public": "public"
}

The messageSlack.sh script file resides in the project directory and looks like this:

curl -X POST -H 'Content-type: application/json' --data '{"text":"$1"}'
     \https://SLACK_WEBHOOK_URL

You can set up predeploy and postdeploy hooks for any of the assets that you can deploy . Note that running firebase deploy triggers all the predeploy and postdeploy tasks defined in your firebase.json file. To run only those tasks associated with a specific Firebase service, use partial deployment commands .

Both predeploy and postdeploy hooks print the standard output and error streams of the scripts to the terminal. For failure cases, note the following:

  • If a predeploy hook fails to complete as expected, deployment is canceled.
  • If deployment fails for any reason, postdeploy hooks are not triggered.

переменные окружающей среды

Within scripts running in the predeploy and postdeploy hooks, the following environment variables are available:

  • $GCLOUD_PROJECT : The active project's project ID
  • $PROJECT_DIR : The root directory containing the firebase.json file
  • $RESOURCE_DIR : (For hosting and functions scripts only) The location of the directory that contains the Hosting or Cloud Functions resources to be deployed

Deployment quotas

It's possible (though unlikely) that you might exceed a quota that limits the rate or volume of your Firebase deployment operations. For example, when deploying very large numbers of functions, you might receive an HTTP 429 Quota error message. To solve such issues, try using partial deployment .

Roll back a deployment

You can roll back a Firebase Hosting deployment from your project's Firebase Hosting page by selecting the Rollback action for the chosen release.

It's not possible to roll back releases of Security Rules for Firebase Realtime Database , Cloud Storage for Firebase , or Cloud Firestore .

Справочник команд

CLI administrative commands

Командование Описание
помощь Displays help information about the CLI or specific commands.
инициализация Associates and sets up a new Firebase project in the current directory. This command creates a firebase.json configuration file in the current directory.
авторизоваться Authenticates the CLI with your Google Account. Requires access to a web browser.
To log into the CLI in remote environments that don't allow access to localhost , use the --no-localhost flag.
login:ci Generates an authentication token for use in non-interactive environments.
login:add Logs in an additional Google Account.
login:list Lists all authenticated Google Accounts.
login:use Sets the active Google Account.
выйти Signs out your Google Account from the CLI.
открыть Opens a browser to relevant project resources.
projects:list Lists all the Firebase projects to which you have access.
использовать Sets the active Firebase project for the CLI.
Manages project aliases .

Project management commands

Командование Описание
Management of Firebase projects
projects:addfirebase Adds Firebase resources and enables Firebase services in an existing Google Cloud project.
projects:create Creates a new Google Cloud project, then adds Firebase resources to the new project.
projects:list Lists all the Firebase projects to which you have access.
Management of Firebase Apps (iOS, Android, Web)
apps:create Creates a new Firebase App in the active project.
apps:list Lists the registered Firebase Apps in the active project.
apps:sdkconfig Prints the Firebase configuration of a Firebase App.
setup:web Deprecated. Instead, use apps:sdkconfig and specify web as the platform argument.
Prints the Firebase configuration of a Firebase Web App.
Management of SHA certificate hashes (Android only)
apps:android:sha:create \
FIREBASE_APP_ID SHA_HASH
Adds the specified SHA certificate hash to the specified Firebase Android App.
apps:android:sha:delete \
FIREBASE_APP_ID SHA_HASH
Deletes the specified SHA certificate hash from the specified Firebase Android App.
apps:android:sha:list \
FIREBASE_APP_ID
Lists the SHA certificate hashes for the specified Firebase Android App.

Deployment and local development

These commands let you deploy and interact with your Firebase Hosting site.

Командование Описание
развертывать Deploys code and assets from your project directory to the active project. For Firebase Hosting , a firebase.json configuration file is required.
служить Starts a local web server with your Firebase Hosting configuration. For Firebase Hosting , a firebase.json configuration file is required.

App Distribution commands

Командование Описание
appdistribution:distribute \
--app FIREBASE_APP_ID
Makes the build available to testers.
appdistribution:testers:add Adds testers to the project.
appdistribution:testers:remove Removes testers from the project.
appdistribution:testers:list Lists testers in the project.
appdistribution:groups:create Creates a tester group.
appdistribution:groups:delete Deletes a tester group.
appdistribution:groups:list Lists tester groups in the project.

App Hosting commands

Командование Описание
apphosting:backends:create \
--project PROJECT_ID \
--location REGION --app APP_ID
Creates the collection of managed resources linked to a single codebase that comprises an App Hosting backend. Optionally specify an existing Firebase Web app by its Firebase app ID.
apphosting:backends:get \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Retrieves specific details, including the public URL, of a backend.
apphosting:backends:list \
--project PROJECT_ID
Retrieves a list of all active backends associated with a project.
firebase apphosting:backends:delete \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Deletes a backend from the project.
firebase apphosting:config:export \
--project PROJECT_ID \
--secrets ENVIRONMENT_NAME
Exports secrets for use in app emulation.
Defaults to secrets stored in apphosting.yaml , or takes --secrets to specify any environment that has a corresponding apphosting. ENVIRONMENT_NAME .yaml file.
firebase apphosting:rollouts:create \
BACKEND_ID \
--git_branch BRANCH_NAME \
--git_commit COMMIT_ID
Creates a manually triggered rollout.
Optionally specify the latest commit to a branch or a specific commit. If no options are provided, prompts selection from a list of branches.
apphosting:secrets:set KEY --project PROJECT_ID \
--location REGION \
--data-file DATA_FILE_PATH
Stores secret material in Secret Manager.
Optionally provide a path from which to read secret data. Set to _ to read secret data from standard input.
apphosting:secrets:grantaccess KEY \
--backend BACKEND_ID \
--emails EMAILS \
--project PROJECT_ID \
--location REGION
Grants permissions to the provided secret(s) to service accounts , users, or groups, so that it can be accessed by App Hosting at build or run time. Can pass one or more secrets, separated by a comma.
apphosting:secrets:describe KEY \
--project PROJECT_ID
Gets the metadata for a secret and its versions.
firebase apphosting:secrets:access \
KEY[@version] \
--project PROJECT_ID
Accesses a secret value given the secret and its version. Defaults to accessing the latest version.

Authentication (user management) commands

Командование Описание
auth:export Exports the active project's user accounts to a JSON or CSV file. For more details, refer to the auth:import and auth:export page .
auth:import Imports the user accounts from a JSON or CSV file into the active project. For more details, refer to the auth:import and auth:export page .

Cloud Firestore commands

Командование Описание
firestore:locations

List available locations for your Cloud Firestore database.

firestore:databases:create DATABASE_ID

Create a database instance in native mode in your Firebase project.

The command takes the following flags:

  • --location <region name> to specify the deployment location for the database. Note you can run firebase firestore:locations to list available locations. Required .
  • --delete-protection <deleteProtectionState> to allow or prevent deletion of the specified database. Valid values are ENABLED or DISABLED . Defaults to DISABLED .
  • --point-in-time-recovery <PITRState> to set whether point-in-time recovery is enabled. Valid values are ENABLED or DISABLED . Defaults to DISABLED . Optional.
  • --edition <edition> to specify the database tier. For Enterprise features, set to enterprise .
  • --firestore-data-access <ENABLED|DISABLED> (Enterprise only) to control Firestore API availability. Defaults to ENABLED .
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (Enterprise only) to control MongoDB-compatible API availability. Defaults to DISABLED .
  • --realtime-updates <ENABLED|DISABLED> (Enterprise only) to enable or disable the "Watch" (realtime) feature. Requires --firestore-data-access to be ENABLED . Defaults to ENABLED .
firestore:databases:list

List databases in your Firebase project.

firestore:databases:get DATABASE_ID

Get database configuration for a specified database in your Firebase project.

For Enterprise databases, the output includes Edition , Firestore Data Access , MongoDB Compatible Data Access , and Realtime Updates status.

firestore:databases:update DATABASE_ID

Update database configuration of a specified database in your Firebase project.

At least one flag is required. The command takes the following flags:

  • --delete-protection <deleteProtectionState> to allow or prevent deletion of the specified database. Valid values are ENABLED or DISABLED . Defaults to DISABLED .
  • --point-in-time-recovery <PITRState> to set whether point-in-time recovery is enabled. Valid values are ENABLED or DISABLED . Defaults to DISABLED . Optional.
  • --firestore-data-access <ENABLED|DISABLED> (Enterprise only) to control Firestore API availability.
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (Enterprise only) to control MongoDB-compatible API availability.
  • --realtime-updates <ENABLED|DISABLED> (Enterprise only) to enable or disable the "Watch" (realtime) feature. Requires --firestore-data-access to be ENABLED .
firestore:databases:delete DATABASE_ID

Delete a database in your Firebase project.

firestore:indexes

List indexes for a database in your Firebase project.

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database for which to list indexes. If not provided, indexes are listed for the default database.
firestore:delete

Deletes documents in the active project's database. Using the CLI, you can recursively delete all the documents in a collection.

Note that deleting Cloud Firestore data with the CLI incurs read and delete costs. For more information, see Understand Cloud Firestore billing .

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database from which documents are deleted. If not specified, documents are deleted from the default database. Optional.

Cloud Functions for Firebase commands

Командование Описание
functions:config:clone Устарело.
Clones another project's environment into the active Firebase project.
functions:config:export Exports the active project's runtime configuration to Google Cloud Secret Manager .
functions:config:get Устарело.
Retrieves existing configuration values of the active project's Cloud Functions .
functions:config:set Устарело.
Stores runtime configuration values of the active project's Cloud Functions .
functions:config:unset Устарело.
Removes values from the active project's runtime configuration.
functions:delete \
FUNCTION_NAME
Deletes the specified function.
functions:list Lists deployed functions.
functions:log Reads logs from deployed Cloud Functions .
functions:secrets:access \
SECRET_NAME
Accesses a secret value given the secret and its version.
functions:secrets:destroy \
SECRET_NAME
Destroys a secret.
functions:secrets:get \
SECRET_NAME
Gets the metadata for a secret and its versions.
functions:secrets:prune Destroys unused secrets.
functions:secrets:set \
SECRET_NAME
Creates or updates a secret.
functions:shell Starts a local interactive shell for testing functions.

For more information, refer to the environment configuration documentation .

Crashlytics commands

Командование Описание
crashlytics:mappingfile:generateid \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML
Generates a unique mapping file ID in the specified Android resource (XML) file.
crashlytics:mappingfile:upload \
--app= FIREBASE_APP_ID \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML \
PATH/TO/MAPPING_FILE.TXT
Uploads a Proguard-compatible mapping (TXT) file for this app, and associates it with the mapping file ID declared in the specified Android resource (XML) file.
crashlytics:symbols:upload \
--app= FIREBASE_APP_ID \
PATH/TO/SYMBOLS
Generates a Crashlytics -compatible symbol file for native library crashes on Android and uploads it to Firebase servers.

SQL Connect commands

These commands and their use cases are covered in more detail in the SQL Connect CLI reference guide .

Командование Описание
dataconnect:services:list Lists all deployed SQL Connect services in your Firebase project.
dataconnect:sql:diff \
SERVICE_ID
For the specified service, displays the differences between a local SQL Connect schema and your Cloud SQL database schema.
dataconnect:sql:migrate \
--сила \
SERVICE_ID
Migrates your Cloud SQL database's schema to match your local SQL Connect schema.
dataconnect:sql:grant\
--role= ROLE \
--email= EMAIL \
SERVICE_ID
Grants the SQL role to the specified user or service account email.
For the --role flag, the SQL role to grant is one of: owner , writer , or reader .
For the --email flag, provide the email address of the user or service account to grant the role to.
dataconnect:sdk:generate Generates typed SDKs for your SQL Connect connectors.

Extensions commands

Командование Описание
наружный Displays information on how to use Firebase Extensions commands.
Lists the extension instances installed in the active project.
ext:configure \
EXTENSION_INSTANCE_ID
Reconfigures the parameter values of an extension instance in your extension manifest .
ext:info \
PUBLISHER_ID/EXTENSION_ID
Prints detailed information about an extension.
ext:install \
PUBLISHER_ID/EXTENSION_ID
Adds a new instance of an extension into your extension manifest .
ext:sdk:install Installs SDKs for defining extensions in functions.
ext:list Lists all the extension instances installed in a Firebase project.
Prints the instance ID for each extension.
ext:uninstall \
EXTENSION_INSTANCE_ID
Removes an extension instance from your extension manifest .
ext:update \
EXTENSION_INSTANCE_ID
Updates an extension instance to the latest version in your extension manifest .
ext:export Exports all installed extension instances from your project to your extension manifest .

Extensions publisher commands

Командование Описание
ext:dev:init Initializes a skeleton codebase for a new extension in the current directory.
ext:dev:list \
PUBLISHER_ID
Prints a list of all extensions uploaded by a publisher.
ext:dev:register Registers a Firebase project as an extensions publisher project .
ext:dev:deprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Deprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, deprecates all versions of that extension.
ext:dev:undeprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Undeprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, undeprecates all versions of that extension.
ext:dev:upload \
PUBLISHER_ID/EXTENSION_ID
Uploads a new version of an extension.
ext:dev:usage \
PUBLISHER_ID
Displays install counts and usage metrics for extensions uploaded by a publisher.

Hosting commands

Командование Описание
hosting:disable

Stops serving Firebase Hosting traffic for the active Firebase project.

Your project's Hosting URL will display a "Site Not Found" message after running this command.

Management of Hosting sites
firebase hosting:sites:create \
SITE_ID

Creates a new Hosting site in the active Firebase project using the specified SITE_ID

(Optional) Specify an existing Firebase Web App to associate with the new site by passing the following flag: --app FIREBASE_APP_ID

firebase hosting:sites:delete \
SITE_ID

Deletes the specified Hosting site

The CLI displays a confirmation prompt before deleting the site.

(Optional) Skip the confirmation prompt by passing the following flags: -f or --force

firebase hosting:sites:get \
SITE_ID

Retrieves information about the specified Hosting site

firebase hosting:sites:list

Lists all Hosting sites for the active Firebase project

Management of preview channels
firebase hosting:channel:create \
CHANNEL_ID

Creates a new preview channel in the default Hosting site using the specified CHANNEL_ID

This command doesn't deploy to the channel.

firebase hosting:channel:delete \
CHANNEL_ID

Deletes the specified preview channel

You cannot delete a site's live channel.

firebase hosting:channel:deploy \
CHANNEL_ID

Deploys your Hosting content and config to the specified preview channel

If the preview channel doesn't yet exist, this command creates the channel in the default Hosting site before deploying to the channel.

firebase hosting:channel:list Lists all channels (including the "live" channel) in the default Hosting site
firebase hosting:channel:open \
CHANNEL_ID
Opens a browser to the specified channel's URL or returns the URL if opening in a browser isn't possible
Version cloning
firebase hosting:clone \
SOURCE_SITE_ID : SOURCE_CHANNEL_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the most recently deployed version on the specified "source" channel to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

firebase hosting:clone \
SOURCE_SITE_ID :@ VERSION_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the specified version to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

You can find the VERSION_ID in the Hosting dashboard of the Firebase console.

Realtime Database commands

Note that you can create your initial, default Realtime Database instance in the Firebase console or by using the general firebase init workflow or the specific firebase init database flow.

Once instances are created, you can manage them as described in Manage and interact with specific instances using the CLI .

Командование Описание
database:get Fetches data from the active project's database and displays it as JSON. Supports querying on indexed data.
database:instances:create Creates a database instance with a specified instance name. Accepts the --location option for creating a database in a specified region. For region names to use with this option, see select locations for your project . If no database instance exists for the current project, you are prompted to run the firebase init flow to create an instance.
database:instances:list List all database instances for this project. Accepts the --location option for listing databases in a specified region. For region names to use with this option see select locations for your project .
database:profile Builds a profile of operations on the active project's database. For more details, refer to Realtime Database operation types .
database:push Pushes new data to a list at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:remove Deletes all data at a specified location in the active project's database.
database:set Replaces all data at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:update Performs a partial update at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.

Remote Config commands

Командование Описание
remoteconfig:versions:list \
--limit NUMBER_OF_VERSIONS
Lists the most recent ten versions of the template. Specify 0 to return all existing versions, or optionally pass the --limit option to limit the number of versions being returned.
remoteconfig:get \
--v, version_number VERSION_NUMBER
--o, output FILENAME
Gets the template by version (defaults to the latest version) and outputs the parameter groups, parameters, and condition names and version into a table. Optionally, you can write the output to a specified file with -o, FILENAME .
remoteconfig:rollback \
--v, version_number VERSION_NUMBER
--сила
Rolls back Remote Config template to a specified previous version number or defaults to the immediate previous version (current version -1). Unless --force is passed, prompts Y/N before proceeding to rollback.
remoteconfig:experiments:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config experiments for a project, with optional filtering, number of experiments to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:experiments:get \
EXPERIMENT_ID
Gets the details of the specified Remote Config experiment.
remoteconfig:experiments:delete \
EXPERIMENT_ID
Deletes the specified Remote Config experiment.
remoteconfig:rollouts:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config rollouts for a project, with optional filtering, number of rollouts to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:rollouts:get \
ROLLOUT_ID
Gets the details of the specified Remote Config rollout.
remoteconfig:rollouts:delete \
ROLLOUT_ID
Deletes the specified Remote Config rollout.
,

The Firebase CLI ( GitHub ) provides a variety of tools for managing, viewing, and deploying to Firebase projects.

Before using the Firebase CLI, set up a Firebase project .

Set up or update the CLI

Install the Firebase CLI

You can install the Firebase CLI using a method that matches your operating system, experience level, and/or use case. Regardless of how you install the CLI, you have access to the same functionality and the firebase command.

Windows macOS Linux

Windows

You can install the Firebase CLI for Windows using one of the following options:

Вариант Описание Recommended for...
standalone binary Download the standalone binary for the CLI. Then, you can access the executable to open a shell where you can run the firebase command. New developers

Developers not using or unfamiliar with Node.js
npm Use npm (the Node Package Manager) to install the CLI and enable the globally available firebase command. Developers using Node.js

standalone binary

To download and run the binary for the Firebase CLI, follow these steps:

  1. Download the Firebase CLI binary for Windows .

  2. Access the binary to open a shell where you can run the firebase command.

  3. Continue to log in and test the CLI .

npm

To use npm (the Node Package Manager) to install the Firebase CLI, follow these steps:

  1. Install Node.js using nvm-windows (the Node Version Manager). Installing Node.js automatically installs the npm command tools.

  2. Install the Firebase CLI via npm by running the following command:

    npm install -g firebase-tools

    This command enables the globally available firebase command.

  3. Continue to log in and test the CLI .

macOS or Linux

You can install the Firebase CLI for macOS or Linux using one of the following options:

Вариант Описание Recommended for...
automatic install script Run a single command that automatically detects your operating system, downloads the latest CLI release, then enables the globally available firebase command. New developers

Developers not using or unfamiliar with Node.js

Automated deploys in a CI/CD environment
standalone binary Download the standalone binary for the CLI. Then, you can configure and run the binary to suit your workflow. Fully customizable workflows using the CLI
npm Use npm (the Node Package Manager) to install the CLI and enable the globally available firebase command. Developers using Node.js

auto install script

To install the Firebase CLI using the automatic install script, follow these steps:

  1. Run the following cURL command:

    curl -sL https://firebase.tools | bash

    This script automatically detects your operating system, downloads the latest Firebase CLI release, then enables the globally available firebase command.

  2. Continue to log in and test the CLI .

For more examples and details about the automatic install script, refer to the script's source code at firebase.tools .

standalone binary

To download and run the binary for the Firebase CLI that's specific for your OS, follow these steps:

  1. Download the Firebase CLI binary for your OS: macOS | Linux

  2. (Optional) Set up the globally available firebase command.

    1. Make the binary executable by running chmod +x ./firebase_tools .
    2. Add the binary's path to your PATH.
  3. Continue to log in and test the CLI .

npm

To use npm (the Node Package Manager) to install the Firebase CLI, follow these steps:

  1. Install Node.js using nvm (the Node Version Manager).
    Installing Node.js automatically installs the npm command tools.

  2. Install the Firebase CLI via npm by running the following command:

    npm install -g firebase-tools

    This command enables the globally available firebase command.

  3. Continue to log in and test the CLI .

Log in and test the Firebase CLI

After installing the CLI, you must authenticate. Then you can confirm authentication by listing your Firebase projects.

  1. Log into Firebase using your Google account by running the following command:

    firebase login

    This command connects your local machine to Firebase and grants you access to your Firebase projects.

  2. Test that the CLI is properly installed and accessing your account by listing your Firebase projects. Run the following command:

    firebase projects:list

    The displayed list should be the same as the Firebase projects listed in the Firebase console .

Update to the latest CLI version

Generally, you want to use the most up-to-date Firebase CLI version.

How you update the CLI version depends on your operating system and how you installed the CLI.

Windows

macOS

  • automatic install script : Run curl -sL https://firebase.tools | upgrade=true bash

  • standalone binary : Download the new version , then replace it on your system

  • npm : Run npm install -g firebase-tools

Linux

  • automatic install script : Run curl -sL https://firebase.tools | upgrade=true bash

  • standalone binary : Download the new version , then replace it on your system

  • npm : Run npm install -g firebase-tools

Uninstall the Firebase CLI

How you uninstall the CLI depends on your operating system and how you installed the CLI.

Windows

  • standalone binary : Delete the firebase.exe binary that you downloaded.
  • npm : Run npm uninstall -g firebase-tools

macOS

  • automatic install script : Run curl -sL https://firebase.tools | uninstall=true bash

  • standalone binary : Delete the firebase binary that you downloaded. If you added its location to your PATH environment variable, be sure to remove it.

  • npm : Run npm uninstall -g firebase-tools

Linux

  • automatic install script : Run curl -sL https://firebase.tools | uninstall=true bash

  • standalone binary : Delete the firebase binary that you downloaded. If you added its location to your PATH environment variable, be sure to remove it.

  • npm : Run npm uninstall -g firebase-tools

Use the CLI with CI systems

We recommend that you authenticate using Application Default Credentials when using the CLI with CI systems.

(Recommended) Use Application Default Credentials

The Firebase CLI will detect and use Application Default Credentials if they're set. The simplest way to authenticate the CLI in CI and other headless environments is to set up Application Default Credentials .

(Legacy) Use FIREBASE_TOKEN

Alternatively, you can authenticate using FIREBASE_TOKEN . This is less secure than Application Default Credentials and is no longer recommended.

  1. On a machine with a browser, install the Firebase CLI .

  2. Start the signin process by running the following command:

    firebase login:ci
  3. Visit the URL provided, then log in using a Google account.

  4. Print a new refresh token . The current CLI session will not be affected.

  5. Store the output token in a secure but accessible way in your CI system.

  6. Use this token when running firebase commands. You can use either of the following two options:

    • Option 1: Store the token as the environment variable FIREBASE_TOKEN . Your system will automatically use the token.

    • Option 2: Run all firebase commands with the --token TOKEN flag in your CI system.
      This is the order of precedence for token loading: flag, environment variable, desired Firebase project.

Initialize a Firebase project

Many common tasks performed using the CLI, such as deploying to a Firebase project, require a project directory . You establish a project directory using the firebase init command. A project directory is usually the same directory as your source control root, and after running firebase init , the directory contains a firebase.json configuration file.

To initialize a new Firebase project, run the following command from within your app's directory:

firebase init

The firebase init command steps you through setting up your project directory and some Firebase products. During project initialization, the Firebase CLI asks you to complete the following tasks:

  • Select a default Firebase project.

    This step associates the current project directory with a Firebase project so that project-specific commands (like firebase deploy ) run against the appropriate Firebase project.

    It's also possible to associate multiple Firebase projects (such as a staging project and a production project) with the same project directory.

  • Select Firebase products to set up in your Firebase project.

    This step prompts you to set configurations for specific files for the selected products or features. For more details on these configurations, refer to the specific product's documentation (for example, Hosting or Authentication ). Note that you can always run firebase init later to set up more Firebase products.

At the end of initialization, Firebase automatically creates the following two files at the root of your local app directory:

  • A firebase.json configuration file that lists your project configuration.

  • A .firebaserc file that stores your project aliases .

The firebase.json file

The firebase init command creates a firebase.json configuration file in the root of your project directory.

The firebase.json file is required to deploy assets with the Firebase CLI because it specifies which files and settings from your project directory are deployed to your Firebase project (like Hosting settings, Authentication provider configurations, security rules, and Cloud Functions configuration). Since some settings can be defined in either your project directory or the Firebase console, make sure that you resolve any potential deployment conflicts .

You can configure most Firebase Hosting options directly in the firebase.json file. However, for other Firebase services that can be deployed with the Firebase CLI , the firebase init command creates specific files where you can define settings for those services, such as an index.js file for Cloud Functions . You can also set up predeploy or postdeploy hooks in the firebase.json file.

The following firebase.json file is a comprehensive example showing configuration options for many Firebase services. It also demonstrates features like multi-codebase Cloud Functions , Local Emulator Suite setup, and a Remote Config template. Note that a firebase.json file for any given project will only contain configurations for the Firebase services set up for that specific project (for example, only Firebase Hosting and Cloud Functions ). Adding the $schema key enables validation and autocompletion in many code editors.

    {
      "$schema": "https://raw.githubusercontent.com/firebase/firebase-tools/master/schema/firebase-config.json",
      "hosting": {
        "public": "public",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "cleanUrls": true,
        "trailingSlash": false
      },
      "apphosting": {
        "backendId": "my-app",
        "rootDir": "backend",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ]
      },
      "firestore": {
        "rules": "firestore.rules",
        "indexes": "firestore.indexes.json"
      },
      "storage": {
        "rules": "storage.rules"
      },
      "database": {
        "rules": "database.rules.json"
      },
      "dataconnect": {
        "source": "dataconnect",
        "location": "us-central1"
      },
      "functions": [
        {
          "source": "functions",
          "codebase": "default",
          "ignore": [
            "**/.*",
            "**/node_modules/**"
          ],
          "predeploy": [
            "npm --prefix \"$RESOURCE_DIR\" run lint",
            "npm --prefix \"$RESOURCE_DIR\" run build"
          ]
        }
      ],
      "emulators": {
        "auth": {
          "port": 9099
        },
        "functions": {
          "port": 5001
        },
        "firestore": {
          "port": 8080
        },
        "hosting": {
          "port": 5000
        },
        "storage": {
          "port": 9199
        },
        "ui": {
          "enabled": true,
          "port": 4000
        },
        "singleProjectMode": true
      },
      "extensions": {
        "my-storage-resizer": "firebase/storage-resize-images@^0.1.0"
      },
      "auth": {
        "providers": {
          "anonymous": true,
          "emailPassword": true,
          "googleSignIn": {
            "oAuthBrandDisplayName": "My App",
            "supportEmail": "support@myapp.com"
          }
        }
      },
      "remoteconfig": {
        "template": "remoteconfig.template.json"
      }
    }

While firebase.json is used by default, you can pass the --config PATH flag to specify an alternate configuration file.

Configuration for multiple Cloud Firestore databases

When you run firebase init , your firebase.json file will contain a single firestore key corresponding to your project's default database, as shown in the preceding example.

If your project contains multiple Cloud Firestore databases, edit your firebase.json file to associate different Cloud Firestore Security Rules and database index source files with each database. Modify the file with a JSON array, with one entry for each database.

      "firestore": [
        {
          "database": "(default)",
          "rules": "firestore.default.rules",
          "indexes": "firestore.default.indexes.json"
        },
        {
          "database": "ecommerce",
          "rules": "firestore.ecommerce.rules",
          "indexes": "firestore.ecommerce.indexes.json"
        }
      ],

Cloud Functions files to ignore on deploy

At function deployment time, the CLI automatically specifies a list of files in the functions directory to ignore. This prevents deploying to the backend extraneous files that could increase the data size of your deployment.

The list of files ignored by default, shown in JSON format, is:

"ignore": [
  ".git",
  ".runtimeconfig.json",
  "firebase-debug.log",
  "firebase-debug.*.log",
  "node_modules"
]

If you add your own custom values for ignore in firebase.json , make sure that you keep (or add, if it is missing) the list of files shown in the preceding list.

Manage project aliases

You can associate multiple Firebase projects with the same project directory. For example, you might want to use one Firebase project for staging and another for production. By using different project environments, you can verify changes before deploying to production. The firebase use command lets you switch between aliases as well as create new aliases.

Add a project alias

When you select a Firebase project during project initialization , the project is automatically assigned the alias of default . However, to allow project-specific commands to run against a different Firebase project but still use the same project directory, run the following command from within your project directory:

firebase use --add

This command prompts you to select another Firebase project and assign the project as alias. Alias assignments are written to a .firebaserc file inside your project directory.

Use project aliases

To use assigned Firebase project aliases, run any of the following commands from within your project directory.

Командование Описание
firebase use View a list of defined aliases for your project directory
firebase use \
PROJECT_ID|ALIAS
Directs all commands to run against the specified Firebase project.
The CLI uses this project as the "active project".
firebase use --clear Clears the active project.

Run firebase use PROJECT_ID|ALIAS to set a new active project before running other CLI commands.

firebase use \
--unalias PROJECT_ALIAS
Removes an alias from your project directory.

You can override what's being used as the active project by passing the --project flag with any CLI command. As an example: You can set your CLI to run against a Firebase project that you've assigned the staging alias. If you want to run a single command against the Firebase project that you've assigned the prod alias, then you can run, for example, firebase deploy --project=prod .

Source control and project aliases

In general, you should check your .firebaserc file into source control to allow your team to share project aliases. However, for open source projects or starter templates, you should generally not check in your .firebaserc file.

If you have a development project that's for your use only, you can either pass the --project flag with each command or run firebase use PROJECT_ID without assigning an alias to the Firebase project.

Serve and test your Firebase project locally

You can view and test your Firebase project on locally hosted URLs before deploying to production. If you only want to test select features, you can use a comma-separated list in a flag on the firebase serve command.

Run the following command from the root of your local project directory if you want to do either of the following tasks:

firebase serve --only hosting

Emulate your project using local HTTP functions

Run any of the following commands from your project directory to emulate your project using local HTTP functions.

  • To emulate HTTP functions and hosting for testing on local URLs, use either of the following commands:

    firebase serve
    firebase serve --only functions,hosting // uses a flag
  • To emulate HTTP functions only, use the following command:

    firebase serve --only functions

Test from other local devices

By default, firebase serve only responds to requests from localhost . This means that you'll be able to access your hosted content from your computer's web browser but not from other devices on your network. If you'd like to test from other local devices, use the --host flag, like so:

firebase serve --host 0.0.0.0  // accepts requests to any host

Deploy to a Firebase project

The Firebase CLI manages deployment of code and assets to your Firebase project, including:

  • New releases of your Firebase Hosting sites
  • New, updated, or existing Cloud Functions for Firebase
  • New or updated schemas and connectors for Firebase SQL Connect
  • Security Rules for Firebase Realtime Database
  • Security Rules for Cloud Storage for Firebase
  • Security Rules for Cloud Firestore
  • Indexes for Cloud Firestore
  • Configuration for Authentication

To deploy to a Firebase project, run the following command from your project directory:

firebase deploy

You can optionally add a comment to each of your deployments. This comment will display with the other deployment information on your project's Firebase Hosting page . For example:

firebase deploy -m "Deploying the best new feature ever."

When you use the firebase deploy command, be aware of the following:

  • To deploy resources from a project directory, the project directory must have a firebase.json file. This file is automatically created for you by the firebase init command.

  • By default, firebase deploy creates a release for all deployable resources in your project directory. To deploy specific Firebase services or features, use partial deployment .

Deploy specific Firebase services

If you only want to deploy specific Firebase services or features, you can use a comma-separated list in a flag on the firebase deploy command. For example, the following command deploys Firebase Hosting content and Cloud Storage Security Rules .

firebase deploy --only hosting,storage

The following table lists the services and features available for partial deployment. The names in the flags correspond to the keys in your firebase.json configuration file.

Flag syntax Service or feature deployed
--only auth Authentication provider configuration
--only database Firebase Realtime Database Security Rules
--only dataconnect Firebase SQL Connect schemas and connectors
--only firestore Cloud Firestore Security Rules and indexes for all configured databases
--only functions Cloud Functions for Firebase
--only hosting Firebase Hosting content
--only storage Cloud Storage for Firebase Security Rules

Deployment conflicts for Security Rules

For Firebase Realtime Database , Cloud Storage for Firebase , and Cloud Firestore , you can define Security Rules either in your local project directory or in the Firebase console .

Another option to avoid deployment conflicts is to use partial deployment and only define Security Rules in the Firebase console.

Set up predeploy and postdeploy scripted tasks

You can connect shell scripts to the firebase deploy command to perform predeploy or postdeploy tasks. For example, a predeploy script could transpile TypeScript code into JavaScript, and a postdeploy hook could notify administrators of new site content deploys to Firebase Hosting .

To set up predeploy or postdeploy hooks, add bash scripts to your firebase.json configuration file. You can define brief scripts directly in the firebase.json file, or you can reference other files that are in your project directory.

For example, the following script is the firebase.json expression for a postdeploy task that sends a Slack message upon successful deployment to Firebase Hosting .

"hosting": {
  // ...

  "postdeploy": "./messageSlack.sh 'Just deployed to Firebase Hosting'",
  "public": "public"
}

The messageSlack.sh script file resides in the project directory and looks like this:

curl -X POST -H 'Content-type: application/json' --data '{"text":"$1"}'
     \https://SLACK_WEBHOOK_URL

You can set up predeploy and postdeploy hooks for any of the assets that you can deploy . Note that running firebase deploy triggers all the predeploy and postdeploy tasks defined in your firebase.json file. To run only those tasks associated with a specific Firebase service, use partial deployment commands .

Both predeploy and postdeploy hooks print the standard output and error streams of the scripts to the terminal. For failure cases, note the following:

  • If a predeploy hook fails to complete as expected, deployment is canceled.
  • If deployment fails for any reason, postdeploy hooks are not triggered.

переменные окружающей среды

Within scripts running in the predeploy and postdeploy hooks, the following environment variables are available:

  • $GCLOUD_PROJECT : The active project's project ID
  • $PROJECT_DIR : The root directory containing the firebase.json file
  • $RESOURCE_DIR : (For hosting and functions scripts only) The location of the directory that contains the Hosting or Cloud Functions resources to be deployed

Deployment quotas

It's possible (though unlikely) that you might exceed a quota that limits the rate or volume of your Firebase deployment operations. For example, when deploying very large numbers of functions, you might receive an HTTP 429 Quota error message. To solve such issues, try using partial deployment .

Roll back a deployment

You can roll back a Firebase Hosting deployment from your project's Firebase Hosting page by selecting the Rollback action for the chosen release.

It's not possible to roll back releases of Security Rules for Firebase Realtime Database , Cloud Storage for Firebase , or Cloud Firestore .

Справочник команд

CLI administrative commands

Командование Описание
помощь Displays help information about the CLI or specific commands.
инициализация Associates and sets up a new Firebase project in the current directory. This command creates a firebase.json configuration file in the current directory.
авторизоваться Authenticates the CLI with your Google Account. Requires access to a web browser.
To log into the CLI in remote environments that don't allow access to localhost , use the --no-localhost flag.
login:ci Generates an authentication token for use in non-interactive environments.
login:add Logs in an additional Google Account.
login:list Lists all authenticated Google Accounts.
login:use Sets the active Google Account.
выйти Signs out your Google Account from the CLI.
открыть Opens a browser to relevant project resources.
projects:list Lists all the Firebase projects to which you have access.
использовать Sets the active Firebase project for the CLI.
Manages project aliases .

Project management commands

Командование Описание
Management of Firebase projects
projects:addfirebase Adds Firebase resources and enables Firebase services in an existing Google Cloud project.
projects:create Creates a new Google Cloud project, then adds Firebase resources to the new project.
projects:list Lists all the Firebase projects to which you have access.
Management of Firebase Apps (iOS, Android, Web)
apps:create Creates a new Firebase App in the active project.
apps:list Lists the registered Firebase Apps in the active project.
apps:sdkconfig Prints the Firebase configuration of a Firebase App.
setup:web Deprecated. Instead, use apps:sdkconfig and specify web as the platform argument.
Prints the Firebase configuration of a Firebase Web App.
Management of SHA certificate hashes (Android only)
apps:android:sha:create \
FIREBASE_APP_ID SHA_HASH
Adds the specified SHA certificate hash to the specified Firebase Android App.
apps:android:sha:delete \
FIREBASE_APP_ID SHA_HASH
Deletes the specified SHA certificate hash from the specified Firebase Android App.
apps:android:sha:list \
FIREBASE_APP_ID
Lists the SHA certificate hashes for the specified Firebase Android App.

Deployment and local development

These commands let you deploy and interact with your Firebase Hosting site.

Командование Описание
развертывать Deploys code and assets from your project directory to the active project. For Firebase Hosting , a firebase.json configuration file is required.
служить Starts a local web server with your Firebase Hosting configuration. For Firebase Hosting , a firebase.json configuration file is required.

App Distribution commands

Командование Описание
appdistribution:distribute \
--app FIREBASE_APP_ID
Makes the build available to testers.
appdistribution:testers:add Adds testers to the project.
appdistribution:testers:remove Removes testers from the project.
appdistribution:testers:list Lists testers in the project.
appdistribution:groups:create Creates a tester group.
appdistribution:groups:delete Deletes a tester group.
appdistribution:groups:list Lists tester groups in the project.

App Hosting commands

Командование Описание
apphosting:backends:create \
--project PROJECT_ID \
--location REGION --app APP_ID
Creates the collection of managed resources linked to a single codebase that comprises an App Hosting backend. Optionally specify an existing Firebase Web app by its Firebase app ID.
apphosting:backends:get \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Retrieves specific details, including the public URL, of a backend.
apphosting:backends:list \
--project PROJECT_ID
Retrieves a list of all active backends associated with a project.
firebase apphosting:backends:delete \
BACKEND_ID \
--project PROJECT_ID \
--location REGION
Deletes a backend from the project.
firebase apphosting:config:export \
--project PROJECT_ID \
--secrets ENVIRONMENT_NAME
Exports secrets for use in app emulation.
Defaults to secrets stored in apphosting.yaml , or takes --secrets to specify any environment that has a corresponding apphosting. ENVIRONMENT_NAME .yaml file.
firebase apphosting:rollouts:create \
BACKEND_ID \
--git_branch BRANCH_NAME \
--git_commit COMMIT_ID
Creates a manually triggered rollout.
Optionally specify the latest commit to a branch or a specific commit. If no options are provided, prompts selection from a list of branches.
apphosting:secrets:set KEY --project PROJECT_ID \
--location REGION \
--data-file DATA_FILE_PATH
Stores secret material in Secret Manager.
Optionally provide a path from which to read secret data. Set to _ to read secret data from standard input.
apphosting:secrets:grantaccess KEY \
--backend BACKEND_ID \
--emails EMAILS \
--project PROJECT_ID \
--location REGION
Grants permissions to the provided secret(s) to service accounts , users, or groups, so that it can be accessed by App Hosting at build or run time. Can pass one or more secrets, separated by a comma.
apphosting:secrets:describe KEY \
--project PROJECT_ID
Gets the metadata for a secret and its versions.
firebase apphosting:secrets:access \
KEY[@version] \
--project PROJECT_ID
Accesses a secret value given the secret and its version. Defaults to accessing the latest version.

Authentication (user management) commands

Командование Описание
auth:export Exports the active project's user accounts to a JSON or CSV file. For more details, refer to the auth:import and auth:export page .
auth:import Imports the user accounts from a JSON or CSV file into the active project. For more details, refer to the auth:import and auth:export page .

Cloud Firestore commands

Командование Описание
firestore:locations

List available locations for your Cloud Firestore database.

firestore:databases:create DATABASE_ID

Create a database instance in native mode in your Firebase project.

The command takes the following flags:

  • --location <region name> to specify the deployment location for the database. Note you can run firebase firestore:locations to list available locations. Required .
  • --delete-protection <deleteProtectionState> to allow or prevent deletion of the specified database. Valid values are ENABLED or DISABLED . Defaults to DISABLED .
  • --point-in-time-recovery <PITRState> to set whether point-in-time recovery is enabled. Valid values are ENABLED or DISABLED . Defaults to DISABLED . Optional.
  • --edition <edition> to specify the database tier. For Enterprise features, set to enterprise .
  • --firestore-data-access <ENABLED|DISABLED> (Enterprise only) to control Firestore API availability. Defaults to ENABLED .
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (Enterprise only) to control MongoDB-compatible API availability. Defaults to DISABLED .
  • --realtime-updates <ENABLED|DISABLED> (Enterprise only) to enable or disable the "Watch" (realtime) feature. Requires --firestore-data-access to be ENABLED . Defaults to ENABLED .
firestore:databases:list

List databases in your Firebase project.

firestore:databases:get DATABASE_ID

Get database configuration for a specified database in your Firebase project.

For Enterprise databases, the output includes Edition , Firestore Data Access , MongoDB Compatible Data Access , and Realtime Updates status.

firestore:databases:update DATABASE_ID

Update database configuration of a specified database in your Firebase project.

At least one flag is required. The command takes the following flags:

  • --delete-protection <deleteProtectionState> to allow or prevent deletion of the specified database. Valid values are ENABLED or DISABLED . Defaults to DISABLED .
  • --point-in-time-recovery <PITRState> to set whether point-in-time recovery is enabled. Valid values are ENABLED or DISABLED . Defaults to DISABLED . Optional.
  • --firestore-data-access <ENABLED|DISABLED> (Enterprise only) to control Firestore API availability.
  • --mongodb-compatible-data-access <ENABLED|DISABLED> (Enterprise only) to control MongoDB-compatible API availability.
  • --realtime-updates <ENABLED|DISABLED> (Enterprise only) to enable or disable the "Watch" (realtime) feature. Requires --firestore-data-access to be ENABLED .
firestore:databases:delete DATABASE_ID

Delete a database in your Firebase project.

firestore:indexes

List indexes for a database in your Firebase project.

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database for which to list indexes. If not provided, indexes are listed for the default database.
firestore:delete

Deletes documents in the active project's database. Using the CLI, you can recursively delete all the documents in a collection.

Note that deleting Cloud Firestore data with the CLI incurs read and delete costs. For more information, see Understand Cloud Firestore billing .

The command takes the following flag:

  • --database DATABASE_ID to specify the name of the database from which documents are deleted. If not specified, documents are deleted from the default database. Optional.

Cloud Functions for Firebase commands

Командование Описание
functions:config:clone Устарело.
Clones another project's environment into the active Firebase project.
functions:config:export Exports the active project's runtime configuration to Google Cloud Secret Manager .
functions:config:get Устарело.
Retrieves existing configuration values of the active project's Cloud Functions .
functions:config:set Устарело.
Stores runtime configuration values of the active project's Cloud Functions .
functions:config:unset Устарело.
Removes values from the active project's runtime configuration.
functions:delete \
FUNCTION_NAME
Deletes the specified function.
functions:list Lists deployed functions.
functions:log Reads logs from deployed Cloud Functions .
functions:secrets:access \
SECRET_NAME
Accesses a secret value given the secret and its version.
functions:secrets:destroy \
SECRET_NAME
Destroys a secret.
functions:secrets:get \
SECRET_NAME
Gets the metadata for a secret and its versions.
functions:secrets:prune Destroys unused secrets.
functions:secrets:set \
SECRET_NAME
Creates or updates a secret.
functions:shell Starts a local interactive shell for testing functions.

For more information, refer to the environment configuration documentation .

Crashlytics commands

Командование Описание
crashlytics:mappingfile:generateid \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML
Generates a unique mapping file ID in the specified Android resource (XML) file.
crashlytics:mappingfile:upload \
--app= FIREBASE_APP_ID \
--resource-file= PATH/TO/ANDROID_RESOURCE.XML \
PATH/TO/MAPPING_FILE.TXT
Uploads a Proguard-compatible mapping (TXT) file for this app, and associates it with the mapping file ID declared in the specified Android resource (XML) file.
crashlytics:symbols:upload \
--app= FIREBASE_APP_ID \
PATH/TO/SYMBOLS
Generates a Crashlytics -compatible symbol file for native library crashes on Android and uploads it to Firebase servers.

SQL Connect commands

These commands and their use cases are covered in more detail in the SQL Connect CLI reference guide .

Командование Описание
dataconnect:services:list Lists all deployed SQL Connect services in your Firebase project.
dataconnect:sql:diff \
SERVICE_ID
For the specified service, displays the differences between a local SQL Connect schema and your Cloud SQL database schema.
dataconnect:sql:migrate \
--сила \
SERVICE_ID
Migrates your Cloud SQL database's schema to match your local SQL Connect schema.
dataconnect:sql:grant\
--role= ROLE \
--email= EMAIL \
SERVICE_ID
Grants the SQL role to the specified user or service account email.
For the --role flag, the SQL role to grant is one of: owner , writer , or reader .
For the --email flag, provide the email address of the user or service account to grant the role to.
dataconnect:sdk:generate Generates typed SDKs for your SQL Connect connectors.

Extensions commands

Командование Описание
наружный Displays information on how to use Firebase Extensions commands.
Lists the extension instances installed in the active project.
ext:configure \
EXTENSION_INSTANCE_ID
Reconfigures the parameter values of an extension instance in your extension manifest .
ext:info \
PUBLISHER_ID/EXTENSION_ID
Prints detailed information about an extension.
ext:install \
PUBLISHER_ID/EXTENSION_ID
Adds a new instance of an extension into your extension manifest .
ext:sdk:install Installs SDKs for defining extensions in functions.
ext:list Lists all the extension instances installed in a Firebase project.
Prints the instance ID for each extension.
ext:uninstall \
EXTENSION_INSTANCE_ID
Removes an extension instance from your extension manifest .
ext:update \
EXTENSION_INSTANCE_ID
Updates an extension instance to the latest version in your extension manifest .
ext:export Exports all installed extension instances from your project to your extension manifest .

Extensions publisher commands

Командование Описание
ext:dev:init Initializes a skeleton codebase for a new extension in the current directory.
ext:dev:list \
PUBLISHER_ID
Prints a list of all extensions uploaded by a publisher.
ext:dev:register Registers a Firebase project as an extensions publisher project .
ext:dev:deprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Deprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, deprecates all versions of that extension.
ext:dev:undeprecate \
PUBLISHER_ID/EXTENSION_ID \
VERSION_PREDICATE
Undeprecates extension versions that match the version predicate.
A version predicate can be a single version (such as 1.0.0 ), or a range of versions (such as >1.0.0 ).
If no version predicate is provided, undeprecates all versions of that extension.
ext:dev:upload \
PUBLISHER_ID/EXTENSION_ID
Uploads a new version of an extension.
ext:dev:usage \
PUBLISHER_ID
Displays install counts and usage metrics for extensions uploaded by a publisher.

Hosting commands

Командование Описание
hosting:disable

Stops serving Firebase Hosting traffic for the active Firebase project.

Your project's Hosting URL will display a "Site Not Found" message after running this command.

Management of Hosting sites
firebase hosting:sites:create \
SITE_ID

Creates a new Hosting site in the active Firebase project using the specified SITE_ID

(Optional) Specify an existing Firebase Web App to associate with the new site by passing the following flag: --app FIREBASE_APP_ID

firebase hosting:sites:delete \
SITE_ID

Deletes the specified Hosting site

The CLI displays a confirmation prompt before deleting the site.

(Optional) Skip the confirmation prompt by passing the following flags: -f or --force

firebase hosting:sites:get \
SITE_ID

Retrieves information about the specified Hosting site

firebase hosting:sites:list

Lists all Hosting sites for the active Firebase project

Management of preview channels
firebase hosting:channel:create \
CHANNEL_ID

Creates a new preview channel in the default Hosting site using the specified CHANNEL_ID

This command doesn't deploy to the channel.

firebase hosting:channel:delete \
CHANNEL_ID

Deletes the specified preview channel

You cannot delete a site's live channel.

firebase hosting:channel:deploy \
CHANNEL_ID

Deploys your Hosting content and config to the specified preview channel

If the preview channel doesn't yet exist, this command creates the channel in the default Hosting site before deploying to the channel.

firebase hosting:channel:list Lists all channels (including the "live" channel) in the default Hosting site
firebase hosting:channel:open \
CHANNEL_ID
Opens a browser to the specified channel's URL or returns the URL if opening in a browser isn't possible
Version cloning
firebase hosting:clone \
SOURCE_SITE_ID : SOURCE_CHANNEL_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the most recently deployed version on the specified "source" channel to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

firebase hosting:clone \
SOURCE_SITE_ID :@ VERSION_ID \
TARGET_SITE_ID : TARGET_CHANNEL_ID

Clones the specified version to the specified "target" channel

This command also deploys to the specified "target" channel. If the "target" channel doesn't yet exist, this command creates a new preview channel in the "target" Hosting site before deploying to the channel.

You can find the VERSION_ID in the Hosting dashboard of the Firebase console.

Realtime Database commands

Note that you can create your initial, default Realtime Database instance in the Firebase console or by using the general firebase init workflow or the specific firebase init database flow.

Once instances are created, you can manage them as described in Manage and interact with specific instances using the CLI .

Командование Описание
database:get Fetches data from the active project's database and displays it as JSON. Supports querying on indexed data.
database:instances:create Creates a database instance with a specified instance name. Accepts the --location option for creating a database in a specified region. For region names to use with this option, see select locations for your project . If no database instance exists for the current project, you are prompted to run the firebase init flow to create an instance.
database:instances:list List all database instances for this project. Accepts the --location option for listing databases in a specified region. For region names to use with this option see select locations for your project .
database:profile Builds a profile of operations on the active project's database. For more details, refer to Realtime Database operation types .
database:push Pushes new data to a list at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:remove Deletes all data at a specified location in the active project's database.
database:set Replaces all data at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.
database:update Performs a partial update at a specified location in the active project's database. Takes input from a file, STDIN, or a command-line argument.

Remote Config commands

Командование Описание
remoteconfig:versions:list \
--limit NUMBER_OF_VERSIONS
Lists the most recent ten versions of the template. Specify 0 to return all existing versions, or optionally pass the --limit option to limit the number of versions being returned.
remoteconfig:get \
--v, version_number VERSION_NUMBER
--o, output FILENAME
Gets the template by version (defaults to the latest version) and outputs the parameter groups, parameters, and condition names and version into a table. Optionally, you can write the output to a specified file with -o, FILENAME .
remoteconfig:rollback \
--v, version_number VERSION_NUMBER
--сила
Rolls back Remote Config template to a specified previous version number or defaults to the immediate previous version (current version -1). Unless --force is passed, prompts Y/N before proceeding to rollback.
remoteconfig:experiments:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config experiments for a project, with optional filtering, number of experiments to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:experiments:get \
EXPERIMENT_ID
Gets the details of the specified Remote Config experiment.
remoteconfig:experiments:delete \
EXPERIMENT_ID
Deletes the specified Remote Config experiment.
remoteconfig:rollouts:list \
--filter EXPRESSION
--pageSize NUMBER
--pageToken TOKEN
Lists all Remote Config rollouts for a project, with optional filtering, number of rollouts to return per page (defaults to 10), and page token as the starting offset for the list.
remoteconfig:rollouts:get \
ROLLOUT_ID
Gets the details of the specified Remote Config rollout.
remoteconfig:rollouts:delete \
ROLLOUT_ID
Deletes the specified Remote Config rollout.