Vue-Firebase: How to connect to 2 firebases from the same app - javascript

I have two firebases on the same project and i need to connect to both of them.
There are two javascript files connecting to each firebase which seems ok.
I import both of them
import db from '../FireBase'
import mdb from '../MissionFireBase'
let MissionRef = mdb.ref('mission');
let TeamRef = db.ref('Teams');
let StartRef = db.ref('start');
db is an export of one firebase and mdb of another. On itself each one of them works but when i try to use both of them i get an error
index.cjs.js?3b8b:360 Uncaught FirebaseError {code: "app/duplicate-app", message: "Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).", name: "[DEFAULT]", stack: "[DEFAULT]: Firebase: Firebase App named '[DEFAULT]…0)↵ at fn (http://localhost:8080/app.js:89:20)"}
To me it seems somewhere firebase gets a default id and when trying to use them both it conflicts. I tried calling each one from a different vue component but i get the same result.
The firebase connection is made like so
import Firebases from 'firebase'
let config = {
apiKey: "--",
authDomain: "--",
databaseURL: "--",
projectId: "--",
storageBucket: "--",
messagingSenderId: "--"
};
let apps= Firebases.initializeApp(config);
let mdb = apps.database();
export default mdb
Is this possible? Can i use two different firebase calls or would i need to merge them both together?
Thanks

That's definitely possible. You will need to create separate FirebaseApp instances for each, and then get your database from that.
var secondaryAppConfig = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
};
// Initialize another app with a different config
var secondary = firebase.initializeApp(secondaryAppConfig, "secondary");
// Retrieve the database.
var secondaryDatabase = secondary.database();
For more on this, have a look at the section using multiple projects in your application in the Firebase documentation.

Related

Firebase + React auth not working with my .env

So i've read many topics and lose so much time cause of this issue.
My components don't load anymore and i'm receiving this error in my console : 'FirebaseError: Firebase: Error (auth/invalid-api-key).'
(I specify that is my first project using firebase).
About my firebase.config.js :
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
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_MESSAGING_APP_ID
});
export const auth = app.auth();
export default app;
About my .env.local :
REACT_APP_API_KEY=AIXXXXzaSyX_ITiQXXXXXXXXxcXXXXXXXxU
REACT_APP_AUTH_DOMAIN=XXXXX.firebaseapp.com
REACT_APP_PROJECT_ID=name-name-name
REACT_APP_STORAGE_BUCKET=name-name-name.appspot.com
REACT_APP_MESSAGING_SENDER_ID=5XXX7XXXX5XX
REACT_APP_MESSAGING_APP_ID=1:5XXXX4XXX7X:web:aXXXXxxx0xxxxb4a4xxxxxxdd
**About files location : **
src/utils/firebase.config.js
src/.env.local
About the auth process :
Authentication is used in a signUp component that matches a form
Thanks for reading
When I just paste the API_KEY directly in app like this : apiKey: "string". This works, so I think this issue come from my .env file.
I think you're using create-react-app. If that is the case you need to add the .env file to the root of your project, not the src folder.
See the docs for more info on env vars in create react app https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

Firebase error 500, Unable to resolve "firebase" from "firebase.js"

I am trying to use firebase in my new React app but I am always getting "The development server returned response errror code: 500"
And I have no ideo of what am I doing wrong. I only created a firebase.js file to put my firebase configuration
import * as firebase from 'firebase'
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
export {firebase};
I am getting this error in the terminal (and I am sure of having installed firebase):
Unable to resolve "firebase" from "firebase.js"
This doesn't look right, you imported firebase never used it you created config never used it, is this the whole code ?
Please try to follow firebase documentation, last i checked you had to import only the initializeApp function with config object.
here this might help - Firebase Setup for React App

Having error attempting to use RTDB in Expo managed

I'm attempting to use firebase realtime database on my app. I first authenticate and then I need to use the RTDB. Here is my attempt.
import { initializeApp } from 'firebase/app';
import 'firebase/auth';
import 'firebase/storage';
import { getDatabase } from "firebase/database";
import getEnvVars from '../environment';
const ENV = getEnvVars();
const firebaseConfig = {
apiKey: ENV.firebase.API_KEY,
authDomain: ENV.firebase.AUTH_DOMAIN,
databaseURL: ENV.firebase.DATABASE_URL,
projectId: ENV.firebase.PROJECT_ID,
storageBucket: ENV.firebase.STORAGE_BUCKET,
messagingSenderId: ENV.firebase.MESSAGING_SENDER_ID,
appId: ENV.firebase.APP_ID
};
initializeApp(firebaseConfig);
export const db = getDatabase();
The error I get is:
TypeError: (0, _database.getDatabase) is not a function. (In '(0, _database.getDatabase)()', '(0, _database.getDatabase)' is undefined)
You're mixing up the old, namespaced syntax of SDK versions 8 and lower, with the new, modular syntax of SDK versions 9 and above.
To get the database in v9, you call getDatabase() as a top-level function:
export const db = getDatabase();
I recommend keeping the Firebase documentation ready when going through this, as it has code samples for both the old and new syntax so you can easily compare. For this specific call, see the documentation on getting a database reference.

No Firebase App '[Default] has been created - call firebase.initializeApp()

