I\'m using React with next.js and Google Cloud functions to serve the app. I also use firebase. I\'m looking for the best way to automatically configure the staging and prod
I've finally tracked down an answer to this.
The best way I've found to handle this in React/nextjs
is to use a combination of my ideas #4 and #5 from my original question.
As seen here, firebase
has a firebase apps:sdkconfig
command on the cli that:
Prints the Google services configuration of a Firebase App.
So knowing that, you can add a script to npm
that creates a firebase
config file each time the site gets built. Since it knows which firebase project you are currently using on the command line, it knows the version of the config to output when you're deploying.
Then, in your package.json
, you can set it to run.
"scripts": {
...
"build": "npm run getconfig && next build",
"getconfig": "firebase apps:sdkconfig web --json > ./firebase-config.json",
...
},
Then, in your firebase.js
or wherever you're configuring firebase in your app:
// Get the Firebase config from the auto generated file.
const firebaseConfig = require('./firebase-config.json').result.sdkConfig;
// Instantiate a Firebase app.
const firebaseApp = firebase.initializeApp(firebaseConfig);
This works both locally and in the cloud with no manual changes needed other than what you'd already be doing to switch the environment you're using (i.e. firebase use
)
You might need to tweak which npm script it runs on or other small things to suit your needs, but this general setup is working great for me with production
, staging
and development
environments.