Sign up

app push notifications

How to Use Firebase to Send Push Notifications

Angela Stringfellow

Last updated on

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

One challenge developers face while implementing push notifications is the fragmentation of the platforms on which users are present. Users could be using different mobile operating systems, desktop operating systems, and browsers. This makes coding and developing push notification systems for all the different platforms a challenging task.

Many service providers combine the push notification requirements for an application into a single platform. This way developers can build their application and the notification integrator will do the work of sending the notifications on different platforms. One such notification integrator is Firebase Cloud Messaging (FCM).

A Quick Primer on Firebase Cloud Messaging

FCM is a service under Firebase, an integral component of Google Cloud Platform (GCP). Firebase helps developers build and deploy applications quickly. The main aim of Firebase is to reduce the amount of coding required to build and deliver an application, and FCM aligns with this purpose.  

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 can use FCM to build messaging solutions for their applications. This includes push notifications to various platforms. FCM natively supports:

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

With this multiplatform support from FCM, developers are not required to build notification systems from the ground up for each of these platforms, saving the development team a lot of time. Plus, the codebase for applications also becomes much simpler and easier to read. FCM therefore acts as a powerful intermediary to integrate and implement push notifications to applications across the 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 and marketing teams.

Why FCM?

There are multiple platforms that developers can rely on to send push notifications, and FCM is one of the most popular. This is thanks to the extensive support and features that FCM makes available to its users. Let’s review some of the features that make FCM the most sought after notification platform today.

Integration

One of the key features FCM offers is the wide range of integrations the service provides. First, it supports push notifications to the multiple platforms mentioned earlier, but the integrations possible with FCM go much deeper. For example, it’s very easy to integrate FCM with your other services hosted on the Google Cloud Platform. This makes the management of services easy as the management and analytics for the services can happen on the same platform.

FCM also has simple integrations with Google Ads, Google Analytics, and Google AdMob. In addition to that, FCM also has no trouble integrating with other cloud service providers. To name but a few, AWS, Microsoft, and Linode all work seamlessly with FCM. This makes work easier and simpler for developers.

Analytics

FCM integrates seamlessly with Google Analytics, one of the most popular web analytics platforms on the planet. This powerful free service can be used by the development and marketing teams of your organization to understand how users interact with the push notifications you send.

This information can then be used to design and implement a better push notification strategy in line with the aims of your organization. Google Analytics lets you segment users to gain granular information on how users interact with your applications. It also seamlessly integrates with BigQuery, the data warehousing solution that is part of Google’s Cloud Platform.

Versatile Targeting

FCM lets you create any number of segments for users. This way you can cluster users who exhibit similar characteristics. Different push notification messages can then be sent to different clusters of users, allowing you to target each user with a message that resonates well with each group of customers. This helps to build and improve both app and brand engagement.

A/B Testing

To test the strategies implemented as a result of the Analytics data, you need A/B testing. FCM natively supports A/B testing, which is powered by Google Optimize. This tool offers a simple and intuitive platform to run tests, including product and marketing experiments.

In-App Messaging

Contextual messages are powerful tools to engage customers. FCM can also send targeted contextual messages through in-app messaging. These relevant messages sent to active users can increase in-app engagement and can also be used to drive sales and improve the user experience.

Push Notifications with Firebase

As mentioned before, FCM supports push notifications for multiple platforms. We have covered some of those in previous articles:

In this article, we’ll take a look at how to implement push notifications for your web application with FCM.

Registering Application

You can create and send notifications to web applications directly from the Firebase console. First, go to the Firebase console at https://console.firebase.google.com/.

Click on the Add project button on the console.

Firebase Add project button screenshot
Click the Add project button

On the page that pops up give a name for your web application. This name should help to easily identify the application. This will be handy if you have multiple applications running on Firebase or Google Cloud Platform.

Firebase name your project screenshot
Name your project

Click on the Continue button below the name.

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

The next page is to link your new project with Google Analytics platform. You can enable or disable Google Analytics for your project with the slider. It is recommended that you enable this option. Click on the Continue button to move forward.

Firebase configure Google Analytics screenshot
Configure Google Analytics

On the next page you’ll need to link the Google Analytics account you want to be associated with this project. Choose the right account and click on the Create project button to move forward.

Firebase create your project screenshot
Create your project

The new project will be created in a few seconds. Click on the Continue button to move forward to the project console.

The next step is to add Firebase to your project. For that, click on the WebApp icon (</>) on the console.

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

Next, you’ll need to register a new application with your project. Enter a name that can help you easily identify the application and click on the Register app button. You can also choose to add Firebase hosting for the new application by simply clicking the checkbox next to the relevant text. Alternatively, you can always set up Firebase hosting at a later stage.

Firebase register your app screenshot
Register your app

Adding SDK

The next step is to add Firebase SDK to your project. This can be done by using npm or by using 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. A representative example is given in the code snippet below.


```
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);
``` 

You can use any of the available Firebase libraries for your application. You can check out the available Firebase services at this link.

Using <script> tag

You can add these scripts to the bottom of your <body> tag to incorporate FCM with your WebApp.

```
<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

Once you have initialized Firebase SDK, you need to configure web credentials. In FCM, this is done using Voluntary Application Server Identification or VAPID keys. They help to authorize requests sent to supported web push services such as 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 you need to configure the Web credentials in your application.  ```getToken(): Promise<string>``` is used for utilizing VAPID key credentials. This is required to send requests to different push services. This can be inserted in the code as shown below.

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

The method ```getToken``` can be used when you need to access the current registration token for an instance of the application. The registration token can be retrieved only if the user has given permission to receive push notifications. A ```firebase-messaging-sw.js``` file has 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 specific 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);
// ...
});
```

You can use this token to send messages, segment users, send targeted messages to users, and perform many other actions.

Sending messages

Firebase Cloud Messaging screenshot
Firebase Cloud Messaging

You can create and send notifications in the FCM console. To get started, click on the ‘Send your first message’ button. In the screen that appears, enter an optional title and the message content. You can also add a notification image to be displayed on the notification screen. On the right side of the console, you can see the preview of how it appears on the Android device. You can also preview how it will appear in the expanded state by clicking the tab ‘Expanded view.’ Once everything is in order, click the ‘Next’ button.

Firebase notifications screenshot
Create and send notifications

You can then provide the various targeting options on the next screen before clicking the ‘Next’ button.

Firebase targeting options screenshot
Choose targeting options

The next screen is for scheduling the date and time. You also have the option to switch between various timezones.

Firebase schedule notifications screenshot
Schedule your notifications

You can provide additional data such as the Android notification channel, Notification sound, and expiry on the next page. Once everything is set up, review the settings and click the ‘Publish’ button to send the notification.

Firebase review your message screenshot
Review your message

This sends the first push notification. There are many push notification functionalities in Firebase and these functionalities are explained in detail in the Firebase documentation.

Next Steps…

Push notifications are a seamless way to connect with your users across different platforms, such as iOS apps, Android apps, and web applications. Firebase cloud messaging and its ancillary services make life easier for developers and marketers alike as FCM enables users to send free, targeted messages to increase engagement. The next step for you is to create a space within your application to collate all the push messages your user receives.

This way users will be able to access all the past messages even after they expire. MagicBell’s notification inbox is a nifty tool that lets you integrate a notification inbox to your application in less than an hour. Users will then be able to create custom notification preferences and, in turn, you’ll be able to better serve your users.

Featured Blogposts

Related Blogposts