Sign up

app push notifications

How to Use Firebase to Send Push Notifications

Angela Stringfellow

Last updated on

Push notifications are an integral part of any new application because they provide a direct line of communication between an application and its users. Application developers use push notifications to engage users, increase sales, introduce new products, and share other business-related information. Since push notifications have a critical impact on business, many companies now have a push notification strategy in place.

However, users are on a multitude of platforms, fragmenting the communication process. It’s difficult for developers to implement push notifications in this kind of environment. Users could use different operating systems and browsers, for example, making it difficult for developers to build the right solutions. It’s much more challenging to code and develop push notification systems for all these platforms.

Many service providers combine the push notification requirements for an application into a single platform. This way, developers can build their applications, and the notification integrator will do the work of sending the notifications on different platforms.

Firebase Cloud Messaging (FCM) is a helpful notification integrator that does just that. Learn how FCM works, why it’s so helpful, and how to send push notifications with Firebase.

In this article:

A Quick Primer on Firebase Cloud Messaging

FCM is a service under Firebase, an integral component of the Google Cloud Platform (GCP). Firebase helps developers reduce the amount of coding required to build and deploy applications quickly.

According to the Firebase team, “Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.” Developers use FCM to build messaging solutions for their applications, including push notifications for various platforms. In fact, FCM natively supports:

  • iOS
  • Android
  • Web applications
  • C++ environment
  • Unity environment

Thanks to multiplatform support, developers don’t have to build notification systems from the ground up for each platform, saving the development team a lot of time. Plus, this approach makes application codebases easier to read and understand.

It’s no wonder why FCM adoption is on the rise. Nearly 325,000 live websites currently use Firebase.

FCM acts as a powerful intermediary for integrating and implementing push notifications for applications across various platforms.

For instance, say you have three versions of your application: one for the iOS ecosystem, another for Android, and the third for web applications. Without FCM, you’d need to build more than three notification systems. You’d need one each for iOS and Android, but then you’d also need to accommodate all the different types of browsers for the web application to deliver push notifications without a hitch.

With FCM, you only need to add a few lines of code to each application, and you’ll then be able to send notifications to different platforms from the FCM console. You can also send push notifications programmatically. This makes things even simpler for your company’s development team.

Why FCM?

Developers use multiple platforms to send push notifications, but FCM is the most popular because of its extensive features and customer support. FCM is one of the most sought-after notification tools for several reasons.

Integration

FCM has a wide range of integrations with various service providers. Sure, it supports push notifications for iOS, Android, and the web, but the integrations go further than that.

For example, it’s easy to integrate FCM with other services hosted on the Google Cloud Platform. With this setup, you can manage Google Ads, Google Analytics, Google AdMob, and more on the same platform.

FCM also has no trouble integrating with other cloud service providers like AWS, Microsoft, and Linode. These out-of-the-box integrations make FCM implementation easier and faster for developers.

Analytics

FCM integrates seamlessly with Google Analytics, one of the most popular web analytics platforms on the planet. Developers use this powerful free tool to understand how users interact with their push notifications, assess website or app performance, and much more.

With user data in hand, you can design and implement a better push notification strategy that’s in line with your business goals. Google Analytics lets you segment users to gain granular information on how users interact with your applications. It also integrates with BigQuery, the data warehousing solution for the Google Cloud Platform.

Versatile Targeting

The more personalized push notifications are, the more likely users are to engage with them. With FCM, you can create any number of user segments for easy personalization. Cluster users who exhibit similar characteristics and send them custom messages based on their preferences. This FCM feature allows you to target each user with a message that resonates well.

A/B Testing

Analytics data is essential to improving push notification campaigns, but it won’t tell you everything. A/B testing makes it possible to assess different versions of push notifications and choose the best-performing options. FCM allows A/B testing through Google Optimize, which gives you an intuitive platform for running push notification tests.

Of course, A/B testing should be combined with other testing and analysis tools to fully evaluate your push notifications before implementation. For web push notifications, MagicBell’s Web Push Notifications Demo is a valuable solution to demo standards-based web push notifications on all platforms—including iOS.  

In-App Messaging

Contextual messages are powerful tools for engaging users. FCM can also send targeted contextual messages through in-app messaging. These relevant messages increase in-app engagement for active users, ultimately improving the user experience while driving sales.

Sending Push Notifications with Firebase

Firebase is a valuable tool to have in your corner. From analytics to custom messaging, FCM improves developer workloads while improving the user experience.

Ready to implement push notifications with Firebase? The exact process depends on your platform. In this guide, we’ll focus on implementing push notifications for a web application with FCM.

Check out these resources for platform-specific deep dives:

Registering Your Application

The Firebase console contains everything you need to create and send notifications to web applications. To get started, visit the console and click the “Add project” button.

Firebase Add project button screenshot
Click the Add project button

Next, give a name for your web application that helps you quickly identify what the application is for. Choose a descriptive name, especially if you have multiple applications running on Firebase or Google Cloud Platform.

Firebase name your project screenshot
Name your project

Click “Continue” below the name.

