Firebase Web Push Notification

Firebase web push notification with javascript.

Ayush Chaurasia
The Startup
5 min readDec 21, 2020

--

This blog explains how to register with firebase and create a firebase service worker to receive the message even when web-app is not open in the browser,
using javascript.

Let’s start with the registration part

If you have already registered your app with firebase you can skip this part section and go to the next section Getting FCM credentials and VAPId key.

  1. After Login into firebase go-to console by clicking on the “go-to console button”
  2. Click on the add project.
  3. Now enter the project name and continue
  4. Here the analytics is checked by default, if you want to use Google analytics for your project leave it that way otherwise click on the toggle and continue.
  5. On the next step, it might ask you to create a google analytics account for your project depending on your previous selections.
  6. Now you will be on your project overview screen, here you can see circular buttons like below image. Click on the web button.

7. Complete the steps as you are asked on the “Add Firebase to your web app” page.

Voila! you have registered your app successfully on firebase.

Getting FCM credentials and VAPId key

If you are already aware of this move to the next section.

  1. Go to console and click on your project.
  2. On the project, page click the app icon and a small popup will appear, click on the Settings icon.
  3. You will be on a page which looks exactly like this.
App setting page.

4. Scroll down to find the firebase SDK snippet which looks something like below, keep this code handy we will be using it to initialize firebase.

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "myApiKey",
authDomain: "browser-notif-test.firebaseapp.com",
projectId: "browser-notif-test",
storageBucket: "browser-notif-test.appspot.com",
messagingSenderId: "myMessaginSenderId",
appId: "myAppId",
measurementId: "myMeasurementId"// this is for analytics purpose
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>

5. Move to the cloud messaging tab of your setting, here you will find the server key. Scroll down and click on the generate button to get your vapid key.

Coding the client for FCM web push notification.

Tech stack
J
avascript, firebase-tools.

Let’s setup

Setting up firebase-tool

Install firebase-tools. (If you want to do this using express server click here and skip this section)

npm install -g firebase-tools

Create a directory and add these files.
firebase.json

{
"hosting": {
"public": "./",
"ignore": [
"firebase.json"
]
}
}

manifest.json

{"//_comment1": "Some browsers will use this to enable push notifications.",
"//_comment2": "It is the same for all projects, this is not your project's sender ID",
"gcm_sender_id": "202066980505"}

Let’s set up firebase tools

Go inside your firebase directory(the directory which has the firebase.json file)

run the following commands

$firebase login // it will take you to your default browser singin        there with your credentials.$firebase use --add 
// We will use the below commnad to start firebase server on our local machine.
$firebase serve -p 8081

Setting up the express server

This is an alternative to setting up firebase tool and generally, this is the way you might be serving up your client page.

create app.js

const express = require('express');const app = express();app.use(require('body-parser').json());
app.use(require('express-static')('./'));
app.listen(3000);

That’s it you are done with server setup now you can follow the below step as it is.

Let’s write the code.

Client HTML and js page.

index.html

copy the firebase SDK code in the bottom of the body of the index.html

<!DOCTYPE html><html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FCM cloud messaging</title>
</head>
<body>
<!-- your regular html code -->

<!-- insert here the firebase sdk code-->
<script>
// All the other code realted to firebase will be below this
</script></body>

The Firebase SDK code is used for the initialization of the firebase all the other code should go below that.

Now let’s write a code to receive the message in the foreground.

index.html
//Put this inside the script
messaging.onMessage((payload) => {
console.log('Message received. ', payload);});

Here the payload will contain the received notification information.

Sending a message to the firebase browser client

For firebase to be able to send message to the client it needs to uniquely identify it, which it does via token, tokens are generated on the client-side and can be stored on our server-side. Let’s see how to get the client token.

index.html
//Put this inside the script
//Below above snippet code.
messaging.getToken({vapidKey: 'MY_VAPID_KEY'}).then((currentToken) => {if (currentToken) {console.log("token is ",currentToken);
//Send this token to your server and store it.
} else {
console.log('No registration token available. Request permission to generate one.');
}}).catch((err) => {console.log('An error occurred while retrieving token. ', err);});

In the above snippet use your vapid key.

You can start firebase server and check the printed token in your browser’s console.

Now let’s do the setup to receive notification even our app is not in foreground or browser itself is closed(Background notification).

create a new file firebase-messaging-sw.js and add the following content.

importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');//Remeber this part we have used above in our index.html
var firebaseConfig = {
apiKey: "myApiKey",
authDomain: "browser-notif-test.firebaseapp.com",
projectId: "browser-notif-test",
storageBucket: "browser-notif-test.appspot.com",
messagingSenderId: "myMessaginSenderId",
appId: "myAppId",
measurementId: "myMeasurementId"// this is for analytics purpose
};
const messaging = firebase.messaging();messaging.onBackgroundMessage(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here
const notificationTitle = 'Title';
const notificationOptions = {
body: payload,
icon: '/firebase-logo.png'
}; self.registration.showNotification(notificationTitle,
notificationOptions);
});```

The above file is supposed to run in the background so we will register it with the service worker (A mechanism to run the process in the background, click on the link to get a better understanding of service worker.)

Let’s register with the service worker

async function registerWorker() {console.log('Registering service worker');const registration = await navigator.serviceWorker.
register('/firebase-messaging-sw.js', {scope: '/'});
console.log('Registered service worker');
const subscription = await registration.pushManager.subscribe({userVisibleOnly: true,applicationServerKey: 'my_VAPID'});}if ('serviceWorker' in navigator) {
console.log('Registering service worker');
regiserWorker().catch(error => console.error(error));
}

Now we start the firebase server with firebase serve -p 8081 or if you have express server setup then do node app.js.

You can go to localhost:8081 to see your client-side page, copy the token id printed in the console. You will have to allow the show notification popup of the browser, otherwise, you will not get the token.

Let’s do a curl request to test the notification.

curl -X POST -H "Authorization: key=YOUR_SERVER_KEY" -H "Content-Type: application/json" -d '{"notification": {"title": "First notif",
"body": "Hello world",
"icon": "firebase-logo.png",
"click_action": "http://localhost:8081"
},"to": "CLIENT_TOKEN"}' "https://fcm.googleapis.com/fcm/send"

Press enter and you should see your first notification.

Thanks for your patience reading. Happy development.
I welcome your suggestions(So don’t be shy to leave one
:-D )

Namaste…

--

--

Ayush Chaurasia
The Startup

Team lead, Voracious Reader, and loves to solve problems.