Modern PWA with Vue-CLI 3 + Vuetify + Firestore + Workbox[Part 5]

Eder Ramírez Hernández
10 min readApr 15, 2019

--

Hello again. It’s been a long time since I wrote the last chapter, sorry about that, I have been very busy these days. But I’m here again, ready to continue creating this awesome PWA with Vue.

Until now, we have a PWA able to list, create, and save posts to a database, and take pictures with the device camera. If you haven’t seen the previous chapters you can check them out in the following links.

[Part 1] Create a SPA project using Vue-CLI 3 and Vuetify plugin

[Part 2] Connect the App with an external API and Firestore to save data

[Part 3] Implement offline mode

[Part 4] Access device camera to take pictures

[Part 5] Implement Firebase push notifications (you are here)

[Part 5] Implement Firebase push notifications

Now it’s time to go further sending push notifications to all the app users every time a new post is created.

Before we start I want to tell you that currently there is no way to send web push notifications to iOS devices. If you need to send push notifications on iPhone or iPad you need to create a native app.

This is going to be a huge chapter so I decided to create the next list of sections to give you an overall idea of everything we need in order to develop a push notification system in our app.

  • Firebase CLI Installation.
  • Create a general subscription firebase function.
  • Web push notifications subscription.
  • Configure notifications in background.
  • Send notifications when new post is created.
  • Conclusion

Firebase CLI Installation

We need firebase CLI because we are going to implement firebase functions.

Firebase functions will be our backend written in node.js which we’ll be uploading to Google servers via Firebase CLI.

To install Firebase CLI, open a new terminal and run the next command.

npm install -g firebase-tools

I’m going to install it too to accompany you in the process.

As this is a global package, I needed to write sudo in the beginning (this only applies in mac or linux)

Firebase CLI installation process

At the end of the process firebase-CLI will give some advice on how to install firebase functions emulator. We don’t need it, so we can ignore the advice and move on.

We can confirm a successful installation with the next line of code.

firebase tools --version

Before continuing, you’ll need to authenticate with google. Run the next command and log in.

firebase login

Then we need to navigate to our root project folder and run the next command to initialize firebase into it.

firebase init

After running the command, Firebase CLI will ask which features you want to install. Just select Functions and Hosting and hit Enter.

Then select our cropchien project (your project).

Now select the Javascript language.

Then, it asks us about use ESLint, normally it’s a good practice turn it on in every javascript project. But as this is a learning project we are going to select No.

Now, select yes to install dependencies with npm.

I recommend not to use YARN in our firebase functions backend, I had issues in the past using it with Firebase functions.

Select yes to use public as public folder in our project.

Then Firebase CLI will asks about de SPA configuration, please select Yes.

Firebase CLI will asks about to override the public/index.html, select no of course.

Finally you’ll get a successful message. If you check the repository you should be able to see these new folders and files.

If you open the functions folder, you’ll see these files:

Firebase functions files structure.

As you can see, there is another node_modules folder and other package json file. This means that this functions folder is treated as another separated project. The index.js is the file where we’ll implement our backend.

The index.js file is where we are going to create firebase functions using node.js.

Create a general subscription firebase function.

If you open the package json file in the firebase functions folder, you’ll see these dependencies.

Firebase-cli has installed firebase-admin and firebase-function for us, but we’ll need cors and axios too.

Open the integrated terminal, navigate to functions folder, writing cd functions and hit enter.

Be sure to be in functions folder when you’re working with firebase functions

Install the following dependencies:

npm install cors axios

Remember to use npm instead of yarn inside the functions folder.

Once installed you’d be able to see the new dependencies in the package.json file.

In VSCode Open the index.js file to write our very first function it’ll be called General subscription. Erase the default content and paste the following code.

Let's analyze the code, first we import everything we need to create our functions including axios and cors libraries. Then we initialize our app and we create a firestore instance. The final step is create our GeneralSubscription function. We use axios to create the general theme and when the promise is resolved, we are saving the token in the tokens firestore collection. We’ll use these tokens later to send the notifications.

