I'm trying to use Firebase with my react app.
I have a file with the config as follows:
import * as firebase from 'firebase';
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DB_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGE_ID,
}
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const database = firebase.database();
const auth = firebase.auth()
export {firebase, auth, database };
When I try this, I get an error that says:
FIREBASE FATAL ERROR: Can't determine Firebase Database URL. Be sure to include databaseURL option when calling firebase.initializeApp().
I can't understand this error because I have config included in the call to initialise the app. Config includes the database URL.
How do you initialise the database?
Same issue here.
Context: Gatsby - gatsby-node.js
For SOME reason it dsnt like my env db url. need to hardcode just that value.
const config = {
apiKey: process.env.GATSBY_FIREBASE_API_KEY,
authDomain: process.env.GATSBY_FIREBASE_AUTH_DOMAIN,
databaseURL: "https://blabla.firebaseio.com",
projectId: process.env.GATSBY_FIREBASE_PROJECT_ID,
storageBucket: process.env.GATSBY_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.GATSBY_FIREBASE_MESSAGING_SENDER_ID
}
and it worked.
cya
You don't need that if statement around the firebase.initializeApp(config);
import * as firebase from 'firebase';
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DB_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGE_ID,
}
firebase.initializeApp(config);
You shouldn't need to export these objects, once you initialise the app it should be usable within the project without exporting.
const database = firebase.database();
const auth = firebase.auth()
export {firebase, auth, database };
Don't initialize firebase more than once.
https://github.com/firebase/firebase-functions/issues/228
I think it is a copy paste error :)
in .env file
REACT_APP_DATABASE_URL
but i use
process.env.REACT_APP_DB
Please check it , it worked fine
import firebase from 'firebase/app'
import 'firebase/database';
const config = {
apiKey: process.env.REACT_APP_APIKEY,
authDomain: process.env.REACT_APP_AUTHDOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PID,
storageBucket: process.env.REACT_APP_SB,
messagingSenderId: process.env.REACT_APP_SID,
appId: process.env.REACT_APP_APPID,
measurementId: process.env.REACT_APP_MID
};
firebase.initializeApp(config);
const database = firebase.database();
export { database };
export default firebase;
I know this a old thread, but I was facing this issue since last night and I spent hours racking my brain to figure out what was wrong with my code. To clarify, all .env variables were being read by cra except for the firebase database url.
I tried the following steps:
checked for spelling errors, both the .env variables and also to see if the url was correct, it was.
I tried printing the .env variables to console & screen both, but when I did the values were undefined for all env variables. This really should not happen and I was baffled.
Tried various things, changed the .env variable name for FIREBASE_DATABASE_URL to something random like XYZ (just to make it work somehow) as I thought some env variables were colliding due to same name, still didn't work.
The only way it worked was har-coding it, but this was an hack and not a solution.
The thing to note was point 2. When printing the env vars even after hardcoding the result was 'undefined' on console.
So nothing was wrong, the code should work, but it didn't why?
Out of pure randomness, I opened the task manager (windows). I notices node servers were running, but I had already closed the react dev server!
I killed the processes and restarted the react server, and now it was working.
The issue was stale node servers running in background and nothing was wrong with the code. This also resolved point 2, the console.log statements were working now.
This might not be solution to everyone's issues but it might be or was to the asker's question 3 yrs back, as there is nothing syntactically wrong with their code.
Restarting the development server solves the issue, if you have just written the code and trying to compile it throws this error. So you can try to exit the batch job and again restart the server.
I also got this uncaught error related to firebase.Atlast Finally error should be solved.
Actually when we are using environment variables they should not pass in to bundle.js file which is a client side javascript file..We can use "DefinePlugin" which is a webpack plugin that should manually pass those env variables in to bundle.js file.
Seems like your code is just fine. Just print and check process.env.FIREBASE_DATABASE_URL and its exactly same as mentioned in firebase console. (If you are using create react app, dont forget to add REACT_APP_ to all your env variables, https://create-react-app.dev/docs/adding-custom-environment-variables/)
import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';
import 'firebase/storage';
const appConfiguration = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID,
measurementId: process.env.REACT_APP_MEASUREMENT_ID
};
export const session_type = firebase.auth.Auth.Persistence.LOCAL;
export const app = firebase.initializeApp(appConfiguration);
export const auth = app.auth();
export const db = app.firestore();
export const storage = app.storage();
will get the job done.
I just paste the hardcode config and it worked for me
const config = {
apiKey: "AIzaSyBA2C8S7****************-gCw",
authDomain: "e**********-2aa4c.firebaseapp.com",
databaseURL: "https://************.firebaseio.com",
projectId: "ea********2aa4c",
storageBucket: "ea************2aa4c.appspot.com",
messagingSenderId: "1765********26",
}
Check whether you have set environment variables using require('dotenv').config({ 'path': '.env.development' }). Also make sure that first you the set env variable as above, and then after insert firebaseConfig in Plugins:
new webpack.DefinePlugin({
'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY), // this will set 'process.env.FIREBASE_API_KEY' to actual key in firebase.js cause we do not directly set those value here to make it secure excluding .env files.
'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
'process.env.FIREBASE_MESSAGING_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGING_SENDER_ID),
'process.env.FIREBASE_APP_ID': JSON.stringify(process.env.FIREBASE_APP_ID),
'process.env.FIREBASE_MEASUREMENTID': JSON.stringify(process.env.FIREBASE_MEASUREMENTID)
})` )
For some reason databaseURL read string values in "",
for example if we write:
const fbAuthDomain = "text";
const fbDatabaseURL = "text";
const firebaseConfig = {
authDomain: fbAuthDomain,
databaseURL: fbDatabaseURL
};
// and then:
console.log(firebaseConfig.authDomain); // returns "text"
console.log(firebaseConfig.databaseURL); // returns text
sorry for js example
for me, helped doing variable fbDatabaseURL in json from there i process.env in config - not:
{
"fbDatabaseURL": "\"https://someurl.firebasedatabase.app\""
}
but:
{
"fbDatabaseURL": "https://someurl.firebasedatabase.app"
}
Same issue here but after putting firebaseconfig in componentDidMount() it will solved.
componentDidMount(){
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL:process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID
};
firebase.initializeApp(firebaseConfig);
const myitem = firebase.database().ref('items/').once('value',snapshot=>{
console.log(snapshot.val())
})
}
In the firebase.js, when I removed the blank between databaseURL: and process.env.FIREBASE_DATABASE_URL., it worked.
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL:process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID
};
Related
I deployed a React app, but I'm receiving the error message:
#firebase/database: FIREBASE FATAL ERROR: Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp().
How do I fix this issue?
My firebase.js file currently looks like this...
import firebase from "firebase";
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
});
const database = firebase.database();
export const auth = firebase.auth();
export default database;
My .env.local file looks like this (I redacted full details)
REACT_APP_FIREBASE_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXmRv4
REACT_APP_FIREBASE_AUTH_DOMAIN=XXXXXXXXXXXXXXXXXXXXXXXXXd99c.firebaseapp.com
REACT_APP_FIREBASE_PROJECT_ID=XXXXXXXXXXXXXXXXXXXXXXXXXproject-fd99c
REACT_APP_FIREBASE_STORAGE_BUCKET=XXXXXXXXXXXXXXXXXXXXXXXXXd99c.appspot.com
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=XXXXXXXXXXXXXXXXXXXXXXXXX706
REACT_APP_FIREBASE_APP_ID=XXXXXXXXXXXXXXXXXXXXXXXXX54da93
Your configuration object (the one you pass to initializeApp) is missing a databaseURL property. It's unclear from your question why it's missing or what you may have done to omit it, but that's what you need. You can get the string value for that property in the Firebase console for your app under "project settings".
I'm making an app that writes a waiting list in the firebase realtime databse, but when I try to run this simple bit of code, I get this error (Note- I'm running this on web):
class FirebaseMethods {
FirebaseDatabase database = FirebaseDatabase.instance;
void createPartyWaiting(String partyCode, String partyHostName) async {
partyCode = partyCode.trim();
DataSnapshot data = await database.ref("e").get();
print(data.value);
}
}
and i'm calling it as-
await FirebaseMethods().createPartyWaiting("PartyCode123", "Adam");
But when I call it, I get this error-
Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com
at Re (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:22344)
at Ws (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:148180)
at au (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:166314)
at K.xu.INTERNAL.registerComponent.Y.setServiceProps.Reference [as instanceFactory] (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:187315)
I'm initializing the web like this (I've censored the actual values)-
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (kIsWeb) {
Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "apikey",
authDomain: "authDomain",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"));
}
runApp(const MyApp());
}
I've also found out that there's this optional arguement to the initilaziation method-
But after adding my databaseUrl here, I got this error-
Error: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
at Object.throw_ [as throw] (http://localhost:53659/dart_sdk.js:5063:11)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:53659/packages/firebase_core_web/firebase_core_web.dart.lib.js:248:27)
What am I doing wrong, and how do I fix this? Thanks!
For anyone who has used $ flutterfire configure to configure firebase to your flutter project as shown in here before adding Realtime Database, you will have to run the command again to reconfigure your project or add "databaseURL" to the FirebaseOptions in your lib/firebase_options.dart.
Your lib/firebase_options.dart should look something like this:
// inside lib/firebase_options.dart
// ...
static const FirebaseOptions web = FirebaseOptions(
apiKey: '...',
appId: '...',
messagingSenderId: '...',
projectId: 'project-id',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://your-database-id.firebasedatabase.app', // IMPORTANT!
storageBucket: 'project-id.appspot.com',
measurementId: '...',
);
// ...
Since you're configuring your Firebase project (for web) by passing the configuration data to Firebase.initializeApp, you should also include the URL for your database there:
Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "apikey",
authDomain: "authDomain",
databaseURL: "the URL for your database", // 👈
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"));
You can find this URL in your browser by going to the Realtime Database panel in the Firebase console:
I'm not sure why the databaseURL doesn't show in your auto-complete though, as I have it in all of my Dart configs (most of which are generated by the FlutterFire CLI).
If entering the databaseURL manually gives an error message, I recommend checking if you're on the latest version of the libraries (although I don't recall this ever not being present).
I recreated the flutter and firebase project with a new app id, and it worked.
I have been trying to develop a fully functional, reusable firebase authentication app however after looking online at multiple different solutions, I have developed the below which works perfectly but from my understanding there is no way to protect the API keys/sensitive data? Is there anyway to use environment variables on the plugins/firebase.js file?
The nuxt/firebase docs suggests declaring them within the nuxt.config.js file? But when following the docs and trying to install firebase & #nuxtjs/firebase I keep running into errors. NPM error when I am trying to install #nuxtjs/firebase
Is there any definitive/working best practise to follow when working with Nuxt & Firebase?
~plugins/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore'
import 'firebase/storage'
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
export const auth = firebase.auth()
export const google = new firebase.auth.GoogleAuthProvider()
export const storage = firebase.storage()
export default firebase
~/plugins/fireauth.js
import { auth } from '~/plugins/firebase.js'
export default (context) => {
const { store } = context
return new Promise((resolve, reject) => {
auth.onAuthStateChanged(user => {
console.log(user);
store.dispatch('setUser', user)
resolve(user)
}, err => {
reject(err)
})
})
}
Update to #Kissu
The environment variables are now working as per #kissu's comments below - however the app is now crashing because the initializeApp() is not being run.
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
~/plugins/firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
import 'firebase/compat/storage'
export default ({ $config }) => {
const firebaseConfig = {
apiKey: $config.firebaseConfig.apiKey,
authDomain: $config.firebaseConfig.authDomain,
projectId: $config.firebaseConfig.projectId,
storageBucket: $config.firebaseConfig.storageBucket,
messagingSenderId: $config.firebaseConfig.messagingSenderId,
appId: $config.firebaseConfig.appId
}
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
}
export const auth = firebase.auth()
export const google = new firebase.auth.GoogleAuthProvider()
export const storage = firebase.storage()
Resources:
https://firebase.nuxtjs.org/
https://dev.to/drewclem/building-user-accounts-with-nuxt-vuex-and-firebase-2o6l
In your Firebase Config, you can use local environment variables (from your .env file) using process.env.VUE_APP_:
// ~/plugins/firebase.js
const firebaseConfig = {
apiKey: process.env.VUE_APP_FIREBASE_apiKey,
authDomain: process.env.VUE_APP_FIREBASE_authDomain,
projectId: process.env.VUE_APP_FIREBASE_projectId,
storageBucket: process.env.VUE_APP_FIREBASE_storageBucket,
messagingSenderId: process.env.VUE_APP_FIREBASE_messagingSenderId,
appId: process.env.VUE_APP_FIREBASE_appId,
measurementId: process.env.VUE_APP_FIREBASE_measurementd,
};
But be sure to set your Variables in your .env file like this:
// ~/.env
// NOTE: THIS FILE IS NOT COMMITTED TO CODE REPOSITORY / GITHUB AND SHOULD BE IGNORED BY DEFAULT IN YOUR `.gitignore` FILE
// NOTE: For Vue.js environment variables, you must prefix them with `VUE_APP_`
VUE_APP_FIREBASE_apiKey=
VUE_APP_FIREBASE_authDomain=
VUE_APP_FIREBASE_projectId=
VUE_APP_FIREBASE_storageBucket=
VUE_APP_FIREBASE_messagingSenderId=
VUE_APP_FIREBASE_appId=
VUE_APP_FIREBASE_measurementId=
Where after the = you put your secret keys and ID's. NOTE: Be sure to leave NO SPACE between the = and your key. For example:
VUE_APP_FIREBASE_apiKey=YOUR.KEY.HERE
...
You can read more documentation on VUE_APP Environment Variables here: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
This .env file should not be committed to Github, or your code repository. Instead, set these variables on your production environment. For example, if you are using Netlify or Heroku, you will want to set Environment Variables with the EXACT same names like VUE_APP_FIREBASE_apiKey and set its value to be equal to your Key.
If using Netlify, set your Environment Variables in your Build & Deploy Site Settings:
https://app.netlify.com/sites/{{YOUR_SITE_HERE}}/settings/deploys#environment
I'm new to firebase. I've employed it into my vuejs project. How do i save the firebase config parameters into environment variables. Or is there a better way to achieve this.
Use .env.js files in vue
This is actually not really needed as you can also store the config directly in the main.js file. Also, these firebase config data is public and needs not to be protected. Still here is how you do it.
In your prod.env.js file (located for my setup under the folder config) add
'use strict'
module.exports = {
NODE_ENV: '"production"',
FIREBASE_API_KEY: '"APIKEY"',
FIREBASE_AUTH_DOMAIN: '"YOURID.firebaseapp.com"',
FIREBASE_DATABASE_URL: '"YOURURL"',
FIREBASE_PROJECT_ID: '"YOURID"',
FIREBASE_STORAGE_BUCKET: '""',
FIREBASE_MESSAGING_SENDER_ID: '"YOURSENDERID"',
FIREBASE_APP_ID: '"YOURAPPID"',
}
In main.js call the env variables with process.env.VARIABLENAME.
Here is the setup for firebase:
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
};
you can always create a new file that contains all the configuration settings and gitignore that file hence making it secure.
It depends only on your project structure.
Just import this file wherever it is needed without compromising your security
I'm new to React Native and Firebase coding. I'd like to skip the login process if the user logged in successfully last time. According to Firebase doc, firebase.auth.Auth.Persistence.LOCAL can persist the authentication state even the activity is destroyed. The problem is how can I check the local persisted authentication state when the app initializes?
I managed to use AsyncStorage to achieve the goal, but firebase.auth.Auth.Persistence.LOCAL is supposed to be the simpler approach, but I can't figure it out.
Init codes:
<pre>
componentWillMount() {
const firebaseConfig = {
apiKey: "xxxxxxxxxx",
authDomain: "xxxxx.firebaseapp.com",
databaseURL: "https://xxxx.firebaseio.com",
projectId: "xxxxxx",
storageBucket: "xxxxx.appspot.com",
messagingSenderId: "xxxxxxx"
};
if (!firebase.apps.length) {
console.log("call firebase init");
firebase.initializeApp(firebaseConfig);
console.log(firebase.app().options);
}
}
</pre>