What happens when I import firebase from my firebaseConfig.js file? - javascript

Not a problem/bug, but I have the following questions about the Firebase config file below:
firebaseconfig.js
import * as firebase from 'firebase';
const config = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_ID"
};
firebase.initializeApp(config);
export default firebase;
When I import firebase from this config file (firebaseconfig.js), does it run the entire firebase.js file and then import the firebase object each time, or does it just give me the firebase object at the end? If it's the first answer, then does that mean that multiple instances of firebase app get initialized? If it's the second answer, then when does the code preceding "export default firebase" get executed and not-executed?

When you require or import some javascript code, it only gets executed once, no matter how many times it's required or imported. The resulting export is essentially a singleton that's shared across all modules that uses it.

Related

Module not found: Error: Can't resolve './Firebase'

I am new to react and i have been trying to initialize firebase into my react app.
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
var firebaseConfig = {
apiKey: "AIzaSyCvSb1gFiUYMJA4SbsKlJvhFwJ8IFjSwkg",
authDomain: "raya-feedback.firebaseapp.com",
databaseURL: "https://raya-feedback-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "raya-feedback",
storageBucket: "raya-feedback.appspot.com",
messagingSenderId: "575830594611",
appId: "1:575830594611:web:930556a8f2ccf9bf733f46"
};
firebase.initializeApp(firebaseConfig);
export {firebase};
;
This is my Firebase.js file that I am trying to import into my Body.js file and I have been getting this error "Module not found: Error: Can't resolve './Firebase.js'".
This is my file structure:
This is how I am importing it in the Body.js file
import firebase from './Firebase';
I am kind of lost and I have been trying to initialize in a multitude of different ways I see on Youtube and I am still stuck on this error.
Seeing your folder structure Firebase.js is inside src and your trying to process Firebase.js from src/body, since Firebase.js doesn't exist in body you are getting this error, you have to use
import { firebase } from '../Firebase';
So you may be encountering this error because there is some other error in your Firebase.js file.
I noticed in your code snippet above getauth needs to actually be getAuth
./ means the current directory,
../ means the parent directory (previous one)
../../ means the parent of the parent and so on.
you need to use ../Firebase

Firebase not getting imported in my React JS project/ [duplicate]

This question already has answers here:
Module not found: Error: Package path . is not exported from package
(10 answers)
Closed 10 months ago.
I am trying to use firebase inside my project but the classes related to firebase are not getting imported.
This is what I did till now:
Created a new project in firebase console
ran the commands, npm install -g firebase-tools, npm install firebase-admin --save and npm install --save firebase
Created a new file called firebase.js in my project and added the following code:
import firebase from "firebase"
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyAdjdq8JsRSWKeHQYCHNzXm8nn29cOh-4s",
authDomain: "ig-reels-a9b15.firebaseapp.com",
projectId: "ig-reels-a9b15",
storageBucket: "ig-reels-a9b15.appspot.com",
messagingSenderId: "1018616208158",
appId: "1:1018616208158:web:bb1026f5301bd9294e070f",
measurementId: "G-W3051LNHFL"
};
const firebaseApp = firebase.initializaApp(firebaseConfig)
const db = firebaseApp.firestore()
export default db
I am using db variable to pull out data from the cloud firestore database like this:
import React, {useState, useEffect} from "react"
import './App.css';
import VideoCard from './VideoCard';
import db from "./firebase";
function App() {
const [reels, setReels] = useState([])
useEffect(() => {
db.collection("reels").onSnapshot(snapshot => {
console.log(snapshot.docs.toString())
setReels(snapshot.docs.map(doc => doc.data()))
})
}, [])
Whenever I run this code I get the following error:
Compiled with problems:
ERROR in ./src/firebase.js 3:0-32
Module not found: Error: Package path . is not exported from package C:\Users\Aditya\Documents\reactjs-practise\reels_clone\node_modules\firebase (see exports field in C:\Users\Aditya\Documents\reactjs-practise\reels_clone\node_modules\firebase\package.json)
Did you mean './firebase'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules, C:\Users\Aditya\Documents\reactjs-practise\reels_clone\node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.
I have successfully installed all the firebase related tools. Why am I getting this error?
First, install firebase then You want to create your own firebase.js file. I am give you the example of
firebase.js
import firebase from 'firebase/app';
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "authDomain",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appid"
};
firebase.initializeApp(firebaseConfig);
export default firebase;
App.js
const db = firebase.firestore();
//write you own code

Where is 'initializeApp' in firebase imports?

