FCM setup for push notification in angular 6 web app - firebase

I am trying to integrate fcm in my angular 6.
Here is what i have done.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '93480234033'
});
const messaging = firebase.messaging();
push-notification.js
import firebase from 'firebase';
export const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
console.log('000ooppp', messaging)
messaging.requestPermission()
.then(function(){
console.log('I am in here');
return messaging.getToken()
.then(function(currentToken) {
console.log(currentToken);
})
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
} catch (error) {
console.error(error);
}
}
these two files are in src folder.
i have created an app on firebase console and i have got the config object
config: {
apiKey: "*****",
authDomain: "*****",
databaseURL: "*****",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "*****"
}
And in my app.module.ts file i am initialising firebase with the above object
import { AngularFireModule } from 'angularfire2';
import { ServiceWorkerModule } from '#angular/service-worker';
and then in import
imports: [
...
...
AngularFireModule.initializeApp(environment.firebase),
ServiceWorkerModule.register('/combined-worker.js', { enabled: environment.production })
...
...
]
and in app.component.ts
import { askForPermissioToReceiveNotifications } from './../push-notification';
ngOnInit () {
console.log('pop')
askForPermissioToReceiveNotifications();
}
what i want to do is when user lands on the page and he allows notification to be shown to him, a unique device token id should be generated for that particular user, how can i generate device token id when he clicks on show notification?
getting this error in console
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)

src/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
now in app.module.ts
import {BrowserModule} from '#angular/platform-browser';
import {NgModule} from '#angular/core';
import {AppComponent} from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireMessagingModule } from 'angularfire2/messaging';
const config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
};
#NgModule({
declarations: [
AppComponent
],
imports: [
AngularFireModule.initializeApp(config),
AngularFireMessagingModule
],
bootstrap: [AppComponent]
})
export class AppModule {
}
inside your component that yout want to require permission to send notification:
import {Component, OnInit} from '#angular/core';
import { AngularFireMessaging } from 'angularfire2/messaging';
import { mergeMapTo } from 'rxjs/operators';
export class HomeComponent implements OnInit {
constructor(private _messaging: AngularFireMessaging) {
}
ngOnInit() {
/* request permission */
this._messaging.requestPermission
.pipe(mergeMapTo(this._messaging.tokenChanges))
.subscribe(token => {
console.log(token);
}, err => console.log(err));
/* listen for messages */
this._messaging.messages.subscribe((message: {notification}) => {
console.log(message.notification.title);
console.log(message.notification.body);
});
}
}
Remember that there 2 ways receiving push notifications
1) when the app is open:
you'll have to handle it showing the message
2) when the app is closed:
the browser handle it for you

Hello #wazz try setting your firebase config in your app.module.ts and import firebase
import * as firebase from 'firebase';
...
firebase.initializeApp(firebase_config);

Related

FirebaseError: "projectId" not provided in firebase.initializeApp (NextJS)

