Firebase is back at Google I/O on May 10! Register now

開始使用 Firebase 遠程配置

透過集合功能整理內容 你可以依據偏好儲存及分類內容。


您可以使用 Firebase Remote Config 在您的應用程序中定義參數並在雲端更新它們的值,從而允許您修改應用程序的外觀和行為而無需分發應用程序更新。本指南將引導您完成入門步驟並提供一些示例代碼,所有這些代碼都可以從firebase/quickstart-js GitHub 存儲庫中克隆或下載。

第一步:添加並初始化Remote Config SDK

  1. 如果您還沒有安裝 Firebase JS SDK 並初始化 Firebase

  2. 添加 Remote Config JS SDK 並初始化 Remote Config:

Web version 9

import { initializeApp } from "firebase/app";
import { getRemoteConfig } from "firebase/remote-config";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Remote Config and get a reference to the service
const remoteConfig = getRemoteConfig(app);

Web version 8

import firebase from "firebase/app";
import "firebase/remote-config";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Remote Config and get a reference to the service
const remoteConfig = firebase.remoteConfig();

此對像用於存儲應用內默認參數值、從遠程配置後端獲取更新的參數值,以及控制何時將獲取的值提供給您的應用。

第 2 步:設置最小提取間隔

在開發過程中,建議設置一個相對較低的最小獲取間隔。有關詳細信息,請參閱節流

Web version 9

remoteConfig.settings.minimumFetchIntervalMillis = 3600000;

Web version 8

remoteConfig.settings.minimumFetchIntervalMillis = 3600000;

第 3 步:設置應用內默認參數值

您可以在 Remote Config 對像中設置應用內默認參數值,以便您的應用在連接到 Remote Config 後端之前按預期運行,並且如果沒有在後端設置默認值,則默認值可用。

Web version 9

remoteConfig.defaultConfig = {
  "welcome_message": "Welcome"
};

Web version 8

remoteConfig.defaultConfig = {
  "welcome_message": "Welcome"
};

如果您已經配置了遠程配置後端參數值,則可以下載包含所有默認值的生成的 JSON 文件並將其包含在您的應用程序包中:

休息

curl --compressed -D headers -H "Authorization: Bearer token" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig:downloadDefaults?format=JSON -o remote_config_defaults.json

Firebase 控制台

  1. Parameters選項卡中,打開 Menu ,然後選擇Download default values
  2. 出現提示時,啟用.json for web ,然後單擊Download file

以下示例展示了您可以在應用中導入和設置默認值的兩種不同方式。第一個示例使用fetch ,它將向您的應用程序包中包含的默認文件發出 HTTP 請求:


  const rcDefaultsFile = await fetch('remote_config_defaults.json');
  const rcDefaultsJson = await rcDefaultsFile.json();
  remoteConfig.defaultConfig = rcDefaultsJson;
  

下一個示例使用require ,它在構建時將值編譯到您的應用程序中:

  let rcDefaults = require('./remote_config_defaults.json');
  remoteConfig.defaultConfig = rcDefaults;

第 4 步:獲取要在您的應用中使用的參數值

現在您可以從 Remote Config 對像中獲取參數值。如果您稍後在後端設置值,獲取它們,然後激活它們,這些值可用於您的應用程序。要獲取這些值,請調用getValue()方法,提供參數鍵作為參數。

Web version 9

import { getValue } from "firebase/remote-config";

const val = getValue(remoteConfig, "welcome_messsage");

Web version 8

const val = remoteConfig.getValue("welcome_messsage");

第 5 步:設置參數值

使用 Firebase 控制台或遠程配置後端 API ,您可以創建新的服務器端默認值,根據您所需的條件邏輯或用戶定位覆蓋應用內值。本部分將引導您完成 Firebase 控制台步驟以創建這些值。

  1. Firebase 控制台中,打開您的項目。
  2. 從菜單中選擇遠程配置以查看遠程配置儀表板。
  3. 使用與您在應用程序中定義的參數相同的名稱定義參數。對於每個參數,您可以設置一個默認值(最終將覆蓋應用內的默認值),您還可以設置條件值。要了解更多信息,請參閱遠程配置參數和條件

第 6 步:獲取並激活值

  1. 要從遠程配置後端獲取參數值,請調用fetchConfig()方法。您在後端設置的任何值都將被提取並緩存在遠程配置對像中。
  2. 要使獲取的參數值對您的應用程序可用,請調用activate()方法。

對於希望在一次調用中獲取和激活值的情況,請使用fetchAndActivate()如本例所示:

Web version 9

import { fetchAndActivate } from "firebase/remote-config";

fetchAndActivate(remoteConfig)
  .then(() => {
    // ...
  })
  .catch((err) => {
    // ...
  });

Web version 8

remoteConfig.fetchAndActivate()
  .then(() => {
    // ...
  })
  .catch((err) => {
    // ...
  });

由於這些更新的參數值會影響應用的行為和外觀,因此您應該在確保用戶流暢體驗的時間激活獲取的值,例如用戶下次打開您的應用時。有關更多信息和示例,請參閱遠程配置加載策略

節流

如果應用程序在短時間內獲取的次數太多,獲取調用可能會受到限制。在這種情況下,SDK 會拋出FETCH_THROTTLE錯誤。建議您捕獲此錯誤並以指數退避模式重試,在後續提取請求之間等待更長的間隔。

在應用程序開發期間,您可能希望非常頻繁地刷新緩存(每小時多次),以便在開發和測試應用程序時快速迭代。為了適應擁有眾多開發人員的項目的快速迭代,您可以在您的應用中臨時添加一個具有較低最小獲取間隔 ( Settings.minimumFetchIntervalMillis ) 的屬性。

