I have a firebase config file like this:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const firebaseApp = firebaseApp;
I am trying to authenticate a user but keep getting firebaseApp.auth() is not a function.
let me = db.collection('staff').where('email', '==', this.current_user.email)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.fbUser = doc.id;
let email = doc.data().email;
let pw = doc.data().key;
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
//console.log('Already authenticated.');
} else {
firebaseApp.auth().signInWithEmailAndPassword(email, pw)
.then(liu => {
//console.log('Logged in', liu.uid);
let uid = liu.uid;
this.$localStorage.set('fbId',this.fbUser, 0);
this.$localStorage.set('fbAuthId', uid, 0);
me.update({
is_active: true
});
});
} // end if
});
});
Don't I have to configure the app? There's no auth functionality in #firebase.
Any help is appreciated.
You should add the auth Firebase service in your initialization, as follows:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
import "#firebase/auth"; // <- NEW
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const auth = firebaseApp.auth(); // <- NEW
export const firebaseApp = firebaseApp;
Then, in your component, you do:
auth.onAuthStateChanged(user => {})
and
auth.signInWithEmailAndPassword(email, pw)
Related
I want to integrate FCM with nextjs project.
This error is occurring whenever I save the firebase.js config file. I'm not being able to use Firebase Cloud Messaging in Firebase V9.
I use firebase 9.10.0
my firebase.js config
import { initializeApp } from 'firebase/app';
import { getToken, getMessaging, onMessage } from 'firebase/messaging';
const firebaseConfig = {
apiKey: "*************",
authDomain: "********************",
projectId: "******************",
storageBucket: "*****************",
messagingSenderId: "*************",
appId: "**********************"
};
console.log('*** Environment ***', process.env.REACT_APP_ENV)
console.log('*** Firebase Config ***', firebaseConfig)
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export const getOrRegisterServiceWorker = () => {
if ('serviceWorker' in navigator) {
return window.navigator.serviceWorker
.getRegistration('/firebase-push-notification-scope')
.then((serviceWorker) => {
if (serviceWorker) return serviceWorker;
return window.navigator.serviceWorker.register('/firebase-messaging-sw.js', {
scope: '/firebase-push-notification-scope',
});
});
}
throw new Error('The browser doesn`t support service worker.');
};
export const getFirebaseToken = () =>
getOrRegisterServiceWorker()
.then((serviceWorkerRegistration) =>
getToken(messaging, { vapidKey: "***********", serviceWorkerRegistration }));
export const onForegroundMessage = () =>
new Promise((resolve) => onMessage(messaging, (payload) => resolve(payload)));
Ather searing a lot I found solutions:
I change the code of my firebase.js file to the below code
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
import localforage from "localforage";
const firebaseConfig = {
apiKey: "**********************",
authDomain: "*******************",
projectId: "******************",
storageBucket: "****************",
messagingSenderId: "****************",
appId: "**************"
};
// Initialize Firebase
const firebaseCloudMessaging = {
init: async () => {
initializeApp(firebaseConfig);
try {
const messaging = getMessaging();
const tokenInLocalForage = await localStorage.getItem("fcm_token");
// Return the token if it is alredy in our local storage
if (tokenInLocalForage !== null) {
return tokenInLocalForage;
}
// Request the push notification permission from browser
const status = await Notification.requestPermission();
if (status && status === "granted") {
// Get new token from Firebase
const fcm_token = await getToken(messaging, {
vapidKey:
"********************",
});
console.log("token in fcm_token", fcm_token);
// Set token in our local storage
if (fcm_token) {
localforage.setItem("fcm_token", fcm_token);
return fcm_token;
}
}
} catch (error) {
console.error(error);
return null;
}
},
};
export { firebaseCloudMessaging };
I'm new here. Been having issues with working with the firebase cloud messaging. Tried sending notification throught the the notification composer but it not promting any notification at my side. N:B I have no knowledge of backend technologies, so only implemented it in the front-end.
This is my code
// For the App.js folder
import { initializeApp } from "firebase/app";
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
Notification.requestPermission().then((permission) => {
if(permission === 'granted'){
console.log('permission granted')
}
})
.catch((err) => {
console.log('permission denied:', err)
})
getToken(messaging, {vapidKey: 'BMRthb-93vz-iQl0XQA8AsKbzMyLq-f2JCB00B2rMb35Z_1iVdWX8CquQ820-z6vyMmdDB0W46FIIS3R5IhTbXY'}).then((token) => {
console.log('my token is', token);
});
onMessage(messaging, (payload) => {
console.log(payload.notification);
new Notification(payload.notification.title, {
body:payload.notification.body
})
})
For the Service worker folder
import { getMessaging, onBackgroundMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('received background messages:', payload)
const notificationTitle= payload.notification.notificationTitle
const notificationBody = {
body: payload.notification.body,
}
self.registration.showNotification(notificationTitle, notificationBody);
})
i would apprecitate if someone can come through for me. thanks[image 1(app.jsimage2 (app.js)](https://i.stack.imgur.com/tMoq2.png)
Tried evrything, but to no avail. I want to be able to send notifications to user via the notificTION COMPOSER
firebaseInit.js
import firebase from 'firebase/app';
const FirebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
};
firebase.initializeApp(FirebaseConfig);
export default firebase;
what did i try;
var data = async function getConfig() {
var x= await fetch('/someurl')
.then(function(res) {
return res.json();
})
.catch(function(err) {
return console.log(err);
});
return x;
};
firebase.initializeApp(getConfig());
export default firebase;
i can get external config file but it is not exporting..................................
Export a promise-returning function...
// firebaseInit.js
import firebase from "firebase/app";
export default function() {
return fetch('/someurl').then(res => {
firebase.initializeApp(res.json());
return firebase
}).catch(err => {
console.log(err);
throw err;
});
};
Await it in the importing module...
import firebasePromise from 'firebaseInit.js'
let firebase;
async someFunction() {
firebase = firebase || await firebasePromise();
// use firebase
}
So I'm not sure how to do this exactly. Here is what I have:
In my Index.js I have
Index.getInitialProps = async function () {
const firebase = require('firebase')
const firebaseConfig = {
apiKey: "examplezbxW_9nKoUjas",
authDomain: "example-prod.firebaseapp.com",
databaseURL: "https://example-prod.firebaseio.com",
projectId: "example-prod",
storageBucket: "example-prod.appspot.com",
messagingSenderId: "1234567890",
appId: "1:1234567890:web:1234567890"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const db = firebase.firestore()
const data = db.collection('data').get()
return {
data
}
}
This gives me an error of FirebaseError: projectId must be a string in FirebaseApp.options
(Maybe I need to run the firebase node package and login...)
It says the error is occurring at this line const db = firebase.firestore()
Any help is appreciated. Maybe this isn't the spot I should be trying to load firestore data... not sure.
I also considered creating a node server and doing it that way, but ideally, I'd like to avoid that.
Okay, so there was a couple changes I made to fix this.
I moved my firebase initialization to another file and that file looked like this:
import firebase from 'firebase/app'
import 'firebase/firestore'
export function loadDB() {
try {
var config = {
apiKey: "YOUR INFO HERE",
authDomain: "YOUR INFO HERE.firebaseapp.com",
databaseURL: "https://YOUR INFO HERE.firebaseio.com",
projectId: "YOUR INFO HERE",
storageBucket: "YOUR INFO HERE.appspot.com",
messagingSenderId: "YOUR INFO HERE",
appId: "YOUR INFO HERE"
};
firebase.initializeApp(config);
} 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);
}
}
return firebase;
}
Then, in my NextJS componenet, in the getInitialProps method, I have:
import { loadDB } from '../lib/db'
Index.getInitialProps = async function () {
const db = await loadDB()
let data = []
const querySnapshot = await db.firestore().collection('data').get()
querySnapshot.forEach(doc => {
data.push(doc.data())
})
return {
data
}
}
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firebase = require('firebase/app');
const credentials = require('./credentials.json');
const db = admin.firestore();
const user = require('./http-functions/user-creation')
var config = {
apiKey: "KEY",
authDomain: "ecommerce.firebaseapp.com",
databaseURL: "https://ecommerce.firebaseio.com",
projectId: "ecommerce",
storageBucket: "ecommerce.appspot.com",
messagingSenderId: "ID"
};
firebase.initializeApp(config)
admin.initializeApp({
credential: admin.credential.cert(credentials),
databaseURL: "https://ecommerce.firebaseio.com",
projectId: "ecommerce"
});
exports.addUser = functions.https.onRequest((req, res) => user.addUser(req, res, db, firebase))
I'm importing firebase so that I can use the firebase.auth() to create a new user on cloud functions firestore. But I'm having this error where it says that when I run my firebase deploy:
Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
at FirebaseAppError.FirebaseError [as constructor]
Below is the code for adding a new user
module.exports = {
addUser: function(req, res, db, firebase, admin) {
firebase.auth().createUserWithEmailandPassword(email, password)
.then(userRecord => {
const uid = userRecord.uid;
const email = userRecord.email;
return firebase.firestore()
.collection('users')
.doc(uid)
.set({email: email},
{merge: true});
})
.catch(err => {
console.log(err)
})
}
}
Try assigning the intitializeApp into a const and use it instead of firebase.auth()
Something like:
var config = {
apiKey: "KEY",
authDomain: "ecommerce.firebaseapp.com",
...
};
const firebaseApp = firebase.initializeApp(config)
module.exports = {
addUser: function(req, res, db, firebase, admin) {
firebaseApp.auth().createUserWithEmailandPassword(email, password)
...
}
}