Firebase initialization - javascript

I am using Firebase for the back-end of my app, my firebase configuration looks like :
const firebaseConfig = {
apiKey: 'xx',
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
}
firebase.initializeApp(firebaseConfig)
my question is what if i some configuration data is incorrect.
So how to check if my Firebase database is initialized correctly ? thanks

You can write a test case to check if your configuration is valid.
const getPost = async () => {
const snapshot = await firestore.collection('Posts').get();
const myPosts = snapshot.docs.map(collectIdsAndDocs);
console.log(myPosts);
setPosts({ myPosts });
};
const createPost = async (post) => {
const docRef = await firestore.collection('Posts').add(post);
const doc = await docRef.get();
console.log(doc);
};
createPost({ Title: 'My First Post', Content: 'My content' });
getPost();

Related

Reference error: self is not defined when implementing firebase messaging

In my Nextjs project I'm trying to implement push notification with firebase messaging (my firebase version is 8.10.0), after creating the firebase-messaging-sw.js file in my public folder:
importScripts(
"https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"
);
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: null,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I now created a [utility] file (that I named Firebase.js) where I'll implement helper functions like the request token function.
Here is a code snippet from that file:
import firebase from "firebase/app";
import "firebase/messaging";
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
!firebase.apps.length && firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
export const requestForToken = () => {
// func that generates and returns a FCM token
};
export const onMessageListener = async () =>
new Promise((resolve) => {
messaging.onMessage((payload) => {
resolve(payload);
}
);
});
Now to use those functions I created another file Notification.js:
import React, { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { requestForToken, onMessageListener } from "./Firebase";
const Notification = () => {
const [notification, setNotification] = useState({ title: "", body: "" });
useEffect(() => {
requestForToken();
}, []);
const ToastDisplay = () => {
return (
<>
<b>{notification?.title} </b>
<p>{notification?.body}</p>
</>
);
};
const notify = () => toast(<ToastDisplay />);
useEffect(() => {
notification?.title && notify();
}, [notification]);
onMessageListener()
.then((payload) => {
setNotification({
title: payload?.notification?.title,
body: payload?.notification?.body,
});
})
.catch((err) => console.log("failed: ", err));
return <></>;
};
export default Notification;
I imported Notification.js in _app.js and when I run my app I get the following error:
And I can't understand the reason why and [more importantly] how to fix it.
Hope this should work as All the setup I have worked inclined with your requirement,
Here are version's those I am using,
"next": "^12.0.7",
"firebase": "^8.6.8",
"#firebase/installations": "^0.5.4"
Here is firebase init'n,
/* eslint-disable import/prefer-default-export */
// import firebase from 'firebase/app';
import firebaseClient from "firebase/app";
import "firebase/installations";
import "firebase/auth";
import "firebase/messaging";
import "firebase/functions";
import "firebase/analytics";
const CLIENT_CONFIG = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***",
};
if (typeof window !== "undefined" && firebaseClient.apps?.length <= 0) {
firebaseClient.initializeApp(CLIENT_CONFIG);
(window as any).firebase = firebaseClient;
if (firebaseClient.messaging.isSupported()) {
const msg = firebaseClient.messaging();
const creds = {
vapidKey: process.env.NEXT_PUBLIC_FIREBASE_WEB_FCM_TOKEN
? process.env.NEXT_PUBLIC_FIREBASE_WEB_FCM_TOKEN
: "",
};
msg.getToken(
creds,
)
.then((token) => {
// Send the token to your app server if notification service granted
console.log(token);
})
.catch((err) => {
// If user blocks notification service
console.log(err);
});
}
}
export { firebaseClient };
Here is the firebase-messaging-sw.js at public folder
/* eslint-disable space-before-function-paren */
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("../firebase-messaging-sw.js")
.then((registration) => {
console.log("Registration successful, scope is:", registration.scope);
})
.catch((err) => {
console.log("Service worker registration failed, error:", err);
});
}
Hope this get your working!.
Try this:
import { initializeApp } from "firebase/app";
import { getMessaging, onMessage } from "firebase/messaging";
const firebaseConfig = {
// ...
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// ...
})
// ...
Also take a look into firebase docs
EDIT:
Take a look here too. It's showing how to receive messages into client.
Hope I've helped you with something :)

Unable to request permission to fetch device token in javascript