遠程配置的默認和推薦生產獲取間隔為 12 小時,這意味著在 12 小時的窗口中不會從後端多次獲取配置,無論實際進行了多少次獲取調用。具體來說,最小抓取間隔按以下順序確定:

  1. Settings.minimumFetchIntervalMillis中的參數。
  2. 默認值為 12 小時。

下一步

If you haven't already, explore the Remote Config use cases , and take a look at some of the key concepts and advanced strategies documentation, including:

,


You can use Firebase Remote Config to define parameters in your app and update their values in the cloud, allowing you to modify the appearance and behavior of your app without distributing an app update. This guide walks you through the steps to get started and provides some sample code, all of which is available to clone or download from the firebase/quickstart-js GitHub repository.

Step 1: Add and initialize the Remote Config SDK

  1. If you haven't already, install the Firebase JS SDK and initialize Firebase .

  2. Add the Remote Config JS SDK and initialize Remote Config:

Web version 9

import { initializeApp } from "firebase/app";
import { getRemoteConfig } from "firebase/remote-config";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Remote Config and get a reference to the service
const remoteConfig = getRemoteConfig(app);

Web version 8

import firebase from "firebase/app";
import "firebase/remote-config";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Remote Config and get a reference to the service
const remoteConfig = firebase.remoteConfig();

This object is used to store in-app default parameter values, fetch updated parameter values from the Remote Config backend, and control when fetched values are made available to your app.

Step 2: Set minimum fetch interval

During development, it's recommended to set a relatively low minimum fetch interval. See Throttling for more information.

Web version 9

remoteConfig.settings.minimumFetchIntervalMillis = 3600000;

Web version 8

remoteConfig.settings.minimumFetchIntervalMillis = 3600000;

Step 3: Set in-app default parameter values

You can set in-app default parameter values in the Remote Config object, so that your app behaves as intended before it connects to the Remote Config backend, and so that default values are available if none are set on the backend.

Web version 9

remoteConfig.defaultConfig = {
  "welcome_message": "Welcome"
};

Web version 8

remoteConfig.defaultConfig = {
  "welcome_message": "Welcome"
};

If you have already configured Remote Config backend parameter values, you can download a generated JSON file that includes all default values and include it in your app bundle:

REST

curl --compressed -D headers -H "Authorization: Bearer token" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig:downloadDefaults?format=JSON -o remote_config_defaults.json

Firebase console

  1. In the Parameters tab, open the Menu , and select Download default values .
  2. When prompted, enable .json for web , then click Download file .

The following examples show two different ways you could import and set default values in your app. The first example uses fetch , which will make an HTTP request to the defaults file included in your app bundle:


  const rcDefaultsFile = await fetch('remote_config_defaults.json');
  const rcDefaultsJson = await rcDefaultsFile.json();
  remoteConfig.defaultConfig = rcDefaultsJson;
  

The next example uses require , which compiles the values into your app at build time:

  let rcDefaults = require('./remote_config_defaults.json');
  remoteConfig.defaultConfig = rcDefaults;

Step 4: Get parameter values to use in your app

Now you can get parameter values from the Remote Config object. If you later set values in the backend, fetch them, and then activate them, those values are available to your app.To get these values, call the getValue() method, providing the parameter key as an argument.

Web version 9

import { getValue } from "firebase/remote-config";

const val = getValue(remoteConfig, "welcome_messsage");

Web version 8

const val = remoteConfig.getValue("welcome_messsage");

Step 5: Set parameter values

Using the Firebase console or the Remote Config backend APIs , you can create new server-side default values that override the in-app values according to your desired conditional logic or user targeting. This section walks you through the Firebase console steps to create these values.

  1. In the Firebase console , open your project.
  2. Select Remote Config from the menu to view the Remote Config dashboard.
  3. Define parameters with the same names as the parameters that you defined in your app. For each parameter, you can set a default value (which will eventually override the in-app default value) and you can also set conditional values. To learn more, see Remote Config Parameters and Conditions .

Step 6: Fetch and activate values

  1. To fetch parameter values from the Remote Config backend, call the fetchConfig() method. Any values that you set on the backend are fetched and cached in the Remote Config object.
  2. To make fetched parameter values available to your app, call the activate() method.

For cases where you want to fetch and activate values in one call, use fetchAndActivate() as shown in this example:

Web version 9

import { fetchAndActivate } from "firebase/remote-config";

fetchAndActivate(remoteConfig)
  .then(() => {
    // ...
  })
  .catch((err) => {
    // ...
  });

Web version 8

remoteConfig.fetchAndActivate()
  .then(() => {
    // ...
  })
  .catch((err) => {
    // ...
  });

Because these updated parameter values affect the behavior and appearance of your app, you should activate the fetched values at a time that ensures a smooth experience for your user, such as the next time that the user opens your app. See Remote Config loading strategies for more information and examples.

Throttling

If an app fetches too many times in a short time period, fetch calls may be throttled. In such cases, the SDK throws a FETCH_THROTTLE error. You are recommended to catch this error and retry in exponential backoff mode, waiting longer intervals between subsequent fetch requests.

During app development, you might want to refresh the cache very frequently (many times per hour) to let you rapidly iterate as you develop and test your app. To accommodate rapid iteration on a project with numerous developers, you can temporarily add a property with a low minimum fetch interval ( Settings.minimumFetchIntervalMillis ) in your app.

The default and recommended production fetch interval for Remote Config is 12 hours, which means that configs won't be fetched from the backend more than once in a 12 hour window, regardless of how many fetch calls are actually made. Specifically, the minimum fetch interval is determined in the following order:

  1. The parameter in Settings.minimumFetchIntervalMillis .
  2. The default value of 12 hours.

下一步

If you haven't already, explore the Remote Config use cases , and take a look at some of the key concepts and advanced strategies documentation, including: