Derek Derek - 1 year ago 289
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?


Answer Source


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(''+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 => {

Where config is the configuration snippet for your Firebase web application, so config.apiKey is the public api key for your app.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download