How to access an already initialized firebase app in React-native? - reactjs

This maybe a very novice question but I am stuck at here. I am a begineer in React-native and currently working with firebase real-time db with react. I've already initialized my firebase app in one screen(login.js). Since I am using firebase 3.X I cannot reinitialize that app again in another screen. How can I access that already initialized app into another screen(register.js)?

And for the modular Firebase Web SDK 9 and up:
import { initializeApp } from "firebase/app";
import Constants from "expo-constants";
// Initialize Firebase
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId,
measurementId: Constants.manifest.extra.measurementId,
};
const app = initializeApp(firebaseConfig);
export default app;
And then where you need it:
import app from '../config/firebaseConfig';
This is using Expo and 'expo-contants' (https://docs.expo.dev/versions/latest/sdk/constants/) to avoid committing your keys to your Github repo. If not using Expo then you can use react-native-dotenv (https://www.npmjs.com/package/react-native-dotenv) which does the same for pure react native apps.

Here is how you export Firebase Config
Make sure you have added firebase to your project by npm install firebase --save
then create a config file at ./Config/FirebaseConfig.js
Add the below code in your file.
import Fb from 'firebase';
const config = {
apiKey: 'apiKey',
authDomain: 'projectId.firebaseapp.com',
databaseURL: 'https://databaseName.firebaseio.com',
};
const Firebase = Fb.initializeApp(config);
export default Firebase;
After this you can import firebase in any of your component by import Firebase from 'Firebase';

Related

firestore' does not exist on type 'typeof import

Difficulty in setting up this app as firebase, exported from firebase/app doesn't seem to have the firestore() method on it (See attached image). This is my code. Someone please help me fix it.
// Import the functions you need from the SDKs you need
import firebase from 'firebase/app';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "-------",
authDomain: "--------",
projectId: "------------",
storageBucket: "------------",
messagingSenderId: "---------",
appId: "----------"
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig)
export const firestore = firebase.firestore()
Maybe you're using Firestore v9. So you might be using the methods from the old API
You can check what version of firebase you've installed by looking at the major version of the npm package in your package.json
Here is a snippet from the Firestore docs on how to initialize firestore with with the web version v9 (https://firebase.google.com/docs/firestore/quickstart)
// Initialize Cloud Firestore through Firebase
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
const firebaseApp = initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
const db = getFirestore();

Getting the error : Module not found: Can't resolve 'firebase/app'

import 'firebase/auth';
import 'firebase/database';
import 'firebase/storage';
var firebaseConfig = {
apiKey: "AIzaSyCEtbuZ3oIA8amHdyOBXMLLmHCZMuHIPVg",
authDomain: "react-slack-clone-6284c.firebaseapp.com",
databaseURL: "https://react-slack-clone-6284c.firebaseio.com",
projectId: "react-slack-clone-6284c",
storageBucket: "react-slack-clone-6284c.appspot.com",
messagingSenderId: "1010926924701",
appId: "1:1010926924701:web:d5d331af0cfe6fd31db574",
measurementId: "G-9K7S58J5LF"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
export default firebase;
My firebase.js file is inside the src folder and i am getting the error as mentioned.While importing firebase to my Register.js, i am encoutering this error
See https://firebase.google.com/docs/web/setup#using-module-bundlers
You should add import * as firebase from "firebase/app";
// Firebase App (the core Firebase SDK) is always required and must be listed first
import * as firebase from "firebase/app";
// If you enabled Analytics in your project, add the Firebase SDK for Analytics
import "firebase/analytics";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
// ...
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
npm install firebase#8.3.1 --save

React firebase api - .a.auth is not a function

I did a research but found that problem only in node.js context, or react context but from a long time ago, and guys say that upgrading their firebase helped. Mine was installed just last month.
Basically I'm using React with firebase api, and I this code:
firebase.auth().signInWithEmailAndPassword('an email', 'a password);
Throws the following error:
TypeError: WEBPACK_IMPORTED_MODULE_2__firebase.a.auth is not a function
Of course I'm importing firebase:
import firebase from '../../firebase';
All the other firebase commands work just fine.
Has anyone had an experience with that problem using react.js ?
Thanks a lot in advance
Just posting the answer, maybe to help others. The simple solution (thanks to think-twice) is to import "firebase/auth". Here is an example of the Firebase file:
import firebase from 'firebase/app';
import 'firebase/storage';
import "firebase/database";
import "firebase/auth"
// Initialize Firebase
var config = {
apiKey: "*********************",
authDomain: "...",
databaseURL: "...",
projectId: "....",
storageBucket: "....",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const storage = firebase.storage();
export {
storage, firebase as default
}
First check your path is correct, if is, try to delete the node_modules folder and make npm install again !

React NextJS Firebase error refresh Firebase App named '[DEFAULT]' already exists

I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit

firebase.initializeApp is not a function

I'm trying to make a site in React, and I have added the Firebase library using npm i firebase --save
I am then trying to call this in my app, but I am not having much joy:
import * as firebase from "firebase";
const instance = firebase.initializeApp({
apiKey: '123',
authDomain: 'https://123.firebaseapp.com/',
databaseURL: 'https://123.firebaseio.com/'
});
export default instance;
No matter what I try, it throws:
firebase.initializeApp is not a function
I've checked its in my node_modules and i've reinstalled it, but I still have no such luck.
Any suggestions?
I had a the same problem with firestore in my Vue application.
I eventually came right by doing the following in my firebase.js file:
import { firebase } from '#firebase/app'
As opposed to :
import * as firebase from 'firebase/app'
Also if you are using any specific firebase modules you need to import them individually like so:
import '#firebase/auth'
import '#firebase/firestore'
const db = firebase.firestore()
const auth = firebase.auth()
export { db, auth }
Hope this helps somebody.
This is how I solved this
import firebase from "firebase";
const firebaseConfig = {
apiKey: "Api Key",
authDomain: "Domain",
databaseURL: "URL",
projectId: "ID",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
export default db;
Can you please try with:
var firebase = require('firebase/app');
Credits.
Been having a similar issue with firebase v4.12.1 throwing error of initializeApp not being a function. I solved it by switching to using #firebase/app 0.1.10 npm package instead.
import { firebase } from '#firebase/app';
Using it in a next.js v5.1.0 project.
been having the same problem but in VUE, in case it works i solved importing each element separately
// This import loads the firebase namespace.
import firebase from 'firebase/app';
// These imports load individual services into the firebase namespace.
import 'firebase/auth';
import 'firebase/database';
import 'firebase/firestore';
import 'firebase/storage';
Hope can help ;)
This is the new firebase SKD modular recommendation. Avoid using the
import firebase from 'firebase/app';
and try to use modular import, such as:
import {initializeApp} from "firebase/app";
const instance = {
apiKey: '123',
authDomain: 'https://123.firebaseapp.com/',
databaseURL: 'https://123.firebaseio.com/'
};
export const app = initializeApp(instance);
references
https://firebase.google.com/docs/web/learn-more#modular-version
const auth = firebase.auth()
export { db, auth }`import * as firebase from "firebase";
require("#firebase/firestore");
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase.firestore();

Resources