19

I am trying to move the tiny node-express app I made into Firebase functions.

The files have dotenv variables. Earlier I thought If I just deployed and put the dotenv in dependency, It would work but that didn't happen so...

So, I went to the environment configuration article of Firebase to understand how I can set .env

Which states to set things by doing something like this

firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"

But I have so many environment configurations and doing that some what seems to be a cumbersome task.

So let's say this is an environment file

# App port Address
PORT = 8080

# Google Secret 
GOOGLE_CALLBACK_URL =   http://localhost:8080/auth/google/callback
GOOGLE_CLIENT_ID = 40xxxx8-xxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET = lxxxxxxxxxxxxO

# Client Address 
CLIENT_ADDRESS = http://localhost:3000/


# Meetup Secret 
MEETUP_CALLBACK_URL = http://localhost:8080/auth/meetup/callback
MEETUP_CLIENT_ID = exxxxxxxxxxxxxxxxxxxt
MEETUP_CLIENT_SECRET = sxxxxxxxxxxxxxxxxt

#EventBrite Secret 
EVENTBRITE_CALLBACK_URL = http://localhost:8080/auth/eventbrite/callback
EVENTBRITE_CLIENT_ID = UxxxxxxxxxxxxxN
EVENTBRITE_CLIENT_SECRET = Nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx4 

How Can I best set up so that when I do firebase firebase serve --only functions,hosting it doesn't throw any errors such as

OAuth2Strategy requires a clientID option

9 Answers 9

35

As of Feb 16, 2022 Firebase now supports .env, .env.prod, .env.dev, .env.local files natively!

https://firebase.google.com/docs/functions/config-env

Set your variables in the corresponding environment, and then run firebase use dev or firebase use prod before you deploy.

Your variables can be accessed via process.env.VARIABLE_NAME

1
  • 3
    Amazing new feature! One gotchya - I needed to have an .env.local when using the local emulators. I just wasted an hour thinking it wasn't working when I just didn't have this file. I also recommend the new $ firebase functions:config:export command to download your existing environment through firebase-tools.
    – digibake
    Commented Feb 23, 2022 at 16:13
6

UPDATED 2019-06-04

I'm very sorry. This solution is wrong.

I found the correct way.

https://stackoverflow.com/a/45064266/1872674

You should put a .runtimeconfig.json into the functions directory. Your dotenv variables move to .runtimeconfig.json with json format.


This is my solution.

const functionConfig = () => {
    if (process.env.RUN_LOCALLY) {
        const fs = require('fs');
        return JSON.parse(fs.readFileSync('.env.json'));
    } else {
      return functions.config();
    }
};

The functionConfig() was called by your Firebase Function.

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("someservice id is: " + functionConfig().someservice.id);
});

.env.json is like:

{
  "someservice": {
    "key":"THE API KEY",
    "id":"THE CLIENT ID"
  }
}

Finally, run the command with the RUN_LOCALLY variable.

RUN_LOCALLY=1 firebase serve

When we will deploy functions, don't forget to update the environment configuration in Firebase using the .env.json.

1
  • 2
    See the answer from @d-_-b which is more up to date Commented Apr 5, 2022 at 15:34
3

The Firebase CLI currently doesn't allow you to set process environment variables on deployment. This may change in the future. The configuration vars it supports today (that you linked to) are not actually process environment variables - they stored somewhere else that's not actually the process environment.

If you absolutely need to be able to set process environment variables, you will have to deploy your function with gcloud, which means that you also won't be able to use the firebase-functions module to define your function. Start with the Google Cloud Functions documentation to learn about deployment from a Cloud perspective.

If you want to use the Firebase tools, I'd recommend that you find a different way to configure your function that doesn't involve process environment variables.

3

If you want to have your functions use the process.env variables, you you can set them by going to google cloud console and cloud functions. You will be able to find the deployed firebase functions there. You can select each function one by one and then set the environment variables there.

2

what I did was create a env.json file into functions FOLDER:

//env.json
{
   "send_email_config": {
       "FOW_ADMIN_EMAIL": "[email protected]",
       "FOW_ADMIN_EMAIL_PASSWORD": "adminPassExample",
       "FOW_ADMIN_RECEIVER_EMAIL": "[email protected]"
   }
}