My app is connected to firebase and auth is working fine. However, when trying to use firestore I can't figure out this problem.
Possible Unhandled Promise Rejection (id: 0):
Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()
I am getting the above error however, I am already calling initializeApp and not sure what else to try. I am trying to get access to a collection on firestore and print it out but it gives me the error when I try to access firestore.
I have tried doing console.log(firebase.app().name) which gives the name of the app, so not sure how it is not initialised.
var firebaseConfig = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "****",
}
firebase.initializeApp(firebaseConfig)
const db = firebase.firestore()
My imports are
import "firebase/firestore"
import firebase from "firebase"
import firestore from "#react-native-firebase/firestore"
I have tried so many different questions on here and forums but nothing has helped
Make sure that you made all the configuration correctly by following this video
And just make sure that the first 2 lines at main function are (follow the same order):
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//rest of the code
runApp(MyApp());
}
As per Kishan above. I added the google-services.json file into the android level folder and modified both build.gradle files.
https://firebase.google.com/docs/android/setup followed step 3 here to update the build.gradle files to use google-services.

Initialize Firebase references in two separate files in the new API

I have upgraded to the new API and don't know how to initialize Firebase references in two separate files:
/* CASE 1 */
// 1st file
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
// 2nd file - initialize again
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
RESULT: bundle.js:535 Uncaught Error: Firebase App named '[DEFAULT]' already exists.
/* CASE 2 */
// 1st file
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
// 2nd file - don't initialize
var rootRef = firebase.database().ref();
RESULT: bundle.js:529 Uncaught Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
Before the new API I just called
var myFirebaseRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
in each file, and it worked okay.
This is an issue I ran into as well upgrading to the new version of Firebase. You might want two separate firebase apps initialized, like explained in other answers, but I just wanted to use the refs in two different locations in my app and I was getting the same error.
What you need to do for this situation is to create a firebase module for your app that only initializes firebase once, then you import or require it elsewhere in your app.
This is pretty simple, here is mine: modules/firebase.js
import firebase from 'firebase';
var firebaseConfig = {
apiKey: "some-api-key",
authDomain: "some-app.firebaseapp.com",
databaseURL: "https://some-app.firebaseio.com",
storageBucket: "some-app.appspot.com",
};
var FbApp = firebase.initializeApp(firebaseConfig);
module.exports.FBApp = FbApp.database(); //this doesnt have to be database only
And then elsewhere in your application you simply:
import FBApp from '/your/module/location'
var messagesRef = FBApp.ref("messages/");
You need to name your different instances (Apps as Firebase calls them); by default you're working with the [DEFAULT] App, because that's the most common use case, but when you need to work with multiple Apps then you have to add a name when initialising:
// Intialize the "[DEFAULT]" App
var mainApp = firebase.intializeApp({ ... });
// Intialize a "Secondary" App
var secondaryApp = firebase.initializeApp({ ... }, "Secondary");
...
mainApp.database().ref("path/to/data").set(value);
secondaryApp.database().ref("path/to/data").set(anotherValue);
You can find a more example scenarios in the updated Initialize multiple apps section of the Add Firebase to your JavaScript Project guide.
If you don't have the control over where Firebase will be instantiated, you can do something like this:
try {
let firApp = firebase.app(applicationName);
return firApp;
} catch (error) {
return firebase.initializeApp({
credential: firebase.credential.cert(firebaseCredentials),
databaseURL: firebaseUrl
}, applicationName);
}
Firebase will try to get the application, if it doesn't exist, then you can initialize it freely.
I made the mistake by importing like this.
import firebase from 'firebase'
const firebaseConfig = {
apiKey: 'key',
authDomain: 'domain',
databaseURL: 'url',
storageBucket: ''
};
firebase.initializeApp(firebaseConfig);
This worked fine for a few days but when I tried to sign in with custom tokens my auth object was not changed. I had to refresh the page for it to update so I could make certain calls to the database which were protected by my own auth credentials rules.
".read": "$uid === auth.uid || auth.isAdmin === true || auth.isTeacher === true",
When I changed my imports to this it worked again.
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const firebaseConfig = {
apiKey: 'key',
authDomain: 'domain',
databaseURL: 'url',
storageBucket: ''
};
firebase.initializeApp(firebaseConfig);
Then whenever I need to use Firebase in a certain module I import this(notice the import from firebase/app instead of firebase):
import firebase from 'firebase/app';
And talk to certain services like so:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// Authenticated.
} else {
// Logged out.
}
});
firebase.database().ref('myref').once('value').then((snapshot) => {
// do stuff with the snapshot
});
To make multiple instances using new firebase.initializeApp(), you need a second parameter for the firebase constructor:
firebase.initializeApp( {}, "second parameter" );
Compare it to the old way to generate multiple instances where
new Firebase.Context()
is the second parameter:
new Firebase('', new Firebase.Context() );
For a small fraction of the people here, this issue might be cause by trying to initialize fb admin on the same script that you used to initialize fb on the front end. If anybody is initializing firebase twice on the same script (once for admin and once for frontend), then you need initialize firebase admin in a different script than in front end, and do not import anything that is exported on the backend script on the frontend (and vise versa).

Categories

Resources