I am using Laravel 8.
I run:
npm install firebase
Than in my /resrouces/app.js I have:
import './bootstrap';
import { initializeApp } from "firebase/app";
import { getMessaging, getToken} from "firebase/messaging";
And I run npm run watch which compiles new version of app.js
Than I have this:
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="/js/firebase.js" type="module"></script>
Before closing </head>
And here is what I have in firebase.js:
const firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXX",
authDomain: "example.firebaseapp.com",
projectId: "beast-burst",
storageBucket: "app.example.com",
messagingSenderId: "XXXXX",
appId: "YYYY:ZZZZ:JJJJ:KKKK",
measurementId: "G-12345678"
};
// Initialize Firebase
const bbFirebase = initializeApp(firebaseConfig);
const messaging = getMessaging();
// Add the public key generated from the console here.
getToken(messaging, { vapidKey: 'YYYYYYYYYYYYYYYYYYY' }).then((currentToken) => {
if (currentToken) {
console.log("TOKEN: " + currentToken);
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
This gives me the following error:
initializeApp is not defined
at firebase.js:13:20
If I add these lines into firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js";
import { getMessaging, getToken} from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js";
It works, however I don't want this. I want to use it like this as they describe in the guides:
import { initializeApp } from "firebase/app";
import { getMessaging, getToken} from "firebase/messaging";
However if I add these lines to firebase.js I get this error:
TypeError: Failed to resolve module specifier "firebase/app". Relative references must start with either "/", "./", or "../".
Any idea what is going wrong and how can I fix it?
Related
I am getting the following error in my React app when trying to initialize Firebase:
Uncaught FirebaseError: Firebase: Error (auth/invalid-api-key).
at createErrorInternal (assert.ts:142:1)
at _assert (assert.ts:167:1)
at new Auth (auth.ts:56:1)
at
instance.INTERNAL.registerComponent._firebase_component__WEBPACK_IMPORTED_MODULE_2__.Component.setServiceProps.ActionCodeInfo.Operation.EMAIL_SIGNIN [as instanceFactory] (index.ts:82:1)
at Provider.getOrInitializeService (provider.ts:318:1)
at Provider.getImmediate (provider.ts:115:1)
at FirebaseAppImpl._getService (firebaseApp.ts:138:1)
at firebaseAppImpl.<computed> [as auth] (firebaseNamespaceCore.ts:185:1)
at Object.serviceNamespace [as auth] (firebaseNamespaceCore.ts:166:1)
at new Firebase (firebase.js:17:1)
I am using the following versions of React and Firebase:
React: 18.2.0
Firebase: 9.16.0
I have checked that the API key in my .env file is correct, but the error persists.
Here is the source code of my firebase.js file:
import app from "firebase/compat/app";
import "firebase/compat/auth";
const config = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_ID,
};
class Firebase {
constructor() {
app.initializeApp(config);
this.auth = app.auth();
}
// *** Auth API ***
doCreateUserWithEmailAndPassword = (email, password) =>
this.auth.createUserWithEmailAndPassword(email, password);
doSignInWithEmailAndPassword = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password);
doSignOut = () => this.auth.signOut();
doPasswordReset = (email) => this.auth.sendPasswordResetEmail(email);
doPasswordUpdate = (password) =>
this.auth.currentUser.updatePassword(password);
}
export default Firebase;
.env file:
REACT_APP_API_KEY=AIzsdfceg7Cu22Ma8RYadHVnrSoRwQ-B7ZEejs
REACT_APP_AUTH_DOMAIN=devsproject-75523.firebaseapp.com
REACT_APP_DATABASE_URL = https://devsproject-75523-default-rtdb.firebaseio.com/
REACT_APP_PROJECT_ID=devsproject-75523
REACT_APP_STORAGE_BUCKET=devsproject-75523.appspot.com
REACT_APP_MESSAGING_SENDER_ID=1009026371636
REACT_APP_ID=1:1009026371636:web:a57fr518532bc351d0f6f9
Any help would be appreciated.
Update:
I tried to do this on the config object:
const config {
apiKey: process.env.REACT_APP_API_KEY || "mock_key",
.....
}
now i am able to see the page instead of that empty view port, i don't know whether its a bandaid solution or does it actually solved anything:
Am i moving right, please i need your feedback
I'm very new to next.js, and I'm developing an API with it, side that API I want to use firebase, so I set up firebase but when I try to call it, this error appears: "unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization"
Code below.
Firebase config file
import firebase from 'firebase/app';
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "*******",
authDomain: "********",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
//if(!firebase.apps.length){
//}
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
Firestore service
import { firestore } from './firebase';
export class Firestore {
async getOne(collection, uid){
const data = await firestore.collection(`${collection}/${uid}`).get();
return await data.docs();
}
}
API page
import {Firestore} from '../../utils/firestore';
const firestore = new Firestore();
const getBanners = () => {
return firestore.getOne('settings','client');
//return data;
}
export default function Handler(req,res){
res.status(200).json({
'name':"getBanners",
'data': getBanners()
});
}
I solved this issue by adding import firebase from 'firebase/compat/app'; and also import 'firebase/compat/firestore';. And works!
I am trying to use firebase for my chat application developed using React Native and I am getting following error while pushing records into firebase.
[TypeError: _firebaseConfig.default.database is not a function. (In '_firebaseConfig.default.database()', '_firebaseConfig.default.database' is undefined)]
I have created a firebase configuration file as below.
firebase-config.js
import Firebase from 'firebase/compat/app';
const firebaseConfig = {
apiKey: '',
databaseURL: '',
projectId: '',
appId: '',
};
export default Firebase.initializeApp(firebaseConfig);
Messages.js
import Firebase from './firebase-config';
export const sendMessage = async (from, to, message) => {
try {
return await Firebase.database()
.ref('messages/' + from)
.child(to)
.set({
from: from,
to: to,
message: message,
});
} catch (error) {
console.log(error);
}
};
export const receiveMessage = async (from, to, message) => {
try {
return await getDatabase(Firebase)
.ref('messages/' + to)
.child(from)
.push({
from: from,
to: to,
message: message,
});
} catch (error) {
console.log(error);
}
};
You're not importing the Realtime Database SDK anywhere, so when you try to then access firebase.database() you get an error saying that it can't be found.
To fix this, import the Realtime Database SDK after you import Firebase from 'firebase/compat/app'.
import firebase from 'firebase/compat/app';
import 'firebase/database';
...
I recommend also checking out the example in the upgrade guide on updating imports to v9 compat.
I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
src/App.vue
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
public/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
src/plugins/firebase.js
import firebase from '#firebase/app'
import '#firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
What did I do wrong?
I've found a solution in another QA here in StackOverflow (which I can't find anymore for some reason).
Turns out you have to use Firebase API v7.8.0 instead of 5.5.6 like the docs said at the time. So those first two lines in public/firebase-messaging-sw.js should read like this instead:
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js')
Same issue i was faced. In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different. After set same version in "firebase-messaging-sw.js" importScripts which was in
"package.json", my issue is resolved.
Before change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
After change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
In my case the version on package.json (8.2.1) was different from the actual SDK_VERSION (8.0.1)
After changed service-workers with the same version worked..
I had a bunch of issues setting firebase push notifications for Vue 3 (with Vite), and I had PWA support enabled with vite-plugin-pwa, so it felt like I was flying blind half the time. I was finally able to set up support for PWA, but then I ran into the following issues:
I was getting notifications in the background (when my app was not in focus), but not in the foreground.
When I did get notifications in the background, it appeared twice.
Here's my complete setup. I have the latest firebase as of this post (9.12.1)
// firebase-messaging-sw.js file in the public folder
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-app-compat.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-messaging-compat.js"
);
// Initialize Firebase
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "/icon.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I've seen some posts online provide the onBackgroundMessage here in the service worker, but I experimented with commenting it out and it seemed to fix the issue of notifications appearing twice.
Next, is a firebase.js file with which I retrieve tokens and subsequently listen for foreground notifications.
// firebase.js in same location with main.js
import firebase from "firebase/compat/app";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = firebase.initializeApp(firebaseConfig);
export default getMessaging(app);
And then in main.js
import App from "./App.vue";
import firebaseMessaging from "./firebase";
const app = createApp(App)
app.config.globalProperties.$messaging = firebaseMessaging; //register as a global property
And finally, in App.vue (or wherever you wish to get tokens and send to your serverside)...
import {getToken, onMessage} from "firebase/messaging";
export default {
mounted() {
getToken(this.$messaging, {
vapidKey:
"XXX-XXX",
})
.then((currentToken) => {
if (currentToken) {
console.log("client token", currentToken);
onMessage(this.$messaging, (payload) => {
console.log("Message received. ", payload);
});
//send token to server-side
} else {
console.log(
"No registration token available. Request permission to generate one"
);
}
})
.catch((err) => {
console.log("An error occurred while retrieving token.", err);
});
}
}
Of course don't forget the vapidKey. Took a minute, but it worked perfectly.
For now, I am not offering any opinion as to what the foreground notification should look like, so I am merely logging the payload. But feel free to show it however you deem fit.
I'm trying to add authentication using Firebase in my Vue app, but I'm getting [Vue warn]: Error in v-on handler: "TypeError: _config_firebase__WEBPACK_IMPORTED_MODULE_8__.user.SignInWithEmailAndPassword is not a function" error.
Here is my irebase config file:
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_AUTH_DOMAIN",
databaseURL: "MY_DB_URL",
projectId: "MY_PROJECT_ID",
storageBucket: "MY_STORAGE_BUCKET",
messagingSenderId: "MY_MESSAGE_SENDER_ID",
appId: "MY_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a Firestore instance
export const user = firebase.auth();
export const db = firebase.firestore();
Then the action in Vuex:
import { db, user } from "./config/firebase";
loginUser({ commit }, payload) {
user
.SignInWithEmailAndPassword(payload)
.then(user => {
console.log(user);
commit("SET_USER", user);
})
.catch(error => {
commit("setLoading", false);
commit("setError", error);
console.log(error);
});
router.push("/");
}
So far, I have been able to Create, Read, Update and Delete, although, the config file was slightly different than this, when I added auth was when I altered the code.
Change this:
user.SignInWithEmailAndPassword(payload)
into this:
user.signInWithEmailAndPassword(payload)
From the docs:
Asynchronously signs in using an email and password.