Firebase Cloud Messaging in Nuxt (Push Notifications)

We are going to implement push notifications into our Nuxt application using Firebase. I’m going to assume that you know some basics of Vue and Nuxt. The push notifications will appear in the notifications drawer in the user’s operating system (outside of the browser). Therefore, we are going create a key that tells Firebase what type of operating system the user is using.

We are going to use a service worker to handle incoming messages from firebase. Nuxt has some nice documentation to set up Firebase. This guide will help you with any further questions.
https://firebase.nuxtjs.org/guide/getting-started

  1. Add dependencies
npm install firebase
npm install @nuxtjs/firebase

2. Go to https://console.firebase.google.com/

3. Add a project (give it a project name)

4. On the “overview” page, click on the </> icon to register the app

5. When you click “register”, you will see some code appear that looks something like this:

<script>
var firebaseConfig = {
apiKey: yourKey",
authDomain: "yourAuthDomain",
projectId: "yourProjectId",
storageBucket: "yourStorageBucket",
messagingSenderId: "yourMessagingSenderId",
appId: "yourAppId",
measurementId: "yourMeasurementId"

};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>

6. Copy and Paste all of the code below into the “module” property of the nuxt.config.js file. The bolded code comes from the code in the bolded code in step 5. Make sure to require fs.

const fs = require('fs')// modules
[
'@nuxtjs/firebase',
{
config: {
apiKey: "<yourKey>",
authDomain: "<yourAuthDomain>",
projectId: "<yourProjectId>",
storageBucket: "<yourStorageBucket>",
messagingSenderId: "<yourMessagingSenderId>",
appId: "<yourAppId>",
measurementId: ",<yourMeasurementId>"
},
services: {
messaging: {
createServiceWorker: true,
fcmPublicVapidKey: '<yourFCMPublicVapidKey>', //see step 7
inject: fs.readFileSync('./serviceWorker.js') //see step 8
},
}
}

7. To find your “fcmPublicVapidKey,” go to the “Project Settings.” Then, click on “Cloud Messaging.” Click on the “Generate key pair” button. Replace the ‘yourFCMPublicVapidKey’ in the nuxt.config.js file with the newly-generated key.

8. We need to setup a service worker to handle the push notifications. Create a file called serviceWorker.js in the root directory. Paste the following code in this file.

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'
},
};

9. Now, we need to listen for incoming messages from Firebase so we can create push notifications. Therefore, we want to initialize Firebase in the async mounted() lifecycle hook in your index.vue file. To initialize Firebase, we need to create a token so that Firebase can send the push notification to the appropriate device (ie desktop, mobile, tablet).

You will need to replace <yourServerKey> with your key. To find your server key, go to the Firebase console => Project Settings => Cloud Messaging.

Now, rebuild your nuxt app. (ie. npm run dev). You should see a message appear in your notifications drawer.

Make sure you install/import axios.

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)
})

10. We need to make a POST request to https://fcm.googleapis.com/fcm/send to test the push notification. I’d recommend using postman. I’ve posted a screenshot of how to set up the header and body. In the authorization field of the header, you’ll need to provide the server key from step 9 (you can console.log() to see the value). Pay close attention to the syntax of the server key value you input into postman. It should be “key=yourServerKey”. When you submit the postman request, you should see a notification in your windows drawer.

async mounted() {
const currentToken = await this.$fire.messaging.getToken()
console.log(currentToken)
}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store