Firebase Google Analytics for your Firebase project screenshot
Google Analytics for your Firebase project

The next page will link your new project with the Google Analytics platform. Firebase allows you to enable or disable Google Analytics for your project with the slider, but we recommend enabling it. Click “Continue” to move forward.

Firebase configure Google Analytics screenshot
Configure Google Analytics

On the next page, associate your Google Analytics account with this project. Choose the right account and click “Create project” to move forward.

Firebase create your project screenshot
Create your project

Your project will generate in just a few seconds. In the next step, you’ll add Firebase to your project. To do that, click the WebApp icon (</>).

Firebase Add Firebase to your app screenshot
Add Firebase to your project

Next, register a new application with your project. Enter a name that easily identifies the application and click “Register app.” You can also click the checkbox if you want to add Firebase hosting for the new application. If you aren’t ready to do that right now, you can always set up Firebase hosting later.

Firebase register your app screenshot
Register your app

Adding SDK

The next step is to add Firebase SDK to your project. You can do that with npm or the <script> tag.

Using npm

Use the following command to install Firebase SDK with npm.

npm install firebase

Then initialize Firebase and use the required functions from the SDK. Here’s an example code snippet to show you how:

import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "AUTH_DOMAIN_FQDN",
  projectId: "PROJECT_ID",
  storageBucket: "STORAGE_BUCKET_FQDN",
  messagingSenderId: "MESSAGING_SENDER_ID",
  appId: "APP_ID",
  measurementId: "MEASUREMENT_ID",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

The sky’s the limit with this option. You’re free to use any of the available Firebase libraries for your application, too.

Using <script> tag

You can also incorporate FCM in your web app by adding these scripts to the bottom of the <body> tag.

<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.9/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.9/firebase-analytics.js";

const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "AUTH_DOMAIN_FQDN",
  projectId: "PROJECT_ID",
  storageBucket: "STORAGE_BUCKET_FQDN",
  messagingSenderId: "MESSAGING_SENDER_ID",
  appId: "APP_ID",
  measurementId: "MEASUREMENT_ID",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>

Configure Web Credentials

After initializing Firebase SDK, it’s time to configure web credentials. In FCM, you do this with Voluntary Application Server Identification or VAPID keys. These tools authorize requests sent to supported web push services, like Apple Push Notification Service and browser services.

You also need to add a key pair. You can either generate a new key pair or import an existing key pair.

Once key pairs are set up, configure the web credentials in your application withgetToken(): Promise<string>, which is essential for using VAPID key credentials. Here’s an example of how to insert this into your code:

// Add the public key from the key pair generated or imported to the console.
messaging.getToken({vapidKey: "VAPID_PUBLIC_KEY"});

You can use the getToken method to access the current registration token for an application instance. The downside is that you can only retrieve an application token if the user gives permission to receive push notifications, so keep that in mind.

A firebase-messaging-sw.js file also needs to be present at the root to retrieve the device token. Use the following code snippet to retrieve a token and adjust it according to your requirements:

import { getMessaging, getToken } from "firebase/messaging";

const messaging = getMessaging();
getToken(messaging, { vapidKey: "VAPID_PUBLIC_KEY" })
  .then((currentToken) => {
    if (currentToken) {
      // Insert code to send the token to your server.
      // You can also update the UI according to the retrieved token.
    } else {
      console.log(
        "Registration token not available. Generate new one by asking for permission."
      );
      // ...
    }
  })
  .catch((err) => {
    console.log("An error occurred. ", err);
    // ...
  });

With this token, you have the power to send messages, segment users, send targeted messages, and much more.

Sending messages

Firebase Cloud Messaging screenshot
Firebase Cloud Messaging

At this point, you’ve registered the application, added SDK, and configured credentials. The final step is to create and send notifications from the FCM console.

To get started, click “Send your first message.” Give the message an optional title and message content if you want. You can also add a notification image if you want one to display on users’ screens.

Check out the right side of the console to preview how the push notification will display on an Android device. Click “Expanded view” to preview how it’ll look in an expanded state.

Once everything is to your liking, click “Next.”

Firebase notifications screenshot
Create and send notifications

If you want to send messages to specific segments or groups, provide Firebase with your targeting requirements and move on to the next screen.

Firebase targeting options screenshot
Choose targeting options

Pick a date and time to send the message. Unless you’re sending messages to local users, we recommend checking users’ time zones so you don’t send messages in the middle of the night.

Firebase schedule notifications screenshot
Schedule your notifications

On the next page, Firebase allows you to provide additional data like:

  • Android notification channel
  • Notification sound
  • Expiration

Once you set everything up, review your settings one last time and click “Publish” to send the notification.

Firebase review your message screenshot
Review your message

This sends the first push notification. However, that’s just the tip of the iceberg. Check out Firebase’s full documentation to learn more about its advanced push notification functionalities.

Best Practices for Engaging FCM Push Notifications

Smartphone user receiving push notifications

