In this tutorial, we’ll explore how to deploy Firebase Functions with Node.js to send push notifications to your mobile app users. Push notifications are a powerful tool for engaging users and informing them about critical updates or events within your application.

Prerequisites

Before we begin, make sure you have the following:
Node.js is installed on your machine.

  • A Firebase project set up on the Firebase Console.
  • Firebase CLI installed (npm install -g firebase-tools).
  • Basic knowledge of JavaScript and Firebase.

Setting Up Firebase Function

  1. Initialize Firebase in your project directory
    firebase init function
  2. Install the necessary dependencies:
    npm install firebase-admin

Creating the Push Notification Function.
Now, let’s create a Firebase Function to send push notifications. Create a file named sendPushNotification.js in your functions directory:

// sendPushNotification.js
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK
const serviceAccount = require('./serviceAccount.json');
const projectId = serviceAccount.project_id;
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  projectId: projectId
});
async function sendPushNotification(registrationToken, notificationPayload) {
  const message = {
    notification: {
      title: notificationPayload.title,
      body: notificationPayload.body
    },
    token: registrationToken
  };
  try {
    const response = await admin.messaging().send(message);
    return response;
  } catch (error) {
    console.error('Error sending push notification:', error);
    return error;
  }
}
module.exports = { sendPushNotification };

Implementing the HTTP Function
Next, let’s create an HTTP function to trigger the push notification. Create a file named. index.js:

// index.js
const { onRequest } = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
const sendPushNotification = require("./sendPushNotification");

exports.sendNotificationToApp = onRequest(async (request, response) => {
  logger.info("Sending push notification...");
  const { tokens, notification } = request.body;
  const data = await sendPushNotification.sendPushNotification(tokens, notification);
  response.send(data);
});

Deploying the Function
Finally, let’s deploy our Firebase Function:
firebase deploy --only functions
Conclusion
In this tutorial, we’ve learned how to deploy Firebase Functions with Node.js to send push notifications to mobile app users. Push notifications are an essential tool for engaging users and keeping them informed about important application updates. Experiment with different notification payloads and delivery strategies to optimize user engagement in your app.

Read more: Firebase Functions: Push Notifications with Node.js

Read More Blog

Quiz Time