• Home
  • React + Firebase – How to send push notifications

React + Firebase – How to send push notifications

Many today’s websites send some notifications to their users and today I will show you how to implement such functionality in your React Web App using Firebase. You can find code for this demo in my Github here.

Firebase is Google Platform that offers various services for web developers which help them to build their apps quickly. To send the notifications, we will use the service called Cloud Messaging, which allows us to send messages to any device using HTTP requests.

Please take a look a Firebase documentation first and then register your account and create a new project within it. Go to your project settings inside Firebase console and click Add Firebase to your Web App. You will get some snippet inside popup and you need to copy it and save to your machine because we will need some config from it later in our React App.

Now let’s create basic React App on our machine…

create-react-app chrisvznots

After we create React app we need to install firebase package

cd chrisvznots
npm install firebase --save

Inside our src directory we need to create file called pushnotification.js. This file initializes Firebase and passes the keys of your project. Replace messagingSenderId wit your sender id ( you can find it inside your copied snippet from Firebase project that you save earlier on your machine)

Also in this file we will create the function askForPermissioToReceiveNotifications so that user can choose whether or not to receive notifications.

pushnotification.js

import firebase from 'firebase';

export const initializeFirebase = () => {
  firebase.initializeApp({
    messagingSenderId: '<--YOUR SENDER ID-->' // tvoj sender id
  });
}

export const askForPermissioToReceiveNotifications = async () => {
  try {

    const messaging = firebase.messaging();

    await messaging.requestPermission();
    const token = await messaging.getToken();
    console.log('user token: ', token);

    return token;
  } catch (error) {
    console.error(error);
  }
}

We need to call initializeFirebase inside our entry point of React App. Go to index.js and add initializeFirebase()

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { initializeFirebase } from './pushnotification';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.register();
initializeFirebase();

Also our app needs Service Worker

A service worker is a script that your browser runs in the background, separate from the web page, enabling features that do not require a web page or user interaction.

By default when we start Firebase app looks for a file called firebase-messaging-sw.js. So let’s create that file inside our public folder

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');

firebase.initializeApp({
    messagingSenderId: '<--YOUR SENDER ID-->' // tvoj sender id
});

const messaging = firebase.messaging();

This service worker will basically import the script needed to show the notifications when your app is in the background.

Next we need to call our askForPermissioToReceiveNotifications function from app so I add simple button inside App.js

import React, { Component } from 'react';
import './App.css';
import { askForPermissioToReceiveNotifications } from './pushnotification';


class App extends Component {
  render() {
    return (
      <div className="App">
       
        <button onClick={askForPermissioToReceiveNotifications} >
          Click here to receive notifications
       </button>

      </div>
    );
  }
}

export default App;

So now is everything ready for testing notifications. Start your react app with npm start and go to localhost:3000

When you click button <Click here to receive notifications> you will see little popup and you need to Allow to receive notifications. After you do that in your developer console you can see user token which we will need when we send some message to this user.

Sending notifications

To send notification to some user we need to make a request to the Firebase API with user token ( that user will receive message )

For testing this I use Postman but you can use any other REST client. Basically, we need to make a POST request to https://fcm.googleapis.com/fcm/send by sending a JSON in the request body.

Here is sample JSON request:

{
    "notification": {
        "title": "Firebase",
        "body": "Firebase is awesome",
        "click_action": "http://localhost:3000/",
        "icon": "http://url-to-an-icon/icon.png"
    },
    "to": "USER TOKEN"
}

Replace “USER TOKEN” with your token that you have inside your Developer Console.

Also we need to pass some request headers :

Content-Type: application/json
Authorization: key=SERVER_KEY

Replace server key with your server key. The server key is found in the project settings in the Firebase Console under the Cloud Messaging tab.

Now, click Send and you will see notification …

You can find code for this demo in my Github here.

Thanks for reading….

 

Tags: , ,

Copyright by Kristijan Klepač 2018