Initialize Firebase realtime database - javascript

I have the following code:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import {
getDatabase,
} from "firebase/database";
// 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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey:
"XXXXXXXXXXXXXXXXXX",
authDomain:
"XXXXXXX-XX-XXXXX.firebaseapp.com",
databaseUrl:
"https://XXXXXXX-XX-XXXXX-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "XXXXXXX-XX-XXXXX",
storageBucket:
"XXXXXXX-XX-XXXXX.appspot.com",
messagingSenderId: "AAAAAAAAAAAA",
appId:
"1:AAAAAAAAAAAA:web:BBBBBBBBBBBBBBB",
measurementId: "G-XXXXXXXXX",
};
// Initialize Firebase
const app = initializeApp(
firebaseConfig
);
const db = getDatabase();
When running my code, Firebase kindly tells me the following:
[2022-11-23T22:45:42.778Z] #firebase/database: FIREBASE WARNING: Database lives in a different region. Please change your database URL to https://XXXXXXX-XX-XXXXX-default-rtdb.europe-west1.firebasedatabase.app (https://XXXXXXX-XX-XXXXX-default-rtdb.firebaseio.com/)
I as a friend of order reads the outputed message and CHANGES the databaseUrl in my code as the one STATED by Firebase in above message.
I then run my code again and get the SAME message. What am I doing wrong?

Related

I am seeing following error while trying to add firebase analytics

I have linked firebase analytics to the firebase project recently but I am getting the following error in my console and nothing is visible in the firebase analytics Dashboard even.
[2022-04-11T06:07:13.736Z] #firebase/analytics: The measurement ID in the local
Firebase config (G-XXXXXXXXX) does not match the measurement ID fetched from the
server (undefined). To ensure analytics events are always sent to the correct Analytics
property, update the measurement ID field in the local config or remove it from the
local config.
This is how I am adding analytics
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "*****************",
projectId: "********",
storageBucket: "*********",
messagingSenderId: "********",
appId: "*******************************",
measurementId: "G-XXXXXXXXX"
};
const app = firebase.initializeApp(firebaseConfig)
const auth = getAuth(app)
const db = getFirestore(app)
firebase.analytics()
const analytics = getAnalytics(app);
console.log(analytics)
Can anyone help what exactly I am missing? Any help is appreciated.
If anyone sees this error, then in my case issue was I have implemented firebase analytics after creating the project not while creating. SO it took 24 hours to reflect. And after 24 hours everything was working.

Firebase multiple "apps" - client side and server side