Firebase Cloud Messaging makes it a cinch to send personalized push notifications to subscribers. However, there’s a lot going on here, so it’s important to optimize your FCM campaigns to get the most engagement from subscribers. Follow these best practices to run better campaigns, save time, and boost subscriber engagement.

Always Obtain User Permission

Never add a user to your push notification list without their permission. It’s against the law to message users without permission, so always gather consent first. Most sites do this with pop-ups asking for browser permissions. This is effective, but don’t bother users with a pop-up as soon as they visit your application. Add a timer so they see it after perusing your site for a while.

It’s also a good idea to link to your privacy and data use policies in the pop-up request. This way, users can get more information about what, exactly, they’re signing up for.

As with any messaging campaign, always give users an easy way to unsubscribe from push notifications. This is a requirement both legally and for a solid user experience.

Use Interactive Elements and Rich Media

In this guide, we showed you how to set up text notifications in Firebase. However, the platform also gives you the ability to upload multimedia messages to save time and boost engagement. Not only does rich media get users’ attention, but it also encourages them to engage with your app.

Experiment by adding images, videos, custom sounds, or action buttons to your push notifications. Just check your platform’s requirements first. All push notification media should meet size and format requirements to give users the best possible experience.

Speed Up Implementation With Foreground and Background Message Handling

FCM seriously speeds up the implementation process for developers, but foreground and background message handling will also give you a speed boost. Message handling matters because it ensures users receive push notifications regardless of the app’s current state. Setting up handling rules ensures users get a consistent experience, whether the app is in the foreground or background.

For background handling:

  • Set up a service worker. This script runs in the background and sends push notifications even when the web app is in the background. You’ll need to register this service worker with your app to use it with FCM.
  • Go to your service worker file, import the Firebase scripts, and initialize Firebase. Use the “setBackgroundMessageHandler” method to receive and handle background messages.
  • Optionally, customize how notifications display.
  • Cache app resources for offline use.

For foreground handling:

  • Use state management. React options like useState or Redux help you handle incoming messages differently, since you don’t need to display notifications the same way when an app is in the foreground.
  • Test the interface. If the user is actively on your web app, make sure the interface updates to reflect the notification. For example, maybe it updates the app’s notification icon with every incoming message.

Background and foreground handling are great tools for improving the user experience, but they have to fire flawlessly. Test everything multiple times to ensure it’s operating correctly.

Explore More Advanced Features

This guide scratches the surface of what’s possible with Firebase Cloud Messaging. If you really want to get value from this tool, try more advanced features like:

  • Topic subscriptions: This feature allows users to subscribe to notifications only for topics or content that interest them. It’s perfect for sending targeted content that users want to see. Of course, it means you need to offer multiple content categories to justify the setup. Set this up with Firebase’s “subscribeToTopic’ and “unsubscribeFromTopic” methods.
  • Group messaging: Most push notifications go out to an entire list or segment. But with group messaging, you can message multiple users at once based on past behavior, location, and more. That’s much more efficient than sending individual messages, especially if you’re sending general updates. Firebase supports this out of the box, but make sure you give each user group a descriptive name so it’s easy to message them by segment.
  • Custom content: The more personalized push notifications are to a user’s interests and history, the more likely they are to interact with your web app. Use analytics and user data to create custom-tailored, dynamic notification content. A/B testing is helpful to see which formats, content, or topics users respond to.

Effective FCM Notifications in the Wild

Firebase offers a lot of firepower for brands. It’s something that MagicBell client Superchat discovered while implementing notifications for its users. Firebase made it a cinch to overhaul the notification program, but Superchat soon had a problem on its hands.

The platform sent both push notifications and emails to users, overwhelming them with a mountain of additional messages. Although Superchat built the foundation with Firebase, they ultimately added MagicBell to launch cross-channel notifications with ease. Today, Superchat sends contextually-relevant, customized notifications to their users without breaking a sweat.

Go Beyond FCM With MagicBell

Push notifications are a seamless way to connect with users across iOS apps, Android apps, and web applications. Firebase Cloud Messaging and its ancillary services make life easier for developers because they support free, targeted messages that increase engagement.

As effective as Firebase is for getting started, it doesn’t help developers deal with notification overwhelm. Fortunately, it’s not the only option. That’s where MagicBell comes in.

MagicBell creates a space within your application that collates all push notifications the user receives, making it possible for users to access all past messages—even after they expire.

MagicBell’s notification inbox is a nifty tool that lets you integrate a notification inbox into your application in less than an hour. Better serve your users with a plug-and-play solution that works: Create your free MagicBell account now.  

Frequently Asked Questions

Can Firebase Cloud Messaging (FCM) handle large-scale applications with millions of users?

Yes. Thanks to its integration with the Google Cloud Platform, FCM can efficiently manage and deliver notifications to millions of users simultaneously.

Is it possible to track the open rate of notifications sent through Firebase?

Yes. Firebase integrates with Google Analytics, which allows you to track various metrics, including push notification open rates.

How does Firebase handle user privacy and data security?

As a brand, you’re ultimately responsible for user safety and data security. However, Firebase does offer security features, like end-to-end encryption. It’s also GDPR compliant.