Use Remote Config in server environments

Firebase Remote Config now supports server-side configuration using the Firebase Admin Node.js SDK v12.1.0+. This new capability empowers you to dynamically manage the behavior and configuration of server-side applications using Remote Config. This includes serverless implementations like Cloud Functions.

Unlike Firebase client SDKs, which fetch a client-specific configuration derived from the Remote Config template, the server-side Remote Config SDK downloads a complete Remote Config template from Firebase. Your server can then evaluate the template with each incoming request and use its own logic to serve a customized response with very low latency.

With server-side Remote Config, you can:

  • Define configuration parameters for applications running on or accessed through your server, allowing for use cases like remotely configuring AI model parameters and prompts and other integrations, to ensure your API keys stay secure.
  • Dynamically adjust parameters in response to changes in your environment or other application changes, like updating LLM parameters and model endpoints.
  • Control costs by remotely updating the APIs your server calls.
  • Generate custom configurations on-the-fly for clients that access your server.

You can deploy server-side Remote Config on Cloud Run, Cloud Functions, or self-hosted server environments.

Before you begin

Follow the instructions in Add the Firebase Admin SDK to your server to create a Firebase project, set up a service account, and add the Firebase Admin Node.js SDK to your server.

Step 1: Initialize the Firebase Admin Node.js SDK and authorize API requests

When you initialize the Admin SDK with no parameters, the SDK uses Google Application Default Credentials and reads options from the GOOGLE_APPLICATION_CREDENTIALS environment variable. For example, to initialize the SDK and add Remote Config:

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

// Initialize Firebase
const firebaseApp = initializeApp();

Step 2: Identify default parameter values for your server application

Identify the variables in your app that you want to dynamically update with Remote Config. Then, consider which variables must be set by default in your application and what their default values should be. This ensures that your application runs successfully even if its connection to the Remote Config backend server is interrupted.

For example, if you are writing a server application that manages a generative AI function, you might set a default model name, prompt preamble, and a generative AI configuration, like the following:

Parameter name Description Type Default value
model_name Model API name String gemini-1.5-pro
preamble_prompt Prompt to prepend to the user's query String I'm a developer who wants to learn about Firebase and you are a helpful assistant who knows everything there is to know about Firebase!
generation_config Parameters to send to the model JSON {"stopSequences": ["I hope this helps"], "temperature": 0.7, "maxOutputTokens": 512, "topP": 0.1, "topK": 20}

Step 3: Configure your server application

After you've determined the parameters you want to use with Remote Config, configure your application to set default values, fetch the server-specific Remote Config template, and use its values. The following steps describe how to configure your Node.js application.

  1. Access and load the template.

    // Initialize server-side Remote Config
    const rc = getRemoteConfig(firebaseApp);
    const template = rc.initServerTemplate();
    
    // Load Remote Config
    await template.load();
    

    If you're using Node.js within a Cloud Functions, you can use the asynchronous getServerTemplate to fetch and load the template in a single step:

    // Initialize server-side Remote Config
    const rc = getRemoteConfig(firebaseApp);
    const template = await rc.getServerTemplate();
    
  2. To ensure that your application runs successfully even if its connection to the Remote Config backend server is interrupted, add default values for each parameter to your app. To do this, add a defaultConfig inside your initServerTemplate or getServerTemplate template function:

    const template = rc.initServerTemplate({
      defaultConfig: {
        model_name: "gemini-pro",
        generation_config: '{"stopSequences": [], "temperature": 0.7, "maxOutputTokens": 512, "topP": 0.1, "topK": 20}',
        preamble_prompt: "I'm a developer who wants to learn about Firebase and you are a helpful assistant who knows everything there is to know about Firebase!"
      },
    });
    
    // Load Remote Config
    await template.load();
    
  3. After the template loads, use template.evaluate() to import parameters and values from the template:

    // Add template parameters to config
    const config = template.evaluate();
    
  4. Optionally, if you set percentage conditions in your Remote Config template, define and provide the randomizationId that you want to use to evaluate your condition(s) within the template.evaluate() function.

    For example, you might set a Firebase installation ID as the randomizationId, or a user ID, to ensure that each user that contacts your server is added to the proper randomized group. The following example is a basic example, but you might configure your server to generate different randomizationIds for different client requests, to ensure that users are served consistent values from Remote Config based on their membership in percentage condition groups.

    For more information about percentage conditions, see User in random percentage.

    // Set the randomizationId
    const randomizationId = "2ac93c28-c459-4760-963d-a3974ec26c04"
    
    // Add template parameters to `config`. Evaluates the
    // template and returns the parameter value assigned to
    // the group assigned to the {randomizationId}.
    const config = template.evaluate({
      randomizationId
    });
    
  5. Next, extract the parameter values you need from the config constant. Use getters to cast the values from Remote Config into the expected format. The following types are supported:

    • Boolean: getBoolean
    • Object: getValue
    • Number: getNumber
    • String: getString

    For example, if you are implementing Vertex AI on your server and want to change the model and model parameters, you might want to configure parameters for model_name and generationConfig. Here's an example of how you could access Remote Config's values:

    // Replace defaults with values from Remote Config.
    const generationConfig =
      JSON.parse(
        config.getString('generation_config'));
    
    const is_ai_enabled = config.getBool('is_ai_enabled');
    
    const model = config.getString('model_name');
    
    // Generates a prompt comprised of the Remote Config
    // parameter and prepends it to the user prompt
    const prompt = `${config.getString('preamble_prompt')} ${req.query.prompt}`;
    
  6. If your server is long-running, as opposed to a serverless environment, use setInterval to periodically reload the template to ensure that you're periodically fetching the most up-to-date template from the Remote Config server.

Step 4: Set server-specific parameter values in Remote Config

Next, create a server Remote Config template and configure parameters and values to use in your app.

To create a server-specific Remote Config template:

  1. Open the Firebase console Remote Config parameters page and, from the Client/Server selector, select Server.
  2. Define Remote Config parameters with the same names and data types as the parameters that you defined in your app and provide values. These values will override the defaultConfig you set in Configure your server application when you fetch and evaluate the template and assign these values to your variables.
  3. Optionally, set percentage conditions to persistently apply a value to a random sample of instances. For more information about percentage conditions, see User in random percentage.
  4. When you've finished adding parameters, click Publish changes.
  5. Review the changes and click Publish changes again.

Step 5: Deploy as a Cloud Function or using Cloud Run

If your server application is lightweight and event-driven, you should consider deploying your code as a Cloud Function. For example, say you have an app that includes character dialogue powered by generative AI APIs like Google AI and Vertex AI. In this case, you could host your LLM serving logic in a Cloud Function that your app calls on-demand. Learn how to deploy your app as a Cloud Function at Get started: write, test, and deploy your first functions.

If your application is intended to be long-running (for example, a web app with assets), you might consider Cloud Run. To deploy your server app with Cloud Run, follow the guide at Quickstart: Deploy a Node.js service to Cloud Run.

For more information about the best use cases for Cloud Run and Cloud Functions, refer to Cloud Functions vs. Cloud Run: when to use one over the other.