1. Opening:
Hello everyone today I will show you how to push notification firebase with reactjs and nodejs. No more wandering, let’s do it together
2. Create reactjs and nodejs project projects
Note: Your computer must have nodejs pre-installed before creating reactjs and nodejs projects, if anyone has not installed access to the link: https://nodejs.org/en
1. Create reactjs . project
To create a reactjs project, run the following command:
npx create-react-app reactjs-firebase
Then you run the following command to install the necessary packages for the project:
npm install firebase --save
2. Create a nodejs . project
To create a nodejs project, run the following command:
npm init
Then you run the following command to install the necessary packages for the project:
npm install fcm-notification fcm-node express --save
3. Configure firebase
1. Firebase login
We will visit this link https://firebase.google.com/ to register or login
You click on the create a project
button as shown above:
Next we enter an arbitrary name and click continue
Continue clicking continue
We click on create a new account
and enter an arbitrary name as shown below
We will choose like the image below and click Create project
Creating the project we will have to wait for a while
2. Create a firebase project for the web
After the notification project is created, click on the continue
button, then it will go to the management page and now we will click the button as shown in the image below to register the project for the web.
You will enter your project name:
Then click on the Register app button, you will see a manual page open:
Copy the code above and save it somewhere for us to use
4. Configuration
1. Configure firebase for Reactjs
We go to the reactjs project just created above and create a file called firebase-messaging-sw.js located in the public
folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Scripts for firebase and firebase messaging // eslint-disable-next-line no-undef importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js'); // eslint-disable-next-line no-undef importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js'); // Initialize the Firebase app in the service worker by passing the generated config const firebaseConfig = { apiKey: "your-code", authDomain: "your-code", databaseURL: "your-code", projectId: "your-code", storageBucket: "your-code", messagingSenderId: "your-code", appId: "your-code" }; // eslint-disable-next-line no-undef firebase.initializeApp(firebaseConfig); // Retrieve firebase messaging // eslint-disable-next-line no-undef const messaging = firebase.messaging(); messaging.onBackgroundMessage(function(payload) { console.log('Received background message ', payload); const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, }; // eslint-disable-next-line no-restricted-globals self.registration.showNotification(notificationTitle, notificationOptions); }); |
and edit firebaseConfig
you just created in the previous step
Next in the src folder you create the file firebase.js and copy the code below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import { initializeApp } from "firebase/app"; import { getMessaging, getToken, onMessage } from "firebase/messaging"; const firebaseConfig = { apiKey: "your-code", authDomain: "your-code", databaseURL: "your-code", projectId: "your-code", storageBucket: "your-code", messagingSenderId: "your-code", appId: "your-code" }; const firebaseApp = initializeApp(firebaseConfig); const messaging = getMessaging(firebaseApp); export const fetchToken = (setTokenFound) => { return getToken(messaging, { vapidKey: "", }) .then((currentToken) => { if (currentToken) { console.log("current token for client: ", currentToken); setTokenFound(true); } else { console.log( "No registration token available. Request permission to generate one." ); setTokenFound(false); } }) .catch((err) => { console.log("An error occurred while retrieving token. ", err); }); }; export const onMessageListener = () => new Promise((resolve) => { onMessage(messaging, (payload) => { resolve(payload); }); }); |
Then also edit firebaseConfig
1 2 3 4 5 | return getToken(messaging, { vapidKey: "", }) |
Now we will get vapidKey
Go back to the firebase management page and click on the tab as shown in the image below
Then select the cloud messaging
tab and scroll down to the bottom and click the Generate key pair
button to generate the key, then copy the newly created key and replace the value for vapidKey
Next, copy the code below into the src/App.js
folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import logo from './logo.svg'; import './App.css'; import {useEffect, useState} from 'react'; import { fetchToken, onMessageListener } from './firebase'; import 'bootstrap/dist/css/bootstrap.min.css'; function App() { const [show, setShow] = useState(false); const [notification, setNotification] = useState({title: '', body: ''}); const [isTokenFound, setTokenFound] = useState(false); useEffect(() => { fetchToken(setTokenFound); },[]) onMessageListener().then(payload => { setNotification({title: payload.notification.title, body: payload.notification.body}) setShow(true); console.log(payload); }).catch(err => console.log('failed: ', err)); const onShowNotificationClicked = () => { setNotification({title: "Notification", body: "This is a test notification"}) setShow(true); } return ( <div className="App"> <header className="App-header"> {isTokenFound && <h1> Notification permission enabled 👍🏻 </h1>} {!isTokenFound && <h1> Need notification permission ❗️ </h1>} <img src={logo} className="App-logo" alt="logo" /> </header> </div> ); } export default App; |
We start the project with the command npm start
and go to http://localhost:3000/ . And allow the browser to push notifications like the image below:
Now you open the browser’s console window and see if there will be a token string for the client:
Copy the string like the picture I circled in red and go back to the firebase management page and select the tab as shown below
You click the button Create your first campaign
to create a test message
Next, you set Notification title
and Notification text
:
Then click the send test message button on the right. It will display a popup where you paste the token you just copied the console window into, then press the +
sign and finally press button test
.
Great to be done after so many steps finally the announcement was pushed out
The reactjs setup step is done, continue to the nodejs setup step
2. Configure firebase for Nodejs
In the nodejs folder you create the file index.js and copy the code below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | var FCM = require('fcm-node'); var serviceAccount = require("your_path_key"); const express = require("express"); const app = express(); var admin = require("firebase-admin"); app.use(express.json()) fcm = new FCM("private_key"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), }); const certPath = admin.credential.cert(serviceAccount); exports.sendPushNofication = (req, res, next) => { console.log(req) } app.post('/send-noti', (req, res) => { try { let message = { to:'token_client', notification: { title: req.body.title, body: req.body.content }, } fcm.send(message, function(err, resp) { if (err) { return res.status(500).send({ message: err }) } else { return res.status(200).send({ message: resp }) } }) } catch (err) { console.log(err) } }) app.listen(5000, function() { console.log(`port run on localhost:5000`); }) |
Then you go back to the firebase page and select the tab as shown below:
You click on generate new button Generate new private key
to generate the key then save it in the nodejs folder
and replace your_path_key
in the code at the top with the path where your key just downloaded:
Continue to select the tab as shown in the picture and click the button Manage API in Google Cloud Console
to switch to the google cloud management page to enable firebase
After you enable it, reload the firebase management page and you will see server key
section
Copy and paste it instead of private_key
in fcm = new FCM("private_key");
The last step you go back to the browser http://localhost:3000/ , and open the browser’s console window and see a token string for the client:
copy the above string and replace token_client
located in
1 2 3 4 5 6 7 8 | let message = { to:'token_client', notification: { title: req.body.title, body: req.body.content }, } |
Ok after so many steps, now we are done, let’s check the results. Now we will use postman to test. Please fill in the postman content like me
After using postman to send you will see the message has been pushed
5. Conclusion
This friend is also quite long, maybe when I write there will be many shortcomings or not fully describe the idea, hope everyone can give me suggestions to improve the quality of the article. I would like to thank everyone for following and supporting me