then I created a file called env.js where I created a function to return the value of functions.config() which is kind of env module

//env.js
// TO UPDATE functions.config().env RUN INSIDE functions FOLDER: 
// firebase functions:config:set env="$(cat env.json)" 

const functions = require('firebase-functions');

const getEnvConfig = () => {
    /* 
       I return functions.config().env cause I set the env.json values into env 
       property running firebase functions:config:set env="$(cat env.json)"
    */
    return functions.config().env
}

exports.getEnvConfig = getEnvConfig;

exports.PROCESS_ENV = getEnvConfig();

then I just call PROCESS_ENV to access the values that I set on env.json file for example:

const { PROCESS_ENV } = require('./utils/env');

exports.mailCredentials = {
    main: {
        email: PROCESS_ENV.send_email_config.FOW_ADMIN_EMAIL,
        password: PROCESS_ENV.send_email_config.FOW_ADMIN_EMAIL_PASSWORD
    },
    receiver: {
        email: PROCESS_ENV.send_email_config.FOW_ADMIN_RECEIVER_EMAIL
    }
}

IMPORTANT!!!!

for this to work you have to deploy functions.config().env with the values of the env.json file

to deploy functions.config().env you just have to run INSIDE the functions FOLDER the next command: firebase functions:config:set env="$(cat env.json)"

and also don't forget to add env.json in your .gitignore

if you have firebase functions FOLDER inside your react project just add */env.json into your react .gitignore file

1
0

your .env file need to be in the "functions" folder

Here you have the documentation about this

https://firebase.google.com/docs/functions/config-env

you can access variables like this :

This is your .env :

PLANET=Earth
AUDIENCE=Humans

and a firebase functions

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

For your local environment you can have a .env.local file and the contents of .env.local take precedence over .env when you are using the emulators suite

1
  • thanks for that : your .env file need to be in the "functions" folder
    – diAz
    Commented Apr 26, 2023 at 20:54
0

Do not use env to store secrets as it is plainly visible in the deployed code in Firebase. Use environment_configuration instead.

https://firebase.google.com/docs/functions/config-env?gen=1st#environment_configuration

1
  • Where in the code is this secret visible? Someone was able to access my API KEY which is in an .env file which has not been uploaded to source control (it is in gitignore) no one but me has access to my Firebase app. I am using Node for Firebase functions. Even every time I change the API KEY it is of no use because they can continue using it. Commented Dec 10, 2023 at 17:57
0

Based on the Environment configuration docs You can use the firebase CLI to set the config this way from your terminal

firebase functions:config:set openai.key="sk-xxxxxxxxxxxxxxxxxxxx"

and then you can use like this in your project

const client = new OpenAI({
  apiKey: functions.config().openai.key,
});

make sure the service name (openai in this case) is in lowercase

0

Note that functions.config() is deprecated as of Firebase 2nd gen env configs

firebase exposes these methods in gen2 defineInt, defineBoolean, defineSecret and defineList

As usual you would add your environment variables in functions/.env file and then your functions method you can access them as below

const { onRequest } = require('firebase-functions/v2/https');
const { defineInt, defineString } = require('firebase-functions/params');

// Define some parameters
const minInstancesConfig = defineInt('HELLO_WORLD_MININSTANCES');
const welcomeMessage = defineString('WELCOME_MESSAGE');

access the value of these keys as

 res.send(`${welcomeMessage.value()}! I am a function.`);

note that these env variables are only available in runtime (after deployment)

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

To create a secret, use the Firebase CLI.

firebase functions:secrets:set SECRET_NAME

Note that Secret name should not overlap with any of the keys in your environment variable (.env file)

Secret parameters must be bound to individual functions that should have access to them so

import {defineSecret} from "firebase-functions/params";
import * as functions from "firebase-functions/v2";
const mysecretKey = defineSecret("SECRET_NAME");

export const myfirebaseFunction = onRequest(
  { secrets: [mysecretKey] },
  (req, res) => {
  // access them using .value()
  const apiKey = mysecretKey.value();
    //…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.