Reputation: 758
I'm trying to implement Google's Firebase Cloud Messaging (FCM) into my Nuxt.js APP.
So far I've installed firebase, created a firebase.js plugin inside ./plugins folder, imported and initialized firebase and the messaging service, everything seems to be working fine.
Now I'm not sure how or where to go from here..
The idea is to handle everything inside vuex, in notifications module.
I want to handle both background and foreground notifications. Background gets handled by service-worker, for the foreground I've made a simple notification component that I want to show everytime I receive a push notification from FCM.
The question:
How would I go about registering a service worker, requesting permission and handling the foreground/background notifications? I mean the exact location/file/way specific to Nuxt.js? Should I make another plugin just for that, use middleware folder or just handle everything in my default layout file?
Whats the cleanest way to go about it?
Thanks in advance!
Upvotes: 20
Views: 3909
Reputation: 7338
Step 1) Install dependencies
npm install firebase
npm install @nuxtjs/firebase
Step 2) Create a file serviceWorker.js
on your project's root folder.
self.addEventListener('push', function (e) {
data = e.data.json();
var options = {
body: data.notification.body,
icon: data.notification.icon,
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
};
Step 3) Config your nuxt.config.js
as follows.
Add this line to the top of your file.
const fs = require('fs')
Update your modules array with firebase credentials.
[
'@nuxtjs/firebase',
{
config: {
apiKey: "<yourKey>",
authDomain: "<yourAuthDomain>",
projectId: "<yourProjectId>",
storageBucket: "<yourStorageBucket>",
messagingSenderId: "<yourMessagingSenderId>",
appId: "<yourAppId>",
measurementId: ",<yourMeasurementId>"
},
onFirebaseHosting: false,
services: {
messaging: {
createServiceWorker: true,
fcmPublicVapidKey: '<yourFCMPublicVapidKey>',
inject: fs.readFileSync('./serviceWorker.js')
}
}
}
]
Step 4 > Finally.. to your index.js or layout file.
async mounted() {
const currentToken = await this.$fire.messaging.getToken()
const data = JSON.stringify({
notification: {
title: 'firebase',
body: 'firebase is awesome',
click_action: 'http://localhost:3000/',
icon: 'http://localhost:3000/assets/images/brand-logo.png'
},
to: currentToken
})
const config = {
method: 'post',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': 'key=<yourServerKey>'
},
data
};
const response = await axios(config)
this.$fire.messaging.onMessage((payload) => {
console.info('Message received: ', payload)
})
this.$fire.messaging.onTokenRefresh(async () => {
const refreshToken = await this.$fire.messaging.getToken()
console.log('Token Refreshed',refreshToken)
})
}
For more details, to understand the steps, you can visit this article.
Upvotes: 1
Reputation: 53
Once you have installed @nuxtjs/firebase
module and insert following code into your nuxt.config.js
where you can get those data from firebase console. I placed them as a dotenv
module because it is easier to manage configuration templates for different projects.
firebase: {
config: {
apiKey: dotenv.parsed.apiKey,
authDomain: dotenv.parsed.authDomain,
databaseURL: dotenv.parsed.databaseURL,
projectId: dotenv.parsed.projectId,
storageBucket: dotenv.parsed.storageBucket,
messagingSenderId: dotenv.parsed.messagingSenderId,
appId: dotenv.parsed.appId,
measurementId: dotenv.parsed.measurementId
},
onFirebaseHosting: false,
services: {
messaging: {
createServiceWorker: true,
fcmPublicVapidKey: dotenv.parsed.vapidKey // OPTIONAL : Sets vapid key for FCM after initialization
}
Once you have implemented it, the module will generate service workers by itself and you can view them on your inspect element console.
All done and said,
In your vuex store, just call this.$fire.messaging.getToken()
to ask users for permission to receive notification.
You can initiate your receiving message with this function below where you call this.$fire.messaging.getToken()
messaging.onMessage(function (payload) {
context.dispatch('yourDesireDispatchFunction', payload)
})
Upvotes: 0
Reputation: 156
you can check the Nuxt Module Nuxt Firebase https://firebase.nuxtjs.org
the documentation is very good https://firebase.nuxtjs.org/service-options/messaging
Upvotes: 0