I have a solution that works for me, based on this article:
https://victorbruce82.medium.com/how-to-deploy-a-react-app-to-different-firebase-hosting-environments-dev-and-prod-da3f4cae9a1e
It uses env-cmd
, and you don't need cloud-functions to get the right env variables on the current firebase-hosting the site is running from (Since NODE_ENV
always returns production
when deployed on firebase)
Based on using two separate firebase projects, one for production, one for development. So after adding a 2nd firebase project, used for development:
Add the dev project to your current one with: firebase use --add
, and use alias dev
.
Create two .env
files: .env.production
and .env.development
with each a variable like:
APP_ENV="production"
(Change it to development
in the .env.development file)
(You can also add API-keys to these .env files, make sure you .gitignore
them, so you don't have secrets in your codebase)
Now in you code you can reference this with process.env.APP_ENV
:
const websiteConfig = process.env.APP_ENV=== 'production' ? {
themeColor: '#fff'
} : {
themeColor: '#ccc'
}
(You can also choose to have a APP_THEME_COLOR
in your .env files instead and access it directly, depending on your preference)
Install env-cmd
npm i -D env-cmd
Now add 2 scripts to your package.json
:
"build:dev":"env-cmd -f .env.development npm run build && firebase deploy -P dev",
"build:prod":"env-cmd -f .env.production npm run build && firebase deploy -P prod"
Now you can deploy your code to two different environments/domains/hosts, but also have them use different environment variables.
(Note: using NODE_ENV
in your .env files does not work, it will always return production
when deployed on firebase hosting)