I am trying to fetch my device token in javascript. I have included these imports in my HTML page:
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-database-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging-compat.js"></script>
My javascript:
const firebaseConfig = {
messagingSenderId: "MY SENDER ID FROM CONSOLE",
apiKey: "MY API KEY FROM CONSOLE",
authDomain: "domain_name.firebaseapp.com",
projectId: "domain_name",
storageBucket: "domain_name.appspot.com",
messagingSenderId: "01234643924812",
databaseURL: "https://domain_name-default-rtdb.firebaseio.com",
appId: "1:1230535236326:web:f0fc4f32t23t235122e112c800"
};
const app = firebase.initializeApp(firebaseConfig);
(async()=>{
try {
await firebase.messaging().requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
})();
When I execute the code, I get this error:
TypeError: firebase.messaging(...).requestPermission is not a function
What am I doing wrong?

Next Js cant find Service messaging (firebase-cloud-messaging)

Hi I using firebase cloud messaging in next js project and when I try to run or build my project I get this error :
info - Checking validity of types
info - Creating an optimized production build
info - Compiled successfully
info - Collecting page data ...node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
Error: Service messaging is not available
at Provider.getImmediate (file:///I:/Work/Web/Php/Project/wamp/www/test/node_modules/#firebase/component/dist/esm/index.esm2017.js:147:23)
at getMessagingInWindow (I:\Work\Web\Php\Project\wamp\www\test\node_modules#firebase\messaging\dist\index.cjs.js:1460:74)
at I:\Work\Web\Php\Project\wamp\www\test.next\server\pages_app.js:117:83 {
type: 'Error'
}
my code :
it seems this problem happens because using getMessaging
firbase.js
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from "firebase/messaging";
var firebaseConfig = {
apiKey: "----",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export const fetchToken = (setTokenFound) => {
return getToken(messaging, {vapidKey: '---'}).then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
setTokenFound(true);
// Track the token -> client mapping, by sending to backend server
// show on the UI that permission is secured
} else {
console.log('No registration token available. Request permission to generate one.');
setTokenFound(false);
// shows on the UI that permission is required
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// catch error while creating client token
});
}
export const onMessageListener = () =>
new Promise((resolve) => {
onMessage(messaging, (payload) => {
resolve(payload);
});
});
firebase-messaging-sw.js
// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-messaging-compat.js');
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "----",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
_app.tsx
import {fetchToken,onMessageListener} from '../tools/firebase'
const [notification, setNotification] = useState({title: '', body: ''});
const [isTokenFound, setTokenFound] = useState(false);
useEffect(() => {
fetchToken(setTokenFound)
onMessageListener().then(payload => {
setNotification({title: payload.notification.title, body: payload.notification.body})
console.log(payload);
}).catch(err => console.log('failed: ', err));
}, []);
i had same issue turns out it was firebase v9 issue
using firebase v8 worked for me
npm i firebase#8.2.3
after installing v8 don't forget to change syntax its firebase.initializeApp(firebaseConfig);

messaging.requestPermission is not a function

trying to send push notification to app but i need permission from user for that but getting this error that messaging.requestPermission is not a function ,
here is my code for push notification.js file
import * as firebase from 'firebase/app';
import { getMessaging } from "firebase/messaging";
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "pushnotification-9b180",
storageBucket: "pushnotification-9b180.appspot.com",
messagingSenderId: "878043563283",
appId: "1:878043563283:web:c2a44f3c8b02ad8a17c6e6",
measurementId: "G-GMWQKL94ZD"
});
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = getMessaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
}
Here is the screenshot of errorserros
What are you using react-native or react?
but in react-native way you need add this line
import messaging from '#react-native-firebase/messaging';
you donĀ“t need
const messaging = getMessaging();
import * as firebase from 'firebase/app';
import { getMessaging } from "firebase/messaging";
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "pushnotification-9b180",
storageBucket: "pushnotification-9b180.appspot.com",
messagingSenderId: "878043563283",
appId: "1:878043563283:web:c2a44f3c8b02ad8a17c6e6",
measurementId: "G-GMWQKL94ZD"
});
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = getMessaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
}

How can I retrieve data from my firebase database?

I have tried many ways to get data from my firebase database, but they dont work.
Is there any simple way to retrieve data from my firebase database?
my js code:
var firebaseConfig = {
apiKey: "REDACTED",
authDomain: "REDACTED.firebaseapp.com",
projectId: "REDACTED",
storageBucket: "REDACTED.appspot.com",
messagingSenderId: "474155068193",
appId: "REDACTED",
measurementId: "G-715TVNY07N"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log(firebase);
var database = firebase.database();
var ref = database.ref('en');
function lah(){
var data = {
kommentti: document.getElementById("viesti").value
}
ref.push(data);
}
my database:
I would like to know what is inside those kommenttis.
If you want to get the data just once without a listener you can use a function like this one:
const getData = async () => {
return firebase
.database()
.ref("en")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
const kommentti = childData.kommentti;
});
});
};

Categories