How to call database().ref() method in Firebase Config firebase V9 - reactjs

I am working on a react project that I am I want to use both Auth and real-time database from firebase. I have managed to set auth but database import is giving me a hard time. I want to use the (database().child().push() ) method to push data to the database but I can't call the database().ref() method in my firebase Config. Anyone?
import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyD8aGnZYjhCTopgdNhuykWvmkJSHKj_h7E",
authDomain: "bonnie-d17be.firebaseapp.com",
databaseURL: "https://bonnie-d17be-default-rtdb.firebaseio.com",
projectId: "bonnie-d17be",
storageBucket: "bonnie-d17be.appspot.com",
messagingSenderId: "397471611615",
appId: "1:397471611615:web:3f6a743f4770ff8718c76a"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const authentication = getAuth(app);
export default app;

Firebase's documentation has examples of both name-spaced (V8) and new functional (V9) syntax. To push a new node, try the following code:
// Initialize database similar to auth
import { getDatabase } from "firebase/database";
export const database = getDatabase();
import { push, child, ref } from "firebase/database";
const dbRef = ref(database)
push(child(dbRef, 'path/')).then(() => {
console.log("Data added")
})

Related

getAuth() invalid in firebase in nextjs

I know there is a NextJS Auth ways to do it but its not comfortable to me and I'm used to do it in firebase, but I don't understand why it is receiving an error in authentication?
Basically I have this bunch of codes.
And the getAuth() is giving me an error..
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
import { getAuth ,GoogleAuthProvider, FacebookAuthProvider, TwitterAuthProvider,GithubAuthProvider } from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
console.log(process.env.API_KEY);
console.log(process.env.AUTH_DOMAIN);
console.log(process.env.PROJECT_ID);
console.log(process.env.STORAGE_BUCKET);
console.log(process.env.MESSAGING_SENDER_ID);
console.log(process.env.APP_ID);
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const storage = getStorage(app);
export const authentication = getAuth();
export const google = new GoogleAuthProvider();
export const facebook = new FacebookAuthProvider();
export const twitter = new TwitterAuthProvider();
export const github = new GithubAuthProvider();
This is the error I received in nextjs.
But all my firebase config in .env file is right and its working in console.log() can anyone tell me why it is not working? I've been annoyed lately at any bugs I receive in NextJS that I don't understand where it come from.
According to Exposing Environment Variables to the Browser, all of your process.env variables should be prefixed with NEXT_PUBLIC_.
Also as a local test, you can copy the project config directly from your project settings in the Firebase cloud UI and replace your config that's dependent on env variables. Use that to verify you're able to connect - then go back to your environment variables.

Package path . is not exported from package [duplicate]

import firebase from 'firebase'
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export default db;
Error
Module not found: Error: Package path . is not exported from package C:\Users\Sairam\Visual Code\todo-list\node_modules\firebase (see exports field in C:\Users\Sairam\Visual Code\todo-list\node_modules\firebase\package.json)
Did you mean './firebase'?
I believe the firebase had lot of updates recently, so you should update the imports this way and it worked liked a charm.
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
// Use this to initialize the firebase App
const firebaseApp = firebase.initializeApp(firebaseConfig);
// Use these for db & auth
const db = firebaseApp.firestore();
const auth = firebase.auth();
export { auth, db };
You should import like below. I see this from the firebase documentation: https://www.npmjs.com/package/firebase
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore/lite';
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
export default db;
In your Firebase config file, set up Firebase as follows:
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';
// Your web app's Firebase configuration
const config = {
//your config json file
};
firebase.initializeApp(config);
export const firestore = firebase.firestore();
export default firebase;
In the relevant .js script import Firestore and Firebase as follows:
import {firestore as db} from './firebase-config'
import firebase from './firebase-config';
If you use electron-react-boilerplate, in webpack.config.renderer.dev.dll.ts, remove firebase from the entry point. For example:
entry: {
renderer: Object.keys(dependencies || {}).filter((it) => it !== 'firebase'),
},
It is not working because you are using Firebase version-8 codes in upgraded Firebase version-9 , so if you want to solve your problem you should install Firebase version-8 by using the code below:
npm i firebase#8.2.3
I noticed that I was importing my firebase.ts config file as import db from "firebase" (absolute imports)
The issue here was that webpack was referencing the "firebase" from node_modules, rather than from my firebase.ts. And that's why it threw that error.
I fixed it by importing my firebase configs as import db from "../../firebase", and that worked
You have mistaken at const db = firebase.firestore();
It should be const db = firebaseApp.firestore();
Even after doing that you will get error of module not found. You need to import as following
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
This worked for me as I had the same issue!!
maybe i meeted the same problem when using webpack.
i solved the problem by setting webpack/configuration/resolve/#resolveconditionnames
As in v-9.8.2. Here is the docs link
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";
import { getDatabase } from "firebase/database";
const firebaseConfig = {};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const firebaseAuth = getAuth(app);
export const fbDatabase = getDatabase(app);
export const fStore = getFirestore(app);
export const fStorage = getStorage(app);
Currently, Firebase provides two Web SDK variants. So make sure that you are using the correct version of firebase library. With version 9 firebase library was arranged independent libraries. Your syntax is using firebase version 8.
version-8 version-9

Firebase and reactjs: Firebase App named '[DEFAULT]' already exists (app/duplicate-app) [duplicate]

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

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