How to subscribe to topics with web browser using Firebase Cloud Messaging

Derek picture Derek · Nov 2, 2016 · Viewed 15.9k times · Source

I'm trying to find a way to send a notification using Firebase Cloud Messaging to all of my app's users, but I have a web-only app. I've seen solutions that appear to be for Android/iOS, which basically involves having the users auto-subscribe to a topic called "allDevices" and then sending a notification to all users subscribed to that topic. I just can't seem to find any documentation on how to have a web-based user subscribe to a topic. Does anyone know if that's possible, and if it is, is there documentation that I've missed that would cover that?

Thanks!

Answer

Frank van Puffelen picture Frank van Puffelen · Nov 2, 2016

There is no direct API to subscribe clients to topics in the Firebase Cloud Messaging SDK for JavaScript. Instead you can subscribe a token to a topic through the REST API. Calling this API requires that you specify the FCM server key, which means that you should only do this on a trusted environment, such as your development machine, a server you control, or Cloud Functions. This is necessary, since having the FCM server key allows sending messages on your app's behalf to all of your app's users.

It turns out that in my tests I was using an older project, where client API keys were allows to subscribe to topics. This ability has been removed from newer projects for security reasons.

In Node.js you could for example call the REST API to create a relation mapping for an app instance](https://developers.google.com/instance-id/reference/server#create_a_relation_mapping_for_an_app_instance) like this:

function subscribeTokenToTopic(token, topic) {
  fetch('https://iid.googleapis.com/iid/v1/'+token+'/rel/topics/'+topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'key='+fcm_server_key
    })
  }).then(response => {
    if (response.status < 200 || response.status >= 400) {
      throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();
    }
    console.log('Subscribed to "'+topic+'"');
  }).catch(error => {
    console.error(error);
  })
}

Where fcm_server_key is the FCM server key, taken from the Firebase console of your project.