Firebase Push Notification Using NodeJS.

 


Step 1: Set up Firebase Project

Go to the Firebase Console(https://console.firebase.google.com/)

Create a new project or select an existing one.

Go to Project Settings -> Cloud Messaging tab.

Take note of the Server Key and Sender ID.

Step 2: Set up Node.js Project

mkdir firebase-push-notifications

cd firebase-push-notifications

npm init -y

npm install firebase-admin

Step 3: Write the Code

Create a file named index.js and add the following code:

const admin = require('firebase-admin');

// Initialize Firebase Admin SDK
const serviceAccount = require('./path/to/serviceAccountKey.json'); // Path to your service account key file
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

// Send a push notification
function sendPushNotification(token, title, body) {
  const message = {
    notification: {
      title: title,
      body: body,
    },
    token: token,
  };

  admin.messaging().send(message)
    .then((response) => {
      console.log('Successfully sent message:', response);
    })
    .catch((error) => {
      console.error('Error sending message:', error);
    });
}

// Example usage
const deviceToken = 'YOUR_DEVICE_TOKEN'; // FCM registration token of the device
const notificationTitle = 'Hello';
const notificationBody = 'This is a Firebase Cloud Messaging notification!';

sendPushNotification(deviceToken, notificationTitle, notificationBody);

Step 4: Run the Code

Run your Node.js script:

Importance notes

Make sure to replace './path/to/serviceAccountKey.json' with the actual path to your Firebase service account key file, and replace 'YOUR_DEVICE_TOKEN' with the device token you want to send the notification to.
To obtain the device token, you need to implement token generation on the client side (typically in your mobile app).
This example sends a notification to a single device.


Comments

Popular posts from this blog

Details in JavaScript Array Methods with Examples