As you can see you need an Authorization header token to create the general theme. Let’s go to firebase console in chrome to get it.

In firebase console click in the cog icon and select project setup.

Then click in Cloud messaging tab and copy the server key.

Create a serverKey.js file inside the functions folder and paste your server Key there.

In the terminal run the next line to upload our function (make sure you are inside functions folder).

firebase deploy --only functions

Return to firebase console and go to the functions section to check that the GeneralSubscription function was created.

Congratulations, now you have your very first firebase function. Now it’s time to work in the front-end again in order to subscribe users to push notifications.

Copy your function URL, you’ll need it in the next submodule.

Web push notifications subscription.

Nowadays most webs ask for push notifications permissions from the very beginning, this is a bad idea because the chances of receive a positive answer decreases.

We need a push notification subscription button, but first we have to make little changes in our configFirebase.js. Just add this lines at the bottom.

Our file should look like this:

Okay, we are ready to request the user for push notifications permissions. Modify App.vue with the next code:

We added a notification subscription button, when it’s clicked we ask firebase for a messaging token and then save it using the firebase function that we’ve previously created. Besides when the component App.vue is mounted we listen for Token refresh just in case we already had a token.

Firebase web push notification requires that our service worker to be called firebase-messaging-sw.js, so create a firebase-messaging-sw.js empty file in src folder for now.

Create a new vue.config.js file in the project’s root folder to merge this custom service worker (empty firebase-messaging-sw.js) with the generated by vue-cli. And paste this code on it:

Besides, we need to make a little change in registerServiceWorker.js file.

So change this line:

register(`${process.env.BASE_URL}service-worker.js`, {

to this:

register(`${process.env.BASE_URL}firebase-messaging-sw.js`, {

In other words we just changed the service worker name.

Remember that, to test these PWA features we should compile files in production mode and serve it via HTTP SERVER. So, lets compile to production.

In terminal, Navigate to project’s root folder (no functions folder) an run this:

yarn run build

npm run build if you aren’t using yarn

and then serve the dist folder with this command:

http-server dist

Let’s try the push notification button. Open the app and click the bell icon button.

Click the allow option and watch the console print.

We can check the database in firebase console and check if the token was saved.

If you’re having issues at this step, you can watch the process step by step in functions / logs. You can even print console.log in your firebase function and see them here.

Ok, We already are subscribed to push notifications now move to the next step

Configure notifications in background

To handle notifications in the background we have to update our new service worker firebase-messaging-sw.js, we have to do it here because the service worker will listen even when the web app is closed or in background.

Add this code to firebase-messaging-sw.js.

Be sure to replace the URL with your firebase project name.

new RegExp(‘https://firebasestorage.googleapis.com/v0/b/cropchien.appspot.com/.*'),

Replace your firebase sender ID too.

Compile to production again to install this service-worker changes.

We are going to use Postman to test all the code we’ve written until now. So install postman if you don’t have it already and then create a new POST request.

set the URL to :

https://fcm.googleapis.com/fcm/send

set the next headers and include your own authorization key:

In body tab select raw option and JSON in the select, then paste this json and change the URL to your URL app.

Test the post route pressing send button, you should be able to see our notification in action.

Chrome — Mac OS Cropchien Notification

Send notifications when new post is created

Can you guess what we need to trigger our new post notification?. Yes you got it, we need to make a new firebase function.

Add this new firebase function at the end of the index file inside of functions folder.

Upload the function (make sure to be inside functions folder).

firebase deploy --only functions

Let’s test it, open a new tab in incognito mode an create a new post.

Conclusion

Congratulations, now our PWA sends notifications to all users when a new post is created. As you can see, the push notifications is a huge and very complex topic. You’ve learned a basic setup but you can go further and send notifications to a certain group of people, or send direct push notifications to specific users.

I invite you to learn more and make improves to your own version of this app, you can even try to upload this app to production and test it in your own phone. If you do it, please share your URL in the comments, I’ll be happy to see your work.

Remember you can check the complete code in the chropchien github repository:

Thank you for following this series of articles, I invite you to follow me on twitter.

Happy Coding.

--

--