Firebase with react issue - reactjs

I am trying to connect my ReactJs app to firebase to implement push notifications. Every time I try to console log the token that I get from firebase, this error always shows up and I don't know how I can solve it. Here is a screenshot of the error :
I added the following lines in my firebase-messaging-sw.js which is located inside my public file and here it is :
importScripts('https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js');
importScripts('https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js');
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function (registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function (err) {
console.log('Service worker registration failed, error:', err);
});
}
firebase.initializeApp({
messagingSenderId: "msg_id",
})
const initMessaging = firebase.messaging()
There is also the file firebase.js and its content which I get the data inside the config object from my firebase project which is already registered :
import firebase from "firebase";
const config = {
apiKey: "my_api_key",
authDomain: "my_domain",
databaseURL: "my_database_url",
projectId: "project_id",
storageBucket: "storage-bucket",
messagingSenderId: "msg_id",
appId: "app_id",
measurementId: "measure_id"
}
firebase.initializeApp(config);
firebase.analytics();
export default firebase;
And here is my useEffect where I am trying to print the token :
useEffect(() => {
const messaging = firebase.messaging();
messaging.requestPermission().then(() => {
return messaging.getToken()
}).then(token => {
console.log("TOKEN :", token)
})
}, [])
I tried many fixes and nothing worked and I still get the same error. I hope that anyone can help me with this. Thanks in advance.

Related

Issue with Firebase push notifications in Version 9 - React JS

I am currently setting up push notifications on my react/firebase project.
I have followed all the steps and added the firebase-messaging-sw.js, getToken etc..
I used to be able to get a FCM token back from getToken but I am no longer able to do so due to this error message:
An error occurred while retrieving token. FirebaseError: Messaging:
A problem occurred while subscribing the user to FCM: Request contains an invalid argument.
(messaging/token-subscribe-failed).
at requestGetToken (requests.ts:67:1)
at async getNewToken (token-manager.ts:139:1)
This error occurs when I call the getTokenFound() method
Before when this was working, I would also have problems with the service worker if I was running the same project on a different system. Only my main development system was able to not hit the service worker error:
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope
('http://localhost:3000/firebase-cloud-messaging-push-scope%27) with script
('http://localhost:3000/firebase-messaging-sw.js%27): ServiceWorker script evaluation failed
(messaging/failed-service-worker-registration).
Two two issues seem to be persistent, often it seems like an error loop happens if I deny the notification permissions and then try to allow them again, I would get the invalid argument error.
Here are my relevant code blocks below, I'm really not sure what else to change here. The react setup for push notifications seems very inconsistent depending on what machine Im on. Many thanks for any insight!
firebase-messaging-sw.js (in public dir with index.html)
importScripts('https://www.gstatic.com/firebasejs/8.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.1/firebase-messaging.js');
const firebaseConfig = {
apiKey: DATA,
authDomain: DATA,
databaseURL: DATA,
projectId: DATA,
storageBucket: DATA,
messagingSenderId: DATA,
appId: DATA,
measurementId: DATA
};
firebase.initializeApp(firebaseConfig);
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,
icon: "../src/assets/image/default.svg",
tag: "notification-1"
};
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
firebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getFunctions } from "firebase/functions";
import { getStorage } from "firebase/storage";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import 'firebase/storage';
export const app = initializeApp({
apiKey: data,
authDomain: data,
databaseURL: data,
projectId: data,
storageBucket: data,
messagingSenderId: data,
appId: data,
measurementId: data
});
export const messaging = getMessaging(app);
export const firestore = getFirestore(app);
export const functions = getFunctions(app);
export const storage = getStorage(app);
export const getTokenFound = async () => {
let currentToken = "";
try {
currentToken = await getToken(messaging, { vapidKey: myVapidKey});
if (currentToken) {
console.log("CURRENT TOKEN", currentToken)
} else {
}
} catch (error) {
console.log("An error occurred while retrieving token. ", error);
}
return currentToken;
};
export const onMessageListener = () =>
new Promise((resolve) => {
onMessage(messaging, (payload) => {
console.log("payload", payload)
resolve(payload);
});
});

Firebase - getToken() throws Unsupported MIME type

I have a react-create-app application, in which I used firebase for pushnotification. Recently I upgraded firebase from 8.* to 9.*. While getting push token, it throws the following error:
FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://9fd5-49-204-137-92.ngrok.io/firebase-cloud-messaging-push-scope') with script ('https://9fd5-49-204-137-92.ngrok.io/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html'). (messaging/failed-service-worker-registration).
In firebase.js, I have the following code set, which throws the above mentioned error
import { initializeApp } from "firebase/app"
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const message_key = "key"
var firebaseConfig = {
apiKey: "apikey",
authDomain: "authdomain",
projectId: "project-app",
storageBucket: "******.com",
messagingSenderId: "id",
appId: "appid",
measurementId: "mid"
};
const firebaseApp = initializeApp(firebaseConfig);
let messaging = getMessaging(firebaseApp);
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register(process.env.PUBLIC_URL + "/firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration);
getToken({messaging, vapidKey: message_key})
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
})
.catch(function(err) {
console.log("Service worker registration failed, error:", err);
});
}}
How can I solve this issue?
Moving firebase-messaging-sw.js file to public directory solved the above issue.

Firebase: Cannot use import statement outside a module and require is not defined