So I started taking a look into firebase and just after defining the intialization as
import firebase from "firebase/compat"
const firebaseConfig = {
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_APP_ID,
measurementId: process.env.REACT_APP_MEASUREMENT_ID
};
const chatSupportApp = firebase.initializeApp(firebaseConfig, "my-app");
A wild warning was display!
/*It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');
ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
Typescript:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';*/
I search in many posts, including documentation and didn't really get how to initialize my app first before using any of the other imports
I found out lately that is was a bit hidden under "firebase/firebase-app"
so it get solved, as
import {initializeApp} from "firebase/firebase-app";
const firebaseConfig = {
apiKey: ...............
};
const chatSupportApp = initializeApp(firebaseConfig, "my-app");
export default chatSupportApp;
This started as a question that I search in most stack overflow posts, but since I solve it for now somehow I wanted also to share with the community in here, but also consider any other suggestion, the question will be then.
Is this approach correct? why all the documentation suggest to do it with
import { initializeApp } from 'firebase/app'; as:
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged, getRedirectResult } from 'firebase/auth';
This really didn't work for me at all and I was not able to use it.
Thanks and enjoy your code!
import {initializeApp} from "firebase/firebase-app";
const firebaseConfig = {
apiKey: ...............
};
const chatSupportApp = initializeApp(firebaseConfig, "my-app");
export default chatSupportApp;

firebase.initializeApp can't find the API key in my dotenv file. (Next.js)

I'm trying to implement Firebase Auth in my Next.js project. The auth system works just fine, BUT only when I directly declare the API key inside of initializeApp. For example:
import firebase from 'firebase/app'
import 'firebase/auth'
const app = !firebase.apps.length ? (
firebase.initializeApp({
apiKey: 'MY_KEY',
authDomain: process.env.FIREBASE_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_SOTORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_SENDER_ID,
appId: process.env.FIREBASE_ID,
measurementId: process.env.FIREBASE_MESUREMENT_ID,
})
) : (firebase.app())
export default app
When I try to get the API key using the .env file, next.js throws the following error:
"Unhandled Runtime Error Error: Your API key is invalid, please check you have copied it correctly."
I've also tried to add those variables by adding the env configuration inside next.config.js, just like Vercel's recommendation https://nextjs.org/docs/api-reference/next.config.js/environment-variables. It also did not work.
My current code goes like this:
import firebase from 'firebase/app'
import 'firebase/auth'
const app = !firebase.apps.length ? (
firebase.initializeApp({
apiKey: process.env.FIREBASE_KEY,
authDomain: process.env.FIREBASE_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_SOTORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_SENDER_ID,
appId: process.env.FIREBASE_ID,
measurementId: process.env.FIREBASE_MESUREMENT_ID,
})
) : (firebase.app())
export default app
What should I do to make initializeApp able to read the process.env.FIREBASE_KEY value?
The Firebase CLI doesn't support deployment of functions that add environment variables. It doesn't matter what you have in any .env file - they simply aren't going to appear in the process environment at all after deployment.
The documented way to provide configuration parameters to your function is explained in the documentation. The variables do not manifest as process environment in process.env. They will appear in the object returned by functions.config() at runtime.
If you really must have process environment variables, you won't be able to use whatever you have sitting in .env. You could instead write and deploy your function using gcloud to specify environment. However, this would lose you all the benefits of using the Firebase CLI, as it's a completely different deployment tool.
You could also deploy with the Firebase CLI, then update the specific environment after deployment with gcloud.
Bottom line is that what you're trying to do isn't terribly easy or straightforward. I suggest learning how to use the config provided by Firebase to make this easier, but this means you will have to copy what you have in .env into its config system.
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_REACT_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_REACT_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_REACT_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_REACT_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_REACT_FIREBASE_MESSAGE_SENDER_ID,
appId: process.env.NEXT_PUBLIC_REACT_FIREBASE_APP_ID,
measurementId: 'G-measurement-id',
};
useEffect(() => {
initializeApp(firebaseConfig);
const messaging = getMessaging();
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// Update the UI to include the received message.
setMessages([...messages, payload]);
});
resetUI();
})

How to import something globally in React Native?

I'm developing an App using React Native and Firebase. So, I created a separate js file to store config of firebase database and then I imported that config file into my screen files when I need to connect with firebase database.
So, I have to import that config file into each and every screen file which I need connect with my firebase database.
I want to know that, is it possible to import that config file globally?
I mean, I create a separate config file, then import it only once into a particular js file (Just for an example, let's think, import it only once into the App.js file) and then, use it in my screen files whenever I need to connect with my firebase database. But in this case, is it possible to use that config file without importing it into each and every screen file?
Hope you will understand what I want to do.
Yes, you just import the file in your main screen/ app entry point.
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/storage';
const config = {
apiKey: "API_KEY",
authDomain: "DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "BUCKET",
messagingSenderId: "MSG_ID",
appId: "APP_ID"
};
app.initializeApp(config);
module.Store = {
Firebase() {
return app;
},
}
if (global) {
global.Store = module.Store;
}
In your main screen
import './Global';
all the functions in Global will be available to all screens.
Demo

Categories