Configure your environment (1st gen)

Note: The 1st-gen functionality described in this page is alsosupported inCloud Functions (2nd gen) with improved features andperformance. For more information about 2nd gen, see theversion comparison. To go directlyto the 2nd gen guide for this feature, seeConfigure your environment.

Often you'll need additional configuration for your functions, such asthird-party API keys or tuneable settings. TheFirebase SDK forCloud Functions offersbuilt-in environment configuration to make it easy to store and retrieve thistype of data for your project.

You can choose between these options:

  • Parameterized configuration (recommended for most scenarios). This provides strongly-typed environmentconfiguration with parameters that are validated at deploy time, whichprevents errors and simplifies debugging.
  • File-based configuration ofenvironment variables. With this approach, you manually create adotenv file for loadingenvironment variables.

For most use cases, parameterized configuration is recommended. This approachmakes configuration values available both at runtime and deploy time, anddeployment is blocked unless all parameters have a valid value.Conversely, configuration with environment variables is not available at deploytime.

Caution: Environment configuration withfunctions.config was deprecated in version 6.0.0, and will be decommissioned in the next major release.After December 2025, new deployments withfunctions.config() will fail. If you are usingfunctions.config(),migrate your configuration as soon as possible.

Parameterized configuration

Cloud Functions for Firebase provides an interface for defining configurationparameters declaratively inside your codebase. The value of these parameters isavailable both during function deployment, when setting deployment and runtimeoptions, and during execution. This means that the CLI will block deploymentunless all parameters have a valid value.

To define parameters in your code, follow this model:

constfunctions=require('firebase-functions/v1');const{defineInt,defineString}=require('firebase-functions/params');// Define some parametersconstminInstancesConfig=defineInt('HELLO_WORLD_MININSTANCES');constwelcomeMessage=defineString('WELCOME_MESSAGE');// To use configured parameters inside the config for a function, provide them// directly. To use them at runtime, call .value() on them.exportconsthelloWorld=functions.runWith({minInstances:minInstancesConfig}).https.onRequest((req,res)=>{res.send(`${welcomeMessage.value()}! I am a function.`);});

When deploying a function with parameterized configuration variables, theFirebase CLI first attempts to load their values from local .env files. If theyare not present in those files and nodefault is set, the CLI will prompt forthe values during deployment, and then automatically save their values to a.env file named.env.<project_ID> in yourfunctions/ directory:

$firebasedeployifunctions:preparingcodebasedefaultfordeployment?EnterastringvalueforENVIRONMENT:prodifunctions:Writingnewparametervaluestodisk:.env.projectId…$firebasedeployifunctions:Loadedenvironmentvariablesfrom.env.projectId

Depending on your development workflow, it may be useful to add the generated.env.<project_ID> file to version control.

Using parameters in global scope

During deployment, your functions code is loaded and inspected before yourparameters have actual values. This means that fetching parameter values duringglobal scope results in deployment failure. For cases where you want to use aparameter to initialize a global value, use the initialization callbackonInit(). This callback runs before any functions run in production but isnot be called during deploy time, so it is a safe place to access a parameter'svalue.

const{GoogleGenerativeAI}=require('@google/generative-ai');const{defineSecret}=require('firebase-functions/params');const{onInit}=require('firebase-functions/v1');constapiKey=defineSecret('GOOGLE_API_KEY');letgenAI;onInit(()=>{genAI=newGoogleGenerativeAI(apiKey.value());})

Configure CLI behavior

Parameters can be configured with anOptions object that controls how the CLIwill prompt for values. The following example sets options to validate theformat of a phone number, to provide a simple selection option, and topopulate a selection option automatically from the Firebase project:

const{defineString}=require('firebase-functions/params');constwelcomeMessage=defineString('WELCOME_MESSAGE',{default:'Hello World',description:'The greeting that is returned to the caller of this function'});constonlyPhoneNumbers=defineString('PHONE_NUMBER',{input:{text:{validationRegex:/\d{3}-\d{3}-\d{4}/,validationErrorMessage:"Please entera phone number in the format XXX-YYY-ZZZZ"}}});constselectedOption=defineString('PARITY',{input:{select:{options:[{value:"odd"},{value:"even"}]}}})conststorageBucket=defineString('BUCKET',{input:{resource:{type:"storage.googleapis.com/Bucket"}},description:"This will automaticallypopulate the selector field with the deploying Cloud Project’sstorage buckets"})

Parameter types

Parameterized configuration provides strong typing for parameter values, andalso support secrets from Cloud Secret Manager. Supported types are:

  • Secret
  • String
  • Boolean
  • Integer
  • Float

See theparams namespace reference for information on the functions for defining parameters.

Parameter values and expressions

