You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cloud Function在Firebase实时数据库Message节点新增子节点时推送通知?

Hey there! I've got you covered with a complete Cloud Function setup to handle this push notification requirement. Since you're new to Node.js, I'll break it down step by step and explain each part clearly so you can follow along easily.

Prerequisites First

Before diving into code, make sure you have these setup:

  • Install the Firebase CLI: Run npm install -g firebase-tools in your terminal
  • Initialize Cloud Functions in your Firebase project: Execute firebase init functions and follow the prompts (choose JavaScript as the language)
  • Enable Firebase Cloud Messaging (FCM) in your Firebase Console (it's usually enabled by default, but double-check under the "Cloud Messaging" tab)
The Complete Cloud Function Code

Replace the contents of functions/index.js with this code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Initialize Firebase Admin SDK
admin.initializeApp();

// Trigger this function when a new message is added to the /Message node
exports.sendNewMessageNotification = functions.database
  .ref("/Message/{messageId}")
  .onCreate(async (snapshot, context) => {
    try {
      // 1. Fetch all user FCM tokens from your database
      // Adjust the path below to match where you store user data (e.g., /users/{userId}/fcmToken)
      const usersSnapshot = await admin.database().ref("/users").once("value");
      const users = usersSnapshot.val();

      if (!users) {
        functions.logger.info("No users found to send notifications to");
        return null;
      }

      // Collect all valid FCM tokens (filter out any empty/null tokens)
      const fcmTokens = Object.values(users)
        .map(user => user.fcmToken)
        .filter(token => token !== null && token !== undefined);

      if (fcmTokens.length === 0) {
        functions.logger.info("No valid FCM tokens found");
        return null;
      }

      // 2. Create the notification payload
      const notificationPayload = {
        notification: {
          title: "New Message Alert",
          body: "You have new message"
        }
      };

      // 3. Send the notification to all users
      const response = await admin.messaging().sendMulticast({
        tokens: fcmTokens,
        notification: notificationPayload.notification
      });

      // Log results
      functions.logger.info(`Successfully sent ${response.successCount} notifications`);
      functions.logger.warn(`Failed to send ${response.failureCount} notifications`);

      // Optional: Handle failed tokens (you could remove invalid tokens from your database here)
      const failedTokens = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success) {
          failedTokens.push(fcmTokens[idx]);
        }
      });
      if (failedTokens.length > 0) {
        functions.logger.error("Failed tokens:", failedTokens);
      }

      return null;
    } catch (error) {
      functions.logger.error("Error sending notifications:", error);
      return null;
    }
  });
Key Things to Adjust for Your Project
  • Database Paths: The code assumes you store user data in /users with each user having an fcmToken field. If your structure is different (e.g., /userProfiles/{userId}/deviceToken), update the path in admin.database().ref("/users") and the user.fcmToken part.
  • Notification Content: You can tweak the title and body in the notificationPayload if you want to adjust the notification text.
How to Deploy the Function

Once you've adjusted the code to match your project, run this command in your terminal (from the functions directory or your project root):

firebase deploy --only functions

That's it! Now whenever a new child node is added to /Message, the function will trigger and send the notification to all users with valid FCM tokens stored in your database.

内容的提问来源于stack exchange,提问作者Sairaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:47:02