I'm building a web app with NextJS, NextAuth and Firebase/Firestore, and I'm getting an error:
error - [FirebaseError: "projectId" not provided in firebase.initializeApp.] {
code: 'invalid-argument',
customData: undefined,
toString: [Function (anonymous)]
This is my JS file:
import NextAuth from "next-auth/next";
import TwitterProvider from "next-auth/providers/twitter";
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { initializeApp, getApp, getApps } from "firebase/app";
import "firebase/auth";
import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
// import { getAnalytics } from "firebase/analytics";
// import { getStorage } from "firebase/storage";
import nextConfig from "next.config";
const firebaseConfig = {
apiKey: nextConfig.env.FIREBASE_API_KEY,
authDomain: nextConfig.env.FIREBASE_AUTH_DOMAIN,
projectId: nextConfig.env.FIREBASE_PROJECT_ID,
storageBucket: nextConfig.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: nextConfig.env.FIREBASE_MESSAGING_SENDER_ID,
appId: nextConfig.env.FIREBASE_APP_ID,
measurementId: nextConfig.env.FIREBASE_MEASUREMENT_ID,
};
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
//const analytics = getAnalytics(app);
const db = getFirestore(app);
//const storage = getStorage(app);
const dbInstance = collection(db, "bugs");
const getBugs = () => {
getDocs(dbInstance).then((data) => {
console.log(data);
});
};
export default NextAuth({
providers: [
TwitterProvider({
clientId: nextConfig.env.TWITTER_CLIENT_ID,
clientSecret: nextConfig.env.TWITTER_CLIENT_SECRET,
version: "2.0", // opt-in to Twitter OAuth 2.0
}),
],
adapter: FirestoreAdapter(db),
});
I can't find any solution on the internet.
Any idea?
In Nextjs, environment variables are only available in the Node.js environment by default, meaning they won't be exposed to the browser.
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_
Change your firebase config as shown below and also change the firebase env variables in the .env file to use NEXT_PUBLIC_ prefix.
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,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

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.

How do I configure SvelteKit to use Firebase Auth?

I have it working with Firebase 8, but I can't seem to get Firebase 9 working...
Here is my firebaseConfig.js file:
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: 'AIzaSyCAAngD7340_noXs7eesCfE9Y3cwqmiZhU',
authDomain: 'svelte-todo-20f21.firebaseapp.com',
projectId: 'svelte-todo-20f21',
storageBucket: 'svelte-todo-20f21.appspot.com',
messagingSenderId: '402466412167',
appId: '1:402466412167:web:c739e7eb86fc5b6ac5ca22',
measurementId: 'G-2N348J0NTE'
};
const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export const firestore = getFirestore(firebaseApp);
export default firebaseApp;
My auth.js file:
import { auth } from './firebaseConfig';
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
// Sign in with popup && Google as the provider
const googleProvider = new GoogleAuthProvider();
export const googleSignIn = async () => {
await signInWithPopup(auth, googleProvider)
.then((user) => {
console.log(user);
})
.catch((error) => {
console.error(error);
});
};
And the index.svelte:
<script>
import { googleSignIn } from '../auth';
</script>
<button on:click={() => googleSignIn()}>Sign In</button>
Seems easy enough but I'm getting this error that I can't resolve...
"500
The requested module '/node_modules/.vite/firebase_firestore.js?v=42dbe183' does not provide an export named 'getFirestore'
SyntaxError: The requested module '/node_modules/.vite/firebase_firestore.js?v=42dbe183' does not provide an export named 'getFirestore'"
If it helps, someone suggested that I update my svelte.config.js file to the following...
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
vite: {
ssr: {
external: ['firebase']
}
}
}
};
export default config;

An error occurred while creating an application on firebase#9.0.0-beta.2 + NUXT

I create an application with firebase#9.0.0-beta.2
I get the error
Created a folder plugins add file firebase.js
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: ''
}
let firebaseApp
try {
firebaseApp = getApp()
} catch (e) {
firebaseApp = initializeApp(firebaseConfig)
}
const db = getFirestore(firebaseApp, {})
export { db }
nuxt.config.js
...
plugins: [
'~/plugins/firebase.js'
],
...
I get the error:
error 'getApp' is not defined no-undef
getApp() is not a built-in method and must be called from the appropriate library, in this case: FirebaseApp.getApp()
import { initializeApp, getApps, getApp } from "firebase/app";
getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();
OR
if (FirebaseApp.getApps(context).isEmpty()) {
FirebaseApp.initializeApp(context);
}

How to configure firebase as nuxt plugin?

I am trying to configure firebase in nuxt as a plugin. I have to make the nuxtInitServer call in store because the env variables are from sharedEnv.
When the login method is invoked on the login page, I get the error:
Uncaught TypeError: _plugins_firebase__WEBPACK_IMPORTED_MODULE_3__.default.auth is not a function
store/index.js
const getSharedEnv = () =>
process.server
? {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DB_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGE_SENDER_ID
}
: {}
...
export const actions = {
nuxtServerInit({ commit, state, store, dispatch }, { req }) {
if (process.server) {
commit('setSharedEnv', getSharedEnv())
}
}
}
plugins/firebase.js
import Vue from 'vue'
import firebase from 'firebase/app'
Vue.use(firebase)
export default context => {
// perform a store action manually to have access to `sharedEnv` object
context.store.dispatch('nuxtServerInit', context)
const env = { ...context.store.state.sharedEnv }
if (!firebase.apps.length) {
console.log('initialize firebase...')
firebase.initializeApp(env)
}
return firebase
}
pages/login/index.vue
<script>
import firebase from '#/plugins/firebase'
export default {
name: 'login',
data() {
return {
email: '',
password: ''
}
},
methods: {
login: function() {
let additionalClaims = {
premiumAccount: true
}
console.log('login page')
console.log(firebase)
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(
response => {
...
You need to also import the firebase/auth library if you need the auth feature
i.e.
import firebase from 'firebase/app';
import 'firebase/auth';

Resources