Firebase cannot find databaseURL when separate databases are created with process.env
I wanted to have separate databases; one for testing and one for development and production. So using the process.env variables and a little library called node-env-file, I set the firebase config variables to the process.env variables. But I am getting this error:
> Uncaught Error: FIREBASE FATAL ERROR: Can't determine Firebase
> Database URL. Be sure to include databaseURL option when calling
> firebase.intializeApp().
In the webpack.config file:
var envFile = require('node-env-file');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
try {
envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV + '.env'));
} catch (e) {
}
// (...)
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
API_KEY: JSON.stringify(process.env.API_KEY),
AUTH_DOMAIN: JSON.stringify(process.env.AUTH_DOMAIN),
DATABASE_URL: JSON.stringify(process.env.DATABASE_URL),
STORAGE_BUCKET: JSON.stringify(process.env.STORAGE_BUCKET),
MESSAGING_SENDER_ID: JSON.stringify(process.env.MESSAGING_SENDER_ID)
}
})
],
// (...)
In config/test.env
and in config/development.env
(these 2 files are similar, but of course the data is different):
API_KEY=myapikeyhere
AUTH_DOMAIN=myauthdomainhere
DATABASE_URL=mydatabaseurlhere
STORAGE_BUCKET=mystoragebuckethere
MESSAGING_SENDER_ID=memessagingsenderidhere
In firebase/index.js
:
import firebase from 'firebase';
try {
var config = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID
};
firebase.initializeApp(config);
} catch (e) {
}
export var firebaseRef = firebase.database().ref();
export default firebase;
I have updated firebase and node-env file libraries.
source to share
In webpack.config.js file replace .env file with the following
envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV.trim() + '.env'));
So, you will get a truncated string.
I had the same problem and when I typed the error in the try / catch block I saw that envFile was trying to find a .env file like 'config / test. env. The spaces after the period were breaking the code. It came from a space here I think (between "test" and "& &") → "NODE_ENV = test && karma start".
A real hard case.
source to share