How to implement Firebase push notification in React JS and Node JS

How to implement Firebase push notification in React JS and Node JS

How to implement Firebase push notification in React JS and Node JS

To implement Firebase push notifications in React JS and Node JS, you can follow the steps below:

  1. Create a Firebase project and enable Cloud Messaging:
  • Go to the Firebase console and create a new project.
  • Once the project is created, go to Project Settings and click on the Cloud Messaging tab.
  • Here, you will find the Server Key and Sender ID. Note them down as you will need them later.
  1. Set up Firebase SDK in your React JS project:
  • Install the Firebase SDK by running npm install firebase in your project directory.
  • Create a new Firebase app by initializing it with your Firebase project credentials:
import firebase from 'firebase/app';
import 'firebase/messaging';

firebase.initializeApp({
  // Your Firebase project configuration object
});

const messaging = firebase.messaging();
messaging.getToken({ vapidKey: 'YOUR_VAPID_KEY' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server for further use
  } else {
    // Show permission request UI
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
});
  1. Implement Firebase Cloud Functions for sending push notifications:
  • Install the Firebase SDK by running npm install firebase-admin in your project directory.
  • Create a new Firebase Cloud Function that listens for changes in your database and sends push notifications to subscribed users:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.sendNotification = functions.database.ref('/messages/{pushId}').onCreate((snapshot, context) => {
  const message = snapshot.val();
  const payload = {
    notification: {
      title: message.title,
      body: message.body,
      click_action: message.click_action
    }
  };

  return admin.messaging().sendToTopic('notifications', payload);
});

  1. Subscribe to push notifications in your Node JS app:
  • Initialize the Firebase Admin SDK with your Firebase project credentials:
const admin = require('firebase-admin');
const serviceAccount = require('./serviceAccount.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'YOUR_DATABASE_URL'
});

const messaging = admin.messaging();
  • Subscribe a user to a topic:
  messaging.subscribeToTopic('DEVICE_TOKEN', 'notifications')
  .then(() => console.log('Successfully subscribed to topic'))
  .catch((err) => console.log('Error subscribing to topic: ', err));

  • Unsubscribe a user from a topic:
  messaging.unsubscribeFromTopic('DEVICE_TOKEN', 'notifications')
  .then(() => console.log('Successfully unsubscribed from topic'))
  .catch((err) => console.log('Error unsubscribing from topic: ', err));