Search code examples
node.jsflutterfirebasepush-notificationfirebase-cloud-messaging

How to Send PushNotification one To one user like a chat app in Flutter by using firebase function?


I want it send to one user but it send to all user nad this is my index.js and from this query from firebase cloud firestore connect(Collection)=>userID(connect(Document))=>userconnect(collection)=>PetID(Document)=>message(collection)=>messageID(message(Document))=>in the field name uid is the uid of receiver and in the same query the field of email is email of user that is sender.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.notifyUserOnMessage = functions.firestore.document('connect/{userId}/userconnect/{petId}/message/{messageId}')
    .onCreate(async (snapshot, context) => {
        const messageData = snapshot.data();

        // Extract the userId and petId from the context
        const targetUserId = context.params.userId;
        const petId = context.params.petId;

        // Fetch the userconnect document to get the userid field
        const userConnectDoc = await admin.firestore().doc(`connect/${targetUserId}/userconnect/${petId}`).get();
        const userConnectData = userConnectDoc.data();

        let recipientUserId;

        if (messageData.uid === userConnectData.userid) {
            recipientUserId = targetUserId;
        } else {
            recipientUserId = userConnectData.userid;
        }

        const payload = {
            notification: {
                title: 'You Have New Message',
                body: 'New Message Arrive.',
                clickAction: 'FLUTTER_NOTIFICATION_CLICK',
            },
            data: {
                click_action: 'FLUTTER_NOTIFICATION_CLICK', // for background
            }
        };


        return admin.messaging().sendToTopic(recipientUserId, payload);
    });

How can i make it send to user that i specific.


Solution

  • You should retrieve a unique token for each user on the end user side let's say after they logged in to your app Ex. Flutter app using

    FirebaseMessaging.instance.getToken().then((token) {
          appPrint('Token is $token');
        });
    

    then you should store this token somewhere (with user's data) and whenever you want to send a notification for this user just pass the stored token inside the map payload

    const payload = {
            token: storedToken, // TOKEN THAT YOU ALREADY STORED IT
            notification: {
                title: 'You Have New Message',
                body: 'New Message Arrive.',
                clickAction: 'FLUTTER_NOTIFICATION_CLICK',
            },
            data: {
                click_action: 'FLUTTER_NOTIFICATION_CLICK', // for background
            }
        };
    

    After passing it the firebase will do the magic for you.