Steve O
Steve O

Reputation: 228

How to notify offline Firebase Cloud Messaging web-clients that they have unread messages

I am using Firebase Cloud Messaging FCM in a web app, my scenario is as follows:

User-A tries to send user-B (who is offline) a message.

When this happens I would like to email user-B so that they know to come back to the web-app to get their message.

So, the two pieces of information on which the decision to contact a user are:

  1. that they are offline
  2. they have an unread message(s)

I have looked at potentially polling things like firebase.database.OnDisconnect or perhaps polling auth.

As this is server-less there are no hooks, so what should I use for this?

Upvotes: 0

Views: 314

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

As this is server-less there are no hooks

Actually, Firebase has a built in system to listen for database changes (such as the onDisconnect write firing) in Cloud Functions for Firebase. For example say that you use a presence system as shown in the docs, storing the connection(s) for each user under /onlineUsers/$uid. That means that as long as the user is online on any device, their /onlineUsers/$uid will exist, and when their last connection is closed (or at least when the server detects that) their /onlineUsers/$uid will disappear.

Now you can set up a Cloud Function that runs in response to a /onlineUsers/$uid being deleted with something like:

exports.userWentOffline = functions.database.ref('/onlineUsers/{uid}')
    .onDelete((snapshot, context) => {
      console.log('userWentOffline', context.params.uid);
      return null;
    });

You can do whatever you want in the body of this Cloud Function.


If you want to take action on another trigger if the user is no longer connected, you'll want to check whether their /onlineUsers/$uid node exists.


A few things to keep in mind:

  • A single user/UID can have multiple connections to the database, even when they're on a single device. So be sure to implement the presence system as shown at the end of the docs I linked, which allows for this.
  • If the connection between the client and the server is not cleanly terminated, it may take up to a few minutes before the server detects that the client is gone, and fires the onDisconnect handlers. So when the Cloud Function runs, you'll want to detect which recent messages have not been delivered.

Upvotes: 1

Related Questions