So, I wanted to add another firebase app into the project. I already had one for SSR (firebase-admin), so server could pre-render sites. Now I want to add firebase#8, so I can start using it on client side, and later apply firestore rules to it. The problem is, when I'm trying to use it I get this error:
/node_modules/#google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/#google-cloud/storage/build/src/index.js
./node_modules/firebase-admin/lib/storage/storage.js
./node_modules/firebase-admin/lib/app/firebase-namespace.js
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js
./firebase/config.js
./firebase/createDocument.js
./components/form/Form.js
./pages/opinia/index.js
https://nextjs.org/docs/messages/module-not-found
Here is my config file:
import * as admin from 'firebase-admin';
import firebase from 'firebase';
import 'firebase/firestore';
// initialize firebase on CLIENT
const firebaseConfig = {
apiKey: process.env.FIREBASE_KEY,
authDomain: process.env.FIREBASE_DOMAIN,
projectId: process.env.FIREBASE_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
};
export const clientApp = initializeApp(firebaseConfig);
// firestore
export const projectFirestoreClient = firebase.firestore(clientApp);
// timestamp
export const timestampClient = firebase.firestore.Timestamp;
// initialize firebase on SERVER
if (!admin.apps.length) {
const serviceAccount = require('./firebase-adminsdk.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
// firestore
export const projectFirestoreAdmin = admin.firestore();
// timestamp
export const timestampAdmin = admin.firestore.Timestamp;
So, my question is, how do I fix this error? And what's causing it? Thanks in advance.
Firebase Admin is not meant to be used on client side. When you run the app, Firebase Admin is also being imported and causing that error. Ideally you should initialize Firebase Admin in a different file that can be accessed on server side only.
Checkout this blog for step-by-step explanation on how to use Firebase Admin with NextJS.

Authenticate users between firebase apps

I have a React app with firebase auth and storage
Following on my previous question with multiple firebase apps here, I ended having multiple firebase apps inside my project.
I have the DEFAULT app initialized
firebase.initializeApp({
apiKey: 'xxxxxxxxxxxxxxxxxxxx',
authDomain: 'buckettest-xxxxx.firebaseapp.com',
projectId: 'buckettest-xxxxx',
storageBucket: 'buckettest-xxxxx.appspot.com',
messagingSenderId: 'xxxxxxxxxxxxxxxxxxxx',
appId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
measurementId: 'G-QZDBHEWHJ5',
});
Users log in with email and password, using signInWithEmailAndPassword method from firebase.auth() from the DEFAULT app above
In a component I create a secondary firebase app that connects to a different storage bucket as follows
const createStoreApp = (bucket) => {
const firebaseStoreApp = firebase.apps.length === 1
? firebase.initializeApp({
storageBucket: bucket.name,
apiKey: 'xxxxxxxxxxxxxxxxxxxx',
authDomain: 'buckettest-xxxxx.firebaseapp.com',
projectId: 'buckettest-xxxxx',
storageBucket: 'buckettest-xxxxx.appspot.com',
messagingSenderId: 'xxxxxxxxxxxxxxxxxxxx',
appId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
measurementId: 'G-QZDBHEWHJ5',
}, 'storage')
: firebase.apps[1];
return firebaseStoreApp;
};
This solution works perfectly BUT there is the issue that there is no autheticated user on this secondary app.
Is there a way to autheticate the currentUser from the DEFAULT app instance to the second one without asking for credentials?
Each initialized app instance has its own authentication. You can't have one app instance reach into another app to get its auth data. As such, you will need to use the Firebase Auth APIs to sign in the user in to the second app instance separately. Since you're using signInWithEmailAndPassword, it sounds like you're going to have to store the user's credentials somewhere until you're able to call initializeApp again with them as needed.

Firebase - need to fix javascript sdk auth error

I'm always getting this error:
TypeError: firebase.auth is not a function
Here is my code base, can some one help me plz?
const functions = require('firebase-functions');
var firebase = require("firebase/app");
var firebaseConfig = {
apiKey: "AIzaSyCGLNi4KMtUSC3CC3s6V-ZLQA87fDEuP-w",
authDomain: "octatradesfirebasedemo.firebaseapp.com",
databaseURL: "https://octatradesfirebasedemo.firebaseio.com",
projectId: "octatradesfirebasedemo",
storageBucket: "octatradesfirebasedemo.appspot.com",
messagingSenderId: "889486380424",
appID: "1:889486380424:ios:fb54696dc8f4a731df7e3d"
};
firebase.initializeApp({firebaseConfig});
console.log(firebase.auth);
});
If you want to use Firebase Authentication, you'll need to include firebase/app and firebas/auth.
var firebase = require("firebase/app");
require("firebase/auth");
That second require statement will add the firebase.auth() object.
Also see the Add Firebase SDKs and initialize Firebase section of the Firebase documentation.
You are going to need to add <script src="/__/firebase/6.6.1/firebase-auth.js"></script> or <script defer src="https://www.gstatic.com/firebasejs/6.6.1/firebase-auth.js"></script> to your app

Firebase credentials don't work when authenticated

I'm trying to implement an authentication for firebase in my react app. I do that with github but it's not relevant.
So I have some credentials and they work just fine. I can fetch my data from db and manilpulate it.
Until I login...
After successfully executing this: firebase.auth().signInWithPopup(githubProvider).then ...
I start constantly receiving warnings of that kind:
FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was not initialized correctly. Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.
I can't do anything to my DB.
And this continues until I log out with firebase.auth().signOut().then ... then everything works fine again.
inb4: I am 100% confident that my credentials are correct. I have copied and pasted them several times.
Can someone give me insight on what is going on in that case?
And here's how I initialize the App
import firebase from 'firebase';
try {
const config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
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,
};
firebase.initializeApp(config);
} catch (e) {}
export const githubProvider = new firebase.auth.GithubAuthProvider();
export const firebaseRef = firebase.database().ref();
export default firebase;

Categories

Resources