This is an Angular CLI app but that's only slightly relevant.
We have pretty typical environment variables, in this case under either
src/environments/environment.ts
or
src/environments/environment.prod.ts
I only ever import my environment using
import { environment } from 'environments/environment'
But, if I run "ng build", it uses "environment.ts" and if I run "ng build --prod" it uses "environment.prod.ts"
Pure magic.
Love it!
But Firebase Cloud Functions is effectively a separate project with a separate build process, so no matter what it just uses "environment.ts" and so I have to remember to manually switch to importing from "environment.prod.ts" each time I deploy to production?
I'm aware of this: https://firebase.google.com/docs/functions/config-env but I don't see how it solves the above problem. Maybe I'm missing something but it seems to me that I'd still have to switch my variables each time using the even-more-cumbersome terminal command syntax (may as well just add ".prod" to my import).
This is workable, sure, but it eliminates safety and some of the convenience of the environment configuration. Eventually someone is bound to do a production deployment and forget to make that switch... and in our case even an accidental deployment to test server with production variables would be harmful since it would mess up our search indexing.
What am I missing? How can I automate the switching?
Open the Runtime, build and connections settings section. Select the Runtime tab. In the Runtime environment variables section, click Add variable and add the name and value. For instructions on how to add environment variables to an existing function, see Updating runtime environment variables.
I finally found a way to do this.
It turns out that at any point you can access the project name within functions using the following:
const project = process.env.GCP_PROJECT;
In my case I created an enum for my two main projects as follows:
enum Projects {
mynametest = 'mynametest',
mynameprod = 'mynameprod',
}
I imported both environments, giving each an alias as follows:
import { environment as devEnv } from '../../src/environments/environment';
import { environment as prodEnv } from '../../src/environments/environment.prod';
Within the relevant functions I used:
const project = process.env.GCP_PROJECT;
let currentEnv;
if (project === Projects.mynametest) {
currentEnv = devEnv;
} else if (project === Projects.mynameprod) {
currentEnv = prodEnv;
} else {
console.error('No valid environment for <something relevant here>');
return null;
}
// use "currentEnv.<myVar>" as you would normally use "environment.<myVar>"
If anyone finds a better and/or more terse way about this, please do share!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With