I meet Cannot use import statement outside when use: import * as firebase from "firebase" and required is not defined when changing it to: const firebase = require("firebase"); The error comes in the file: firebase-messaging-sw.js
My structure folder is like this:
-app:
+firebase-messaging-sw.js
+push-notification.js
+index.js
+routes: => Account: => Login: => Login.js
-build:
+webpack.config.client.dev.js
-package.json
...
index.js:
import 'file-loader?name=firebase-messaging-sw.js!./firebase-messaging-sw.js';
Login.js:
import { initializeFirebase, getTokenFirebase } from "../../../push-notification"
React.useEffect(() => {
initializeFirebase();
getTokenFirebase();
}, []);
push-notification.js:
import * as firebase from "firebase";
export const initializeFirebase = () => {
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxxx",
databaseURL:
"https://xxxxx.firebasedatabase.app",
projectId: "xxxx",
storageBucket: xxxx",
messagingSenderId: "xxxx",
appId: "xxxx",
measurementId: "xxxx",
};
if (firebase.default.apps.length === 0) {
firebase.default.initializeApp(firebaseConfig);
} else {
firebase.default.app(); // if already initialized, use that one
}
};
export const getTokenFirebase = async () => {
const messaging = firebase.default.messaging();
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker
.register("./firebase-messaging-sw.js")
.then(function (registration) {
console.log("Registration successful, scope is:", registration.scope);
messaging
.getToken({
vapidKey:
"xxxx",
serviceWorkerRegistration: registration,
})
.then((currentToken) => {
if (currentToken) {
console.log("current token for client: ", currentToken);
localStorage.setItem("registrationToken", currentToken);
// 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."
);
// 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
});
})
.catch(function (err) {
console.log("Service worker registration failed, error:", err);
});
});
}
};
firebase-messaging-sw.js:
import * as firebase from "firebase"; // This is where the error come!
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxxx",
databaseURL:
"https://xxxxx.firebasedatabase.app",
projectId: "xxxx",
storageBucket: xxxx",
messagingSenderId: "xxxx",
appId: "xxxx",
measurementId: "xxxx",
};
if (firebase.default.apps.length === 0) {
firebase.default.initializeApp(firebaseConfig);
} else {
firebase.default.app();
}
webpack.config.client.dev.js:
plugins: [
new OfflinePlugin({
relativePaths: false,
publicPath: '/',
appShell: '/',
ServiceWorker: {
events: true,
entry: path.join(process.cwd(), 'app/firebase-messaging-sw.js')
},
excludes: ['.htaccess'],
}),
I have no idea how this error comes, can someone give me some instructions?
Did you install firebase as an npm module?
npm install --save firebase
Make sure that the package exists in the package.json file. Only then will you be able to import the module.
var firebase = require('firebase');
var app = firebase.initializeApp({ ... });

Reactjs: TypeError: Failed to register a ServiceWorker for scope with script: A bad HTTP response code (404) was received when fetching the script

I run into error: "TypeError: Failed to register a ServiceWorker for scope ('http://localhost:"Port Number"/') with script ('http://localhost:"Port Number"/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script" when trying to config my Firebase messaging.
I am using airframe-dashboard v 0.1.0, so there is no public folder. So I try creating one like this:
My firebase-messaging-sw.js:
import * as firebase from "firebase";
import "firebase/database";
import 'firebase/messaging';
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxx",
projectId: "myhealthqlpkv1",
storageBucket: "xxxx",
messagingSenderId: "xxxxx",
appId: "xxxx",
measurementId: "xxxx"
};
// Initialize Firebase
firebase.default.initializeApp(firebaseConfig);
// var db = firebase.default.database().ref();
const messaging = firebase.default.messaging();
export default messaging;
In my Login.js, I try to register and getToken:
import messaging from "../../../public/firebase-messaging-sw"
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration.scope);
messaging.getToken({vapidKey: 'xxxx', serviceWorkerRegistration : registration })
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
localStorage.setItem('registrationToken', currentToken);
// 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.');
// 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
});
})
.catch(function(err) {
console.log("Service worker registration failed, error:" , err );
});
}
Now I run into the above error, please help me with this !!!

MIME type error when integration react app with FCM

I am trying to integrate my react app with Firebase to implement push notifications. I have this file with all configurations inside my src folder :
import firebase from 'firebase/app';
import 'firebase/messaging';
const config = {
apiKey: "API_KEY",
authDomain: "MY_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "MEASURE_ID"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
export const requestFirebaseNotificationPermission = () =>
new Promise((resolve, reject) => {
messaging
.requestPermission()
.then(() => messaging.getToken())
.then((firebaseToken) => {
resolve(firebaseToken);
})
.catch((err) => {
reject(err);
});
});
export const onMessageListener = () =>
new Promise((resolve) => {
messaging.onMessage((payload) => {
resolve(payload);
});
});
And, here is how I implement the function to make push notifications work out inside my App.js :
// Load the FCM configuration parameters and activate the push notifications through the app
requestFirebaseNotificationPermission()
.then((firebaseToken) => {
// eslint-disable-next-line no-console
console.log("CHECK_FCM_TOKEN", firebaseToken);
this.setState({ fcmToken: firebaseToken })
})
.catch((err) => {
return err;
});
This is the error that I always get and I am stuck since long with no solutions at all :
If there could be any help to fix this, I would be thankful.
I had similiar issue. The problem was i was not loading the service worker file properly.
Place your service worker file in public folder and try accessing it.
For eg: my service worker file(firebase-messaging-sw.js) was placed in public folder. So if i open http://localhost:3000/firebase-messaging-sw.js i can view the js file.
Before react was trying to fetch this file and returned an html(default index page) file and caused to return MIME type error.

Resources