Firebase

How to set up Firebase Cloud Messaging for topic-based notifications?

Discover how to configure Firebase Cloud Messaging for topic-centric alerts. Follow this detailed guide: from initializing your project to dispatching notifications, ensuring users stay effortlessly connected.

Developer profile skeleton
a developer thinking

Overview

Firebase Cloud Messaging (FCM) lets you send notifications instantly to keep your users engaged on different platforms. With topic-based notifications, users can be grouped by what they care about, ensuring they get messages that matter to them. The setup process has a few main steps: configuring Firebase, integrating FCM in your app, and letting users subscribe to chosen topics. There's also the need to create server-side logic for sending out these tailored messages. Using FCM effectively boosts user interaction and retention with precise communication.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to set up Firebase Cloud Messaging for topic-based notifications?

Step 1: Set Up Firebase Project

  1. Head over to the Firebase Console.
  2. Click on Add Project and just follow the steps to either create a new project or pick an existing one.
  3. Once you're all set, go to the project dashboard.

Step 2: Add Firebase to Your App

  1. In your Firebase project, click the </> icon to add Firebase to your web app.

  2. Follow the instructions to grab the Firebase SDK and firebaseConfig object.

  3. Add the script tags to your HTML and initialize Firebase with the firebaseConfig object at the start of your JavaScript file.

    ```javascript
    // Import the required Firebase modules
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
    import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-messaging.js";

    const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    ```

Step 3: Enable Firebase Cloud Messaging (FCM)

  1. In the Firebase console, go to Project Settings.
  2. Click on the Cloud Messaging tab.
  3. Make sure the Cloud Messaging API is enabled and generate the Server Key. You'll need this for sending notifications.

Step 4: Request Permission to Send Notifications

  1. Ask the user for notification permissions and get an FCM token.

    ```javascript
    const messaging = getMessaging(app);

    // Request permission to send notifications
    Notification.requestPermission().then((permission) => {
    if (permission === 'granted') {
    console.log('Notification permission granted.');
    getToken(messaging, { vapidKey: 'YOUR_PUBLIC_VAPID_KEY' }).then((currentToken) => {
    if (currentToken) {
    console.log('FCM Token:', currentToken);
    // Send the token to your server and subscribe to the topic
    subscribeToTopic(currentToken, 'news'); // Example topic: 'news'
    } else {
    console.log('No registration token available. Request permission to generate one.');
    }
    });
    } else {
    console.log('Unable to get permission to notify.');
    }
    });

    function subscribeToTopic(token, topic) {
    fetch(https://iid.googleapis.com/iid/v1/${token}/rel/topics/${topic}, {
    method: 'POST',
    headers: new Headers({
    'Authorization': key=YOUR_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:', error);
    });
    }
    ```

Step 5: Handle Incoming Messages

  1. Set up a listener to handle incoming messages when the app is in the foreground.

    ```javascript
    onMessage(messaging, (payload) => {
    console.log('Message received. ', payload);
    // Customize notification handling logic here
    });
    ```

Step 6: Send a Topic Message from Server

  1. Use the server key you got in Step 3 and the FCM endpoint to send topic messages.

    ```python
    import requests
    import json

    def send_fcm_topic_notification():
    server_key = 'YOUR_SERVER_KEY'
    topic = 'news' # Example topic
    headers = {
    'Content-Type': 'application/json',
    'Authorization': f'key={server_key}',
    }
    payload = {
    'to': f'/topics/{topic}',
    'notification': {
    'title': 'Breaking News',
    'body': 'Click to read the latest news!',
    },
    'data': {
    'key1': 'value1',
    'key2': 'value2',
    },
    }
    response = requests.post('https://fcm.googleapis.com/fcm/send', headers=headers, data=json.dumps(payload))
    print(response.status_code, response.text)
    send_fcm_topic_notification()
    ```

Each step needs to be followed in order to set up Firebase Cloud Messaging topic-based notifications correctly.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.