Search code examples
javascriptfirebasefirebase-cloud-messagingfirebase-admin

How to set up firebase FCM with Admin SDK for database triggers


I am trying to set up FCM notifications for database triggers using the Firebase Admin SDK and Node js. Based on what I read in the docs, I understand you need the device notification key to send a notification. However, how should the server get the device notification key? Is this something that should be passed from the client to the server? Or is this something that I can look up from my server with an Auth id?

Since the FCM should be fired when the Firebase Database receives an update, I'm not sure how to request then the device notification key responsible for that update.

Thanks


Solution

  • You will need to store all the tokens in a database, where your sender code can then read them from.

    If you look at the sample code in the Firebase documentation on setting up your app for receiving message, you'll see code like this:

    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
    
        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // FCM registration token to your app server.
        sendRegistrationToServer(token);
    }
    

    The call to sendRegistrationToServer is an example of what you might do: it is a function that sends the token to your server, which then presumably stores it in the database.

    If you then look at this example of sending messages to users when data is written to a database, you'll see that it reads the tokens from the database, uses them to send messages to all relevant tokens, and then cleans up tokens that have expired.