Firebase+ReactJS: 'importScripts' is not defined - reactjs

In my Firebase-message-sw.js:
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');
// BG-4OSXtyPghJusRY97ROcRWcTnaa9gWGm1jIHRyfLdfiXhzoItl5QfkLxUbj9MytqwobDAUneyRm9FYq3xWuuc
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);
});
I am getting the following error: 'importScripts' is not defined.
I am trying to get the token, but one more error is happening in this line:
getToken({messaging ,vapidKey: messageKey})
The error is:
The script has an unsupported MIME type ('text/html').

Better replace with this code, worked for me
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/9.6.8/firebase-messaging.js");
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
// your firebaseConfig
};
// eslint-disable-next-line no-undef
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
// eslint-disable-next-line no-undef
const messaging = firebase.messaging();
// eslint-disable-next-line no-undef
messaging.onBackgroundMessage(function (payload) {
console.log("Received background message ", payload);
// dataHandler();
// const notificationTitle = payload.notification.title;
// const notificationOptions = {
// body: payload.notification.body,
// // icon: "./logo192.png",
// };
// // eslint-disable-next-line no-restricted-globals
// return self.registration.showNotification(
// notificationTitle,
// notificationOptions
// );
});

Try directly importing the firebase packages
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
var firebaseConfig = {
apiKey: "*******************************",
authDomain: "********************",
projectId: "***************",
storageBucket: "**********",
messagingSenderId: "********",
appId: "**********************"
};
const fire = firebase.initializeApp(firebaseConfig);
export default fire;

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

react firebase config .env file doesn't work

i have a question about configuration of firebase with a react app. I put all firebase config info in .env file at the top directory as environmental variables. When I tried to use them as process.env.REACT_APP_smth, they all didn't work. Once I replaced the variables to real, raw config info, my app worked. But For sure, it's too dangerous so I don't wanna do it.
Also, the .env file was darker in vs code like mentioning it's not valid or smth.
Anyone knows how to tackle with this issue??
Thanks for your time and effort here in advance.
.env
I replaced REACT_APP_FIREBASE_API_KEY with 123456789.
REACT_APP_FIREBASE_API_KEY = "123456789"
REACT_APP_FIREBASE_AUTH_DOMAIN = "kinnikuhub.firebaseapp.com"
REACT_APP_FIREBASE_DATABASE_URL = "https://kinnikuHub.firebaseio.com"
REACT_APP_FIREBASE_PROJECT_ID = "kinnikuhub"
REACT_APP_FIREBASE_STORAGE_BUCKET = "kinnikuhub.appspot.com"
REACT_APP_FIREBASE_MESSAGING_SENDER_ID = "131675559"
REACT_APP_FIREBASE_APP_ID = "1:131675559:web:3ca3bbad263b6be90ff282"
firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// import { getAnalytics } from "firebase/analytics";
import { addDoc, getDocs, getFirestore } from "firebase/firestore"
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { collection } from "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
export const db = getFirestore();
export const auth = getAuth(app);
const provider = new GoogleAuthProvider();
export const signInWithGoogle = () => {
signInWithPopup(auth, provider)
.then((res) => {
console.log(res);
// todo: Why create users table?? To let users have personal info, number of answers and quizzes cretaed, biography, sns links, etc
// todo: 1st, check if res.user exists
const userCollectionRef = collection(db, 'users');
let userExistance = false;
console.log(`currentUser.uid => ${res.user.uid}`)
console.log(userExistance)
const checkUserExists = async () => {
const querySnapshot = await getDocs(userCollectionRef);
querySnapshot.forEach( (doc) => {
// doc.data() is never undefined for query doc snapshots
// console.log(doc.id, " => ", doc.data());
// console.log(`currentUser.uid => ${res.user.uid}`)
if (doc.data().uid === res.user.uid) {
userExistance = true;
// console.log(userExistance)
return 0;
}
});
console.log(userExistance)
// todo: 2nd, add this user to users collection if it doesn't exists
if (userExistance === false) {
console.log(`userExistance is false, meaning this user hasn't been registerd so I am going add the user into users collection!!! ${res.user.displayName}, ${JSON.stringify(res.user)}`)
const addUser = async () => {
const payload = {
username: res.user.displayName,
uid: res.user.uid,
email: res.user.email,
photoURL: res.user.photoURL,
createdAt: new Date(),
bio: "biography",
};
await addDoc(userCollectionRef, payload);
}
addUser();
} else {
console.log('This user has been already registered!! So glad he/she keeps using this app!!')
}
}
checkUserExists();
}).catch((err) => {
console.log(err);
})
}
// export const AuthState = () => {
// const [userInfo, setUserInfo] = useState({})
// onAuthStateChanged(auth, (user) => {
// if (user) {
// const username = user.displayName;
// const uid = user.uid;
// const email = user.email;
// const photoURL = user.photoURL
// // const emailVerified = user.emailVerified
// setUserInfo({username, uid, email, photoURL});
// console.log(`username => ${username}`)
// console.log(`uid => ${uid}`)
// console.log(`email => ${email}`)
// console.log(`photoURL => ${photoURL}`)
// // console.log(`emailVerified => ${emailVerified}`)
// return userInfo;
// } else {
// console.log("no user signed in")
// }
// })
// }
// sendEmailVerification(auth.currentUser)
// .then(() => {
// console.log('email verification sent!')
// })
##.gitignore
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*
Background:
Yesterday, I initialized my pc to install Monterey in my macbook air and files in the pc were all gone. Then, I git-cloned the repo of this app.
You have everything correct from what I see except the file naming itself. I too struggled to try to get this to work until I made this simple change:
Try renaming your 'firebase.js' file to 'firebase.config.js', this will read your process.env variables as actual variables.
The variable values in .env should not be enclosed in the quotation marks. Remove the quotation marks.
I also had the same issue. I solved the issue by only replacing the projectID with the actual variable.
ex:-
const firebaseConfig = {
apiKey: process.env.REACT_APP_APIKEY,
authDomain: process.env.REACT_APP_AUTHDOMAIN,
projectId: "personal-portfolio-f1e9f",
storageBucket: process.env.REACT_APP_STORAGEBUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGINGSENDERID,
appId: process.env.APPID,
measurementId: process.env.MEASUREMENTID
};

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({ ... });

