Keep Reading
If you enjoyed the post you just read, we have more to say!
Last updated on
Developing mobile and web applications from scratch is an arduous process. Fortunately, developers no longer need to build applications from square one, thanks to open-source packages and code functionalities. Cloud service providers also have platforms that make it easy to quickly create and host applications for web, iOS, and Android apps.
In-app functionality is important, but web app notifications are crucial for returning users to your app. Push notifications typically require a lot of development resources, but open-source tools make it much more manageable.
Firebase is one of the best tools for creating React Native push notifications. In this guide, we’ll explain why Firebase is such a powerful tool for developers and share the step-by-step process of quickly creating push notifications with Firebase.
In this article:
Firebase is a Google application development platform. It offers a host of built-in, integration-ready features and functionalities, allowing developers to create application backends quickly.
Firebase comes with several features for:
Think of Firebase as a suite of tools for expanding your user base, adding more functionalities, and increasing retention. Firebase is one of the top six platforms in terms of market share, with over 42,000 documented customers and a 2.05% market share.
Firebase supports over three million apps with helpful features like:
Most Firebase features work in real-time, giving you up-to-the-moment information on user behavior, errors, and overall app performance. Plus, it supports both iOS and Android devices, so you don’t have to use multiple tools or platforms to send push notifications.
Without Firebase, developers would have to spend countless hours building apps. Opting for a solution like Firebase allows you to scale to handle a large number of apps, users, and loads without performance issues.
Messaging and notification features enhance app user engagement. If you’re trying to build a reliable notification service to implement push notifications without hassle, go with Firebase.
Developers use Firebase for many things. For example, the Firebase SDK is great for authentication, while the Firebase Firestore is used over the Realtime Database.
Firebase has loads of features, but Firebase Cloud Messaging (FCM) is especially helpful for developers implementing React Native push notifications. With FCM, developers can implement simultaneously across multiple platforms.
It supports iOS, Android, web, Unity, and C++ setups. Developers use Firebase to manually trigger messages with CRON jobs or user interaction using cloud functions for remote push notifications.
FCM can also:
Of course, you still need the proper setup and knowledge to leverage FCM. To send a message using FCM, you need two things:
As long as you have these two things, it’s easy to set up local, remote, test, and native push notifications. This setup is much easier than managing push notifications without a programming platform, saving your team a lot of time.
React Native is a library maintained by Facebook that developers use to build front-end applications across different platforms. You can combine React Native with Firebase’s back-end-as-a-service solution to create React Native Firebase. This is a combination tool for building cross-platform applications in just a few steps—and less hassle.
Follow these steps to integrate push notifications in React applications using FCM.
Go to the Firebase console and create a new project. Follow the prompts and modify them according to your needs. You can initiate a new Firebase project with three simple steps.
Go to the Firebase console and create a new project. Follow the prompts and modify them according to your needs. You can initiate a new Firebase project with three simple steps.
Log into Firebase and click "Create a project."
Choose a name for your project, accept the Firebase terms, and click "Continue."
In the second step, you can choose to enable or disable Google Analytics for the project.
The final step is to select a Google Analytics account, link it with the project, select your settings, and accept the terms. Then, click "Create project."
Create a new React Native app according to the React documentation.
$ react-native init pushNotifExample
You can run the Android application with the following code snippet:
$ react-native run-android
You can use multiple packages to add push notification dependency to your React application. react-native-firebase is a popular package that can add all Firebase functionalities to React applications.
Here, we're using the react-native-push-notification package, which only deals with the push notification functionality. You can get the package using Node Package Manager (npm) or Yarn with the following snippet (from GitHub).
For npm:
$ npm install --save react-native-push-notification
For yarn:
yarn add react-native-push-notification
Register your Android or iOS application in the Firebase dashboard. In this example, we'll implement push notifications for Android apps.
Register the Android application and give it a name.
Download the google-services.json file and place it in the root directory of your application module.
Use the following code from the Firebase documentation for the project-level build.gradle (<project>/build.gradle):
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
classpath 'com.google.gms:google-services:4.3.8'
}
}
allprojects {
...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
...
}
}
Next, create the application level build.gradle (<project>/<app-module>/build.gradle) with this code snippet from the Firebase documentation:
apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'
dependencies {
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:28.2.1')
// Add the dependencies for the desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}
Add the following code to AndroidManifest.xml (from GitHub):
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="${applicationId}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application .......>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name"
android:value="YOUR NOTIFICATION CHANNEL NAME"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description"
android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="@android:color/white"/>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
... </application>
Sync the code.
Use the following code (from GitHub) to call PushNotification.configure at the start of the app. It needs to be in a separate JS file and imported to App.js.
import React, {Component} from "react";
import PushNotification from "react-native-push-notification";
// var PushNotification = require("react-native-push-notification");
export default class PushController extends Component{
componentDidMount(){
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log("TOKEN:", token);
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
// process the notification here
// required on iOS only
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// Android only
senderID: "1090501687137",
// iOS only
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true
});
}
render(){
return null;
}
}
The content of the App.js file should look like this:
import React, { Fragment } from 'react';
import PushController from './PushController';
import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, FlatList} from 'react-native';
import {Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions } from 'react-native/Libraries/NewAppScreen';
// Dummy data for list, we'll replace this with data received from push
let pushData = [
{
title: "First push",
message: "First push message"
},
{
title: "Second push",
message: "Second push message"
}
]
_renderItem = ({ item }) => (
<View key={item.title}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.message}>{item.message}</Text>
</View>
);
const App = () => {
return (
<Fragment>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Header />
<View style={styles.listHeader}>
<Text>Push Notifications</Text>
</View>
<View style={styles.body}>
<FlatList
data={pushData}
renderItem={(item ) => this._renderItem(item)}
keyExtractor={(item ) => item.title}
/>
{/* <LearnMoreLinks /> */}
</View>
</ScrollView>
</SafeAreaView>
<PushController/>
</Fragment>
);
};
const styles = StyleSheet.create({
scrollView: {backgroundColor: Colors.lighter,},
listHeader:{ backgroundColor: '#eee', color: "#222", height: 44, padding: 12},
title:{fontSize: 18, fontWeight: 'bold', paddingTop: 10},
message:{ fontSize: 14, paddingBottom: 15, borderBottomColor: "#ccc", borderBottomWidth: 1},
engine: { position: 'absolute', right: 0,},
body: { backgroundColor: Colors.white, paddingHorizontal: 20, paddingVertical: 10, },
sectionContainer: { marginTop: 32, paddingHorizontal: 24, },
sectionTitle: { fontSize: 24, fontWeight: '600', color: Colors.black},
sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', color: Colors.dark,},
highlight: { fontWeight: '700'},
footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right',},
});
export default App;
import React, { Fragment } from 'react';
import PushController from './PushController';
import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, FlatList} from 'react-native';
import {Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions } from 'react-native/Libraries/NewAppScreen';
// Dummy data for list, we'll replace this with data received from push
let pushData = [
{
title: "First push",
message: "First push message"
},
{
title: "Second push",
message: "Second push message"
}
]
_renderItem = ({ item }) => (
<View key={item.title}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.message}>{item.message}</Text>
</View>
);
const App = () => {
return (
<Fragment>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Header />
<View style={styles.listHeader}>
<Text>Push Notifications</Text>
</View>
<View style={styles.body}>
<FlatList
data={pushData}
renderItem={(item ) => this._renderItem(item)}
keyExtractor={(item ) => item.title}
/>
{/* <LearnMoreLinks /> */}
</View>
</ScrollView>
</SafeAreaView>
<PushController/>
</Fragment>
);
};
const styles = StyleSheet.create({
scrollView: {backgroundColor: Colors.lighter,},
listHeader:{ backgroundColor: '#eee', color: "#222", height: 44, padding: 12},
title:{fontSize: 18, fontWeight: 'bold', paddingTop: 10},
message:{ fontSize: 14, paddingBottom: 15, borderBottomColor: "#ccc", borderBottomWidth: 1},
engine: { position: 'absolute', right: 0,},
body: { backgroundColor: Colors.white, paddingHorizontal: 20, paddingVertical: 10, },
sectionContainer: { marginTop: 32, paddingHorizontal: 24, },
sectionTitle: { fontSize: 24, fontWeight: '600', color: Colors.black},
sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', color: Colors.dark,},
highlight: { fontWeight: '700'},
footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right',},
});
export default App;
You can access the Sender ID and other authentication details under the Cloud Messaging section in your project settings.
Run your Android application with the following code snippet:
$ react-native run-android
Go to the FCM dashboard to start sending push notifications. You can find this in Engage>Cloud Messaging.
Follow the prompts to compose and select targets for the push notification.
Select the targets you need.
You can send the message now or schedule it for another time.
You can modify additional options based on your requirements, if needed.
Once you’re done, click “Review.” Click “Publish” in the popup to send messages based on your settings.
The system will send the push notifications based on the schedule you provided and your target criteria.
You’ve laid the foundation for sending push notifications, but users have a say in whether they receive them.
iOS takes user permissions seriously. You have to explicitly request permission from the user to receive push notifications. This applies to native and progressive web apps (PWAs).
This is typically done when the app first launches or the user performs an action requiring notifications. Use this Swift code to create the notification request message:
// Request notification permissions
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
// User granted permission, register for remote notifications
RegistrationServices.shared.registerForRemoteNotifications()
} else {
// User denied permission
}
}
This code requests permission to display alerts, play sounds, and update the app badge. If the user grants permission, you can register for remote notifications. You only get one chance to request permission, so explaining the value of notifications to the user before making the request is important.
Fortunately, you have a little more leeway with Android devices. Starting with Android 13, you must explicitly request the POST_NOTIFICATIONS runtime permission to display notifications. This can be done using the EssentialPermissions plugin in .NET MAUI:
// Request notification permission
var permissionStatus = await Permissions.RequestAsync<Permissions.Notification>();
if (permissionStatus == PermissionStatus.Granted)
{
// User granted permission
}
else
{
// User denied permission
}
This process gives you two chances to request permission before the user is permanently denied. Previously, you didn’t need to request notifications for devices running Android 12 and lower. However, today, devices running Android 13 and higher also require explicit permission.
It’s a best practice to test push notifications once you set them up. This ensures the notifications send at the right time and display correctly across all devices.
To test your setup:
While in-house testing is important, don’t discount the value of user feedback and crash reports. This will help you identify any issues that your team missed during testing.
You can also test your push notifications using our TestFCM tool. If you’re creating web push notifications, test them out at webpushtest.com, which demos standards based web push notifications across all platforms, including iOS.
Even if you set up React Native push notifications correctly, there’s always room for improvement. Follow these performance and optimization best practices to continually improve your development processes and the user experience.
Will your app send lots of notifications? That can add up to performance issues at scale. Follow these tips to handle notifications more efficiently:
Push notifications are a smart way to increase user adoption, but they can also be annoying or intrusive. The key is to deliver valuable information without overwhelming users. You can boost engagement by:
Tracking push notification performance will help you understand user engagement and improve future campaigns. Integrating Firebase with Google Analytics is an easy way to gather this data, although you’ll need to regularly log into Google Analytics to assess notification performance.
Follow these tips to make the most of your performance data:
Most push notifications overlook accessibility, severely limiting the experience of users with disabilities. Follow these best practices to make your push notifications as accessible as possible:
Like any technology, both Firebase and the React Native platform will change over time. It’s crucial for businesses and developers to keep on top of these developments to create the most streamlined push notifications possible:
Implementing push notifications is simple, thanks in large part to solutions like React Native and Firebase. Regardless of how you implement push notifications, they’re a powerful tool for engaging users.
For example, STACKSI needed a sophisticated in-platform notification system to facilitate real-time, asynchronous collaboration and ensure an efficient, user-friendly workflow. They turned to MagicBell for its affordability, immediate integration, and customization features, enabling them to provide more specific notifications and helpful information within notifications when needed.
Luminovo also switched to push notifications for its software-as-a-service (SaaS) business. They use the backend admin board to compose custom notifications without complex coding or logic, saving time while giving customers a better experience.
After implementing push notifications, engage users by giving them an option to access their notifications in an inbox. An inbox gives users a safe place to store and access their messages at any time.
It also reduces the need for repeat notifications, which have the potential to hurt the user experience. Whether it’s an Android or an iOS device, the research shows that users want to re-engage with their notifications whenever it suits them.
There’s no need to write custom code for this, either. Use MagicBell to implement customized inbox functionality in your application in a few minutes. We use API and UI components for multi-channel, real-time delivery across apps, emails, Slack, mobile, web, and more.
Build your user inbox for free: Create a MagicBell account now.
Yes. Reactive Native provides ready-made tools and libraries to integrate push notifications for both iOS and Android devices.
Use libraries like react-native-push-notification to schedule and display local notifications. Install the library, configure it to your React Native project, and use the library’s API to schedule and manage all local notifications.
React Native supports two types of notifications:
Firebase is one of the easiest ways to implement push notifications, but it isn’t your only option. You can use other backend services like MagicBell or make your own server. Once you choose a service, you’ll need to integrate with that service’s SDK or API and configure your React Native app to manage push notifications.