Firebase gives 'appCheck is not a function' when using the client SDK in version 8 - firebase-app-check

I'm getting an error when I initialize the AppCheck in my project.
Firebase version: "^8.8.1".
import "firebase/functions";
const firebaseConfig = {
apiKey: "--",
authDomain: "--",
projectId: "--",
storageBucket: "--",
messagingSenderId: "--",
appId: "--"
};
const app = firebase.initializeApp(firebaseConfig)
const check = firebase.appCheck() // here is the error
check.activate('appCheckKey', true)
const functions = firebase.functions()
export {
app,
functions
}
console error:
Uncaught (in promise) TypeError: firebase.appCheck is not a function

Related

Firebase+ReactJS: 'importScripts' is not defined

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;

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

How do i write into my firebase inside useEffect hook?

this is my code:
useEffect(() => {
var firebaseConfig = {
apiKey: "AIzaSyCn1Sm8P-pgmsHe-n3iLD52LMk0ovTk2J0",
authDomain: "silkymarket-6036a.firebaseapp.com",
projectId: "silkymarket-6036a",
storageBucket: "silkymarket-6036a.appspot.com",
messagingSenderId: "463420618338",
appId: "1:463420618338:web:e817961bc3a14c4ca8c33b",
measurementId: "G-Q1K9YCB91M",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
initializer.database().ref("users/0401").set({
name: "dennos karuga",
age: 21,
});
}, []);
it seems firebase is not initializing properly as it needs some sort of async function, i can do the async function when i want to fetch from a given api url but i cant figure out how to do it when im using firebase. kindly help
You can follow the below approach:
1.You can write the initialization code in a particular file and then export it.
firebase.js
import * as firebase from 'firebase'
const firebaseConfig = {
apiKey: "AIzaSyCn1Sm8P-pgmsHe-n3iLD52LMk0ovTk2J0",
authDomain: "silkymarket-6036a.firebaseapp.com",
projectId: "silkymarket-6036a",
storageBucket: "silkymarket-6036a.appspot.com",
messagingSenderId: "463420618338",
appId: "1:463420618338:web:e817961bc3a14c4ca8c33b",
measurementId: "G-Q1K9YCB91M",
}; // Initialize Firebase firebase.initializeApp(firebaseConfig);
export default firebase;
2.Now you can use it whenever you want in the project as below,
import firebase from './firebase';
firebase.database().ref("users/0401").set({
name: "dennos karuga",
age: 21,
});

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