Firebase evaluates your parameters both at deploy time and while your functionis executing. Due to these dual environments, some extra care must be taken whencomparing parameter values, and when using them to setruntime optionsfor your functions.

To pass a parameter to your function as a runtime option, pass it directly:

constfunctions=require('firebase-functions/v1');const{defineInt}=require('firebase-functions/params');constminInstancesConfig=defineInt('HELLO\_WORLD\_MININSTANCES');exportconsthelloWorld=functions.runWith({minInstances:minInstancesConfig}).https.onRequest((req,res)=>{//…

Additionally, if you need to compare against a parameter in order to know whatoption to pick, you'll need to use built-in comparators instead ofchecking the value:

constfunctions=require('firebase-functions/v1');const{defineBool}=require('firebase-functions/params');constenvironment=params.defineString(ENVIRONMENT,{default:dev});// use built-in comparatorsconstminInstancesConfig=environment.equals('PRODUCTION').thenElse(10,1);exportconsthelloWorld=functions.runWith({minInstances:minInstancesConfig}).https.onRequest((req,res)=>{//…

Parameters and parameter expressions that are only used at runtime can beaccessed with theirvalue function:

constfunctions=require('firebase-functions/v1');const{defineString}=require('firebase-functions/params');constwelcomeMessage=defineString('WELCOME_MESSAGE');// To use configured parameters inside the config for a function, provide them// directly. To use them at runtime, call .value() on them.exportconsthelloWorld=functions.https.onRequest((req,res)=>{res.send(`${welcomeMessage.value()}! I am a function.`);});

Built-in parameters

The Cloud Functions SDK offers three pre-defined parameters, available fromthefirebase-functions/params subpackage:

  • projectID — the Cloud project in which the function is running.
  • databaseURL — the URL of the Realtime Database instance associated with the function (if enabled on the Firebase project).
  • storageBucket — the Cloud Storage bucket associated with the function (if enabled on the Firebase project).

These function like user-defined stringparameters in all respects, except that, since their values are always known tothe Firebase CLI, their values will never be prompted for on deployment norsaved to.env files.

Secret parameters

Parameters of typeSecret, defined usingdefineSecret(), represent stringparameters which have a value stored in Cloud Secret Manager. Instead ofchecking against a local.env file and writing a new value to the file ifmissing, secret parameters check against existence in Cloud Secret Manager, andinteractively prompt for the value of a new secret during deployment.

Secret parameters defined in this way must be bound to individual functions thatshould have access to them:

constfunctions=require('firebase-functions/v1');const{defineSecret}=require('firebase-functions/params');constdiscordApiKey=defineSecret('DISCORD_API_KEY');exportconstpostToDiscord=functions.runWith({secrets:[discordApiKey]}).https.onRequest((req,res)=>{constapiKey=discordApiKey.value();//…
Note: Because the functions emulator runs all functions for a codebase in asingle process, it currently always injects secrets into the process and doesnot respect secret bindings.

Environment variables

Cloud Functions for Firebase supports thedotenv file format for loading environment variables specified in a.env file to yourapplication runtime. Once deployed, the environment variables can be read via theprocess.envinterface.

Note: If you prefer a flow in which function deployment is blocked when anyvalues are missing from your environment configuration, consider usingparameterized configuration.

To configure your environment this way, create a.env file in your project,add the desired variables, and deploy:

  1. Create a.env file in yourfunctions/ directory:

    #Directorylayout:#my-project/#firebase.json#functions/#.env#package.json#index.js
  2. Open the.env file for edit, and add the desired keys. For example:

    PLANET=EarthAUDIENCE=Humans
  3. Deploy functions and verify that environment variables were loaded:

    firebase deploy --only functions# ...# i functions: Loaded environment variables from .env.# ...

Once your your custom environment variables are deployed,your function code can access them withprocess.envsyntax:

// Responds with "Hello Earth and Humans"exports.hello=functions.https.onRequest((request,response)=>{response.send(`Hello${process.env.PLANET} and${process.env.AUDIENCE}`);});

Deploying multiple sets of environment variables

If you need an alternative set of environment variables for your Firebaseprojects (such as staging vs production), create a.env.<project oralias> file and write yourproject-specific environment variables there. The environment variables from.env and project-specific.env files (if they exist)will be included in all deployed functions.

For example, a project could include these three files containing slightlydifferent values for development and production:

.env.env.dev.env.prod
PLANET=Earth

AUDIENCE=Humans

AUDIENCE=Dev HumansAUDIENCE=Prod Humans

Given the values in those separate files, the set of environment variablesdeployed with your functions will vary depending on your target project:

$ firebase use dev$ firebase deploy --only functionsi functions: Loaded environment variables from .env, .env.dev.# Deploys functions with following user-defined environment variables:#   PLANET=Earth#   AUDIENCE=Dev Humans$ firebase use prod$ firebase deploy --only functionsi functions: Loaded environment variables from .env, .env.prod.# Deploys functions with following user-defined environment variables:#   PLANET=Earth#   AUDIENCE=Prod Humans

Reserved environment variables

Some environment variable keys are reserved for internal use. Do not use any ofthese keys in your.env files:

  • All keys starting with X_GOOGLE_
  • All keys starting EXT_
  • All keys starting with FIREBASE_
  • Any key from the following list:
  • CLOUD_RUNTIME_CONFIG
  • ENTRY_POINT
  • GCP_PROJECT
  • GCLOUD_PROJECT
  • GOOGLE_CLOUD_PROJECT
  • FUNCTION_TRIGGER_TYPE
  • FUNCTION_NAME
  • FUNCTION_MEMORY_MB
  • FUNCTION_TIMEOUT_SEC
  • FUNCTION_IDENTITY
  • FUNCTION_REGION
  • FUNCTION_TARGET
  • FUNCTION_SIGNATURE_TYPE
  • K_SERVICE
  • K_REVISION
  • PORT
  • K_CONFIGURATION

Store and access sensitive configuration information

Environment variables stored in.env files can be used for functionconfiguration, but you should not consider them a secure way to store sensitiveinformation such as database credentials or API keys. This is especiallyimportant if you check your.env files into source control.

To help you store sensitive configuration information,Cloud Functions for Firebaseintegrates withGoogle CloudSecret Manager.This encrypted service stores configuration values securely, whilestill allowing easy access from your functions when needed.

Note:Secret Manager is a paid service, with a free tier. SeeHow secrets are billed for more information.

Create and use a secret

To create a secret, use theFirebase CLI.

Note: Make sure not to use anyreserved environment variable namesfor your secrets.

To create and use a secret:

  1. From the root of your local project directory, run the following command:

    firebase functions:secrets:setSECRET_NAME

  2. Enter a value forSECRET_NAME.

    The CLI echoes a success message and warns that you must deploy functionsfor the change to take effect.

  3. Before deploying, make sure your functions code allows the function to access the secret using therunWith parameter:

    exports.processPayment = functions  // Make the secret available to this function  .runWith({ secrets: ["SECRET_NAME"] })  .onCall((data, context) => {    const myBillingService = initializeBillingService(      // reference the secret value      process.env.SECRET_NAME    );    // Process the payment  });
  4. DeployCloud Functions:

    firebase deploy --only functions

Now you'll be able to access it like any other environment variable.Conversely, if another function that does not specify the secret inrunWith tries to access the secret, it receives an undefined value:

exports.anotherEndpoint=functions.https.onRequest((request,response)=>{response.send(`The secret API key is${process.env.SECRET_NAME}`);// responds with "The secret API key is undefined" because the `runWith` parameter is missing});

Once your function is deployed, it will have access to the secret value.Onlyfunctions that specifically include a secret in theirrunWith parameter willhave access to that secret as an environment variable. This helps you make surethat secret values are only available where they're needed, reducing the risk ofaccidentally leaking a secret.

Managing secrets

Use theFirebase CLI to manage your secrets. While managing secrets this way,keep in mind that some CLI changes require you to modify and/or redeployassociated functions. Specifically:

  • Whenever you set a new value for a secret, you must redeploy allfunctions that referencethat secret for them to pick up the latest value.
  • If you delete a secret, make sure that none of your deployed functionsreferences that secret. Functions that use a secret value that has beendeleted will fail silently.

Here's a summary of theFirebase CLI commands for secret management:

# Change the value of an existing secretfirebase functions:secrets:setSECRET_NAME# View the value of a secretfunctions:secrets:accessSECRET_NAME# Destroy a secretfunctions:secrets:destroySECRET_NAME# View all secret versions and their statefunctions:secrets:getSECRET_NAME# Automatically clean up all secrets that aren't referenced by any of your functionsfunctions:secrets:prune

For theaccess anddestroy commands, you can provide the optional versionparameter to manage a particular version. For example:

functions:secrets:accessSECRET_NAME[@VERSION]

For more information about these operations, pass-h with the command toview CLI help.

How secrets are billed

Secret Manager allows 6 active secretversionsat no cost. This means that you can have 6 secrets per month in a Firebaseproject at no cost.

By default, theFirebase CLI attempts to automatically destroy unused secretversions where appropriate, such as when you deploy functions with a new versionof the secret. Also, you can actively clean up unused secrets usingfunctions:secrets:destroy andfunctions:secrets:prune.

Secret Manager allows 10,000 unbilled monthly access operations on asecret. Function instances read only the secrets specified in theirsecretsoption every time they cold start. If you have a lot of function instancesreading a lot of secrets, your project may exceed this allowance, at which pointyou'll be charged $0.03 per 10,000 access operations.

For more information, seeSecret Manager Pricing.

Emulator support

Environment configuration with dotenv is designed to interoperate with alocalCloud Functions emulator.

When using a localCloud Functions emulator, you can override environmentvariables for your project by setting up a.env.local file. Contents of.env.local take precedence over.env and the project-specific.env file.

For example, a project could include these three files containing slightlydifferent values for development and local testing:

.env.env.dev.env.local
PLANET=Earth

AUDIENCE=Humans

AUDIENCE=Dev HumansAUDIENCE=Local Humans

When started in the local context, the emulator loads the environmentvariables as shown:

$firebaseemulators:startiemulators:Startingemulators:functions# Starts emulator with following environment variables:#  PLANET=Earth#  AUDIENCE=Local Humans

Secrets and credentials in theCloud Functions emulator

TheCloud Functions emulator supports the use of secrets tostore and access sensitive configuration information.By default, the emulator will try to access your production secrets usingapplication default credentials.In certain situations like CI environments, the emulator may fail to accesssecret values due to permission restrictions.

Similar toCloud Functions emulator support for environment variables, you canoverride secrets values by setting up a.secret.local file. This makes iteasy for you to test your functions locally, especially if you don't have accessto the secret value.

Migrate from runtime configuration

Thefunctions.config API is deprecated will be decommissioned in March 2027.After that date, deployments withfunctions.config will fail.

To prevent deployment failures, migrate your configuration to Cloud Secret Manager using theFirebase CLI. This is strongly recommended asthe most efficient and secure way to migrate your configuration.

  1. Export configuration with theFirebase CLI

    Use theconfig export command to export your existing environment config to anew secret in Cloud Secret Manager:

    $firebasefunctions:config:exportiThiscommandretrievesyourRuntimeConfigvalues(accessedviafunctions.config())andexportsthemasaSecretManagersecret.iFetchingyourexistingfunctions.config()fromyourproject...Fetchedyourexistingfunctions.config().iConfigurationtobeexported:⚠Thismaycontainsensitivedata.Donotsharethisoutput.{...}Whatwouldyouliketonamethenewsecretforyourconfiguration?RUNTIME_CONFIG✔Creatednewsecretversionprojects/project/secrets/RUNTIME_CONFIG/versions/1```
  2. Update function code to bind secrets

    To use configuration stored in the new secret in Cloud Secret Manager, use thedefineJsonSecret API in your function source. Also, make sure that secrets arebound to all functions that need them.

    Before

    constfunctions=require("firebase-functions/v1");exports.myFunction=functions.https.onRequest((req,res)=>{constapiKey=functions.config().someapi.key;// ...});

    After

    const{onRequest}=require("firebase-functions/v2/https");const{defineJsonSecret}=require("firebase-functions/params");constconfig=defineJsonSecret("RUNTIME_CONFIG");exports.myFunction=onRequest(// Bind secret to your function{secrets:[config]},(req,res)=>{// Access secret values via .value()constapiKey=config.value().someapi.key;// ...});
  3. Deploy Functions

    Deploy your updated functions to apply the changes and bind the secretpermissions.

    firebasedeploy--onlyfunctions:<your-function-name>

Automatically populated environment variables

There are environment variables that are automatically populated in thefunctions runtime and in locally emulated functions. These includethose populated byGoogle Cloud,as well as a Firebase-specific environment variable:

process.env.FIREBASE_CONFIG: Provides the following Firebase project config info:

{  databaseURL: 'https://DATABASE_NAME.firebaseio.com',  storageBucket: 'PROJECT_ID.firebasestorage.app',  projectId: 'PROJECT_ID'}

Note that the values in your actual Firebase configuration might vary dependingon the resources you've provisioned in your project.

This configuration is applied automatically when you initialize the FirebaseAdmin SDK with no arguments. If you are writing functions in JavaScript,initialize like this:

constadmin=require('firebase-admin');admin.initializeApp();

If you are writing functions in TypeScript, initialize like this:

import*asfunctionsfrom'firebase-functions/v1';import*asadminfrom'firebase-admin';import'firebase-functions/v1';admin.initializeApp();

If you need to initialize the Admin SDK with the default project configurationusing service account credentials, you can load the credentials from a file andadd them toFIREBASE_CONFIG like this:

serviceAccount=require('./serviceAccount.json');constadminConfig=JSON.parse(process.env.FIREBASE_CONFIG);adminConfig.credential=admin.credential.cert(serviceAccount);admin.initializeApp(adminConfig);

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-06 UTC.