Firebase Cloud messaging (Notification) - firebase

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

Related

Service messaging is not available

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 };

Why is Firebase Cloud Messaging not showing on foreground in my vue app?

package.json
"firebase": "^9.14.0",
public/firebase-messaging-sw.js
`
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js')
try {
const config = {
apiKey: "AIzaSyBzFxb1h0INNwZ2dKMF83PfoMXa2aCdXqM",
authDomain: "jobdoh-dc1db.firebaseapp.com",
projectId: "jobdoh-dc1db",
storageBucket: "jobdoh-dc1db.appspot.com",
messagingSenderId: "922163524694",
appId: "1:922163524694:web:a50be771626fa1356077f7",
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(payload => {
console.log("Payload :> ", payload)
return self.registration.showNotification("hello", { body: "aaa" })
})
} catch (err) {
console.log("err in sw :> ", err)
}
All console.log that in the firebase-messaging-sw.js are not working.
src/plugins/firebase.js
import { initializeApp, getApps } from 'firebase/app';
import { getMessaging } from 'firebase/messaging'
import '#firebase/app';
const config = {
apiKey: "AIzaSyBzFxb1h0INNwZ2dKMF83PfoMXa2aCdXqM",
authDomain: "jobdoh-dc1db.firebaseapp.com",
databaseURL: "https://jobdoh-dc1db-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "jobdoh-dc1db",
storageBucket: "jobdoh-dc1db.appspot.com",
messagingSenderId: "922163524694",
appId: "1:922163524694:web:a50be771626fa1356077f7",
measurementId: "G-VJ4952421E"
};
const apps = getApps();
const app = !apps.length ? initializeApp(config) : apps[0];
const messaging = getMessaging(app)
export default messaging;
src/index.js
import {createApp} from "vue";
import firebaseMessaging from './plugins/firebase';
const app = createApp();
app.config.globalProperties.$messaging = firebaseMessaging;
app.mount("#app");
I declare the messaging service as a global properties.
And use it in the customPage(eg. NotiPage.vue)
src/pages/NotiPage.vue
<template>
<v-btn #click="getToken">Get Token</v-btn>
</template>
<script>
import { getMessaging, onMessage, getToken } from "firebase/messaging";
export default {
methods: {
async getToken() {
const token = await getToken(this.$messaging, {
ServiceWorkerRegistration: "/public/firebase-messaging-sw.js",
vapidKey:
"BKOVTA3E_8xNS8MqBNVWxv8bxlaOman4gaY5jXpMG-wpev19uWFANeyKy6rRDxfx8QEarlUSqwJ7UNiuripRA4c",
});
if (token) {
console.log(token); // I got the token
} else {
// Request permission
}
},
},
mounted(){
const message = getMessaging();
onMessage(message, (payload) => console.log("Messages :> "), payload)
}
}
</script>
I got the token and message on the console. But not show the noti popup in my chrome. I turn on my notification permission on my computer setting and allow the notification on my chrome.
This is console.log image.
Pls advice me. Where did I wrong?
I want to appear notification popup on my browser and running the process in background.

Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK. [Firebase Auth on NextJS App]

I'm trying to deploy my NextJS App on Vercel. But I'm getting this error.
Also, my project runs smoothly in development mode, but why am I getting such an error while deploying?
Firebase.ts File
import { initializeApp } from "firebase/app";
import {
getAuth,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut,
} from "firebase/auth";
import { handlerSetUser } from "./utils";
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_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
onAuthStateChanged(auth, (user: any) => {
if (user) {
handlerSetUser(user);
} else {
handlerSetUser(false);
}
});
export const login = async (email: any, password: any) => {
try {
const result = await signInWithEmailAndPassword(auth, email, password);
return result;
} catch (error: any) {
alert(error.message);
}
};
export const logout = async () => {
try {
await signOut(auth);
} catch (error: any) {
alert(error.message);
}
};
Vercel Deployment Error
_errorFactory: ErrorFactory {
service: 'auth',
serviceName: 'Firebase',
errors: {
'dependent-sdk-initialized-before-auth': 'Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.'
}
},

How to fix "Cannot read property 'firestore' of null" in Firestore

I will try to change the setting in the function of firestore() but doesn't work.
I read the document and they said that this future will be removed in a future release but I don't seen the solve. So I hope anyone can help me settle this problem
Operating System version: Majove 10.14.2
Library version: ^6.1.0
Firebase Product: firestore
import * as firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
// Initialize Firebase
let firebaseApp = null
if (!firebase.app.length) {
firebaseApp = firebase.initializeApp(firebaseConfig)
}
firebaseApp.firestore().settings({
ssl: false,
timestampsInSnapshots: true
})
export default firebaseApp.firestore()
See https://firebase.google.com/docs/web/setup .
Basic way to initialize firebase is this.
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import "firebase/functions";
import "firebase/storage";
import "firebase/messaging";
import "firebase/performance";
const config = {
// set your config here
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
const storage = firebase.storage();
const functions = firebase.functions();
const firestore = firebase.firestore();
let messaging = null;
try {
if (firebase.messaging.isSupported()) {
messaging = firebase.messaging();
messaging.usePublicVapidKey("your publicVapidKey here");
}
} catch (e) {}
const perf = firebase.performance();
export { firebase, auth, storage, functions, firestore, messaging };
I edited your code.
import firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const firestore = firebase.firestore();
firestore.settings({
ssl: false,
timestampsInSnapshots: true
})
export default firestore;

firestore vue.js: auth() is not a function

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)

Resources