Derek Derek - 1 month ago 23
Javascript Question

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

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

Update

Subscribing a token to a topic through the REST API requires the user of the server key. Since having the server key allows sending messages on your app's behalf to all of your app's users, this can only be securely done from a process that you control.

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.

Original answer below:

You can call the REST API to do so, specifically create a relation mapping for an app instance:

function subscribeTokenToTopic(token, topic) {
  fetch('https://iid.googleapis.com/iid/v1/'+token+'/rel/topics/'+topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'key='+config.apiKey
    })
  }).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 config is the configuration snippet for your Firebase web application, so config.apiKey is the public api key for your app.