Firebase with react issue

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.

Angular Firebase not able to invoke Reset Password

My code is throwing error Uncaught TypeError: _baseUrl.resetPassword is not a function when I am trying to invoke this function.
Following is how I have configured firebase object
var firebaseConfig = {
apiKey: "my api key",
authDomain: "my-domain.firebaseapp.com",
databaseURL: "https://collection-name.firebaseio.com",
projectId: "my-project-id-1111",
storageBucket: "my-storage-bucket.appspot.com",
messagingSenderId: "XXXXXXXXXX",
appId: "1:XXXXXXXXX:web:XXXXXXXXXX"
};
// Initialize Firebase
var _firebase = firebase.initializeApp(firebaseConfig);
var _baseUrl = _firebase.database().ref("web/data");
var _baseAuth = _firebase.auth();
function resetPassword(userEmail) {
_baseUrl.resetPassword({
email: userEmail
}, function(error) {
console.log(error);
if (error === null) {
return false;
} else {
return error;
}
});
}
when I call the resetPassowrd function it throws an error.
Uncaught TypeError: _baseUrl.resetPassword is not a function
I have checked through debugging that I am receiving "_baseUrl" in my function but it does not have a method resetPassword
Please help and Thanks in advance
var firebaseConfig = {
apiKey: "my api key",
authDomain: "my-domain.firebaseapp.com",
databaseURL: "https://collection-name.firebaseio.com",
projectId: "my-project-id-1111",
storageBucket: "my-storage-bucket.appspot.com",
messagingSenderId: "XXXXXXXXXX",
appId: "1:XXXXXXXXX:web:XXXXXXXXXX"
};
// Initialize Firebase
var _firebase = firebase.initializeApp(firebaseConfig);
var _baseUrl = _firebase.database().ref("web/data");
var _baseAuth = _firebase.auth();`enter code here`
function resetPassword(userEmail) {
_baseAuth.sendPasswordResetEmail(
userEmail, actionCodeSettings=null)
.then(function() {
console.log('email sent');
})
.catch(function(error) {
console.log('error occurred');
});
}
I have used this function to reset the password and it is working fine.

Resources