Service messaging is not available - firebase

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

Related

Firebase Cloud messaging (Notification)

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

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.'
}
},

TypeError: _app.default.firestore is not a function. (In '_app.default.firestore()', '_app.default.firestore' is undefined)

The error occurs right when I build the project, it doesn't return any information about where the error is or something, help me please!
My firebase config:
import firebase from 'firebase/compat/app';
require('firebase/firestore')
// 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
const firebaseConfig = {
apiKey: "-",
authDomain: "-",
projectId: "-",
storageBucket: "-",
messagingSenderId: "-",
appId: "-"
};
// Initialize Firebase
let app;
if(firebase.apps.length === 0){
app = firebase.initializeApp(firebaseConfig);
}else{
app = firebase.app()
}
const db = firebase.firestore();
export { db };
Below I leave my fire.js finds all the logic for the file where the post is sent with image text.
Note: firebase collection is configured correctly, with name and my fields.
import firebaseConfig from './firestore';
import firebase from "firebase/compat/app";
class Fire {
constructor() {
firebase.initializeApp(firebaseConfig);
}
addPost = async ({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri);
return new Promise((res, rej) => {
this.firestore
.collection("posts")
.add({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri,
})
.then((ref) => {
res(ref);
})
.catch((error) => {
rej(error);
});
});
};
uploadPhotoAsync = async (uri) => {
const path = `photos/${this.uid}/${Date.now()}.jpg`;
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebase.storage().ref(path).put(file);
upload.on(
"state_changed",
(snapshot) => {},
(err) => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
};
get firestore() {
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;

Firebase config file dynamic import at Vue

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
}

Resources