Step 1) Install dependencies
npm install firebasenpm 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.