Firebase Push Notification Message with JavaScript

Introduction to Firebase

Charles
Charles
Dec 18, 2017 · 3 min read

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.

FCM server has two components for sending and receiving messages which are:

firebase
  • The trusted environment (app server)
  • FCM servers

It is the job of the app server to send the message to the FCM server which then sends the message to the client device.

The trusted environment can be an app server for sending messages; you can also use the Admin SDK or HTTP and XMPP APIs. The work of the server is to forward the message to the FCM server which then sends to the client.

Find out more about how it works here: https://firebase.google.com/docs/cloud-messaging/

In this tutorial, I will show you how to use firebase using JavaScript client to send token and notification messages to the FCM Legacy server.

The FCM JavaScript API lets you receive notification messages in web apps running in browsers that provide service worker support. This includes the following browsers. Check out https://firebase.google.com/docs/cloud-messaging/js/client for more info.

bp

To get a boilerplate code from FCM console, navigate to the developer section and click on the WEB SETUP link above, you will get a boilerplate code to configure your FCM client.

Open the index.html page and you get a notification message that is asking for your permission, click “Allow” refresh the page and the token would be displayed in the browser console then. Copy the token and save it somewhere on your computer.

live_server

Note: I am currently using visual studio code live server instead of creating a node-js app server.

Fork/clone the source code on Git: https://github.com/cizu64/FirebaseClientNotification

To send a message, login to the firebase console and create a new project which is available on https://console.firebase.google.com/

Now you make your request to the Legacy protocol endpoint to create a message.

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=[Server key]

Note: To access this endpoint, you need to be authorized with the server key. If you try to access it with postman without the server, it will throw an error.

The endpoint must contain two request headers for the message to be sent successfully.

  • Content-type: application/json
  • Authorization: Key = <server key>

The server key can be found in the firebase project settings section under the tab cloud messaging in the firebase console.

The notification message is displayed in the console and if the browser is minimized or you open another page, it would show the notification toast.

check out this blog for ASP.NET client integration http://techcerberus.blogspot.com.ng/2017/12/sending-notification-message-with.html

Charles

Written by

Charles

Software developer, Entrepreneur, Writer