How to Add Firebase Push Notification

How to Add Firebase Push Notification Firebase Push Notification is a powerful, scalable solution for delivering timely, targeted messages to users across web and mobile platforms. Developed by Google as part of the Firebase platform, it enables developers to send real-time notifications to users even when the app is in the background or closed. This capability is essential for modern digital expe

Nov 10, 2025 - 08:57
Nov 10, 2025 - 08:57
 1

How to Add Firebase Push Notification

Firebase Push Notification is a powerful, scalable solution for delivering timely, targeted messages to users across web and mobile platforms. Developed by Google as part of the Firebase platform, it enables developers to send real-time notifications to users even when the app is in the background or closed. This capability is essential for modern digital experienceswhether you're running an e-commerce app, a news portal, a social platform, or a productivity tool. Push notifications significantly boost user engagement, retention, and conversion rates by delivering personalized content directly to the users device.

Unlike traditional email or in-app messaging, Firebase Cloud Messaging (FCM)the underlying service for push notificationsoperates at the operating system level, ensuring high delivery rates and low battery consumption. With FCM, you can send notifications based on user behavior, location, device type, or custom audience segments. The service integrates seamlessly with Firebase Analytics, allowing you to track notification performance and optimize campaigns based on real-time data.

Adding Firebase Push Notification to your application is not just a technical taskits a strategic decision that enhances user experience and drives measurable business outcomes. Whether youre building a native Android or iOS app, a progressive web app (PWA), or a cross-platform solution using React Native or Flutter, Firebase provides standardized, documented, and reliable tools to implement push notifications efficiently.

This comprehensive guide walks you through every step of integrating Firebase Push Notification into your application. From initial setup to advanced configuration, best practices, real-world examples, and troubleshooting, youll gain the knowledge needed to deploy a robust, scalable notification system that keeps users informed, engaged, and coming back.

Step-by-Step Guide

1. Create a Firebase Project

To begin integrating Firebase Push Notification, you must first create a Firebase project. Navigate to the Firebase Console and click Add Project. Provide a unique project name and select or create a Google Cloud organization if prompted. Disable Google Analytics for this project if you plan to use a separate analytics tool, or enable it to gain deeper insights into notification performance later.

Once the project is created, youll be redirected to the project overview dashboard. This is your central hub for managing all Firebase services, including Cloud Messaging, Authentication, Analytics, and more. Click on the gear icon in the top-left corner and select Project Settings. Under the Your apps section, click Add app and choose the platform youre developing forAndroid, iOS, or Web.

2. Register Your App with Firebase

For Android apps, enter your package name (found in your apps build.gradle file under applicationId). For iOS apps, input your bundle identifier (visible in Xcode under the project settings). For web applications, provide a descriptive name and optionally enable the Firebase Hosting service.

Firebase will generate a configuration file specific to your platform:

  • Android: google-services.json
  • iOS: GoogleService-Info.plist
  • Web: A JavaScript configuration object

Download the appropriate file and place it in your project directory. For Android, move google-services.json into the app/ folder. For iOS, drag GoogleService-Info.plist into your Xcode project root using the file navigator, ensuring Copy items if needed is checked. For web, keep the configuration snippet handy for later use.

3. Configure Firebase SDK in Your Project

Next, integrate the Firebase SDK into your application. For Android, open your project-level build.gradle file and add the Google Services plugin:

classpath 'com.google.gms:google-services:4.3.15'

Then, in your app-level build.gradle, apply the plugin and add the FCM dependency:

apply plugin: 'com.google.gms.google-services'

dependencies {

implementation 'com.google.firebase:firebase-messaging:23.6.0'

}

For iOS, use CocoaPods to install Firebase. In your projects root directory, create or edit the Podfile:

platform :ios, '12.0'

use_frameworks!

target 'YourAppTarget' do

pod 'Firebase/Messaging'

end

Run pod install in your terminal and open the generated .xcworkspace file in Xcode.

For web applications, include Firebase in your HTML file via CDN or install via npm:

npm install firebase

Then initialize Firebase in your JavaScript file:

import { initializeApp } from "firebase/app";

import { getMessaging } from "firebase/messaging";

const firebaseConfig = {

apiKey: "YOUR_API_KEY",

authDomain: "your-project.firebaseapp.com",

projectId: "your-project",

storageBucket: "your-project.appspot.com",

messagingSenderId: "YOUR_SENDER_ID",

appId: "YOUR_APP_ID"

};

const app = initializeApp(firebaseConfig);

const messaging = getMessaging(app);

4. Request Notification Permission

Before sending notifications, you must obtain explicit user consent. On Android, this is handled automatically if the app targets API level 33 or higher. For older versions, you may need to declare the POST_NOTIFICATIONS permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

On iOS, you must request authorization in your app delegate or SwiftUI view:

import UserNotifications

import Firebase

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in

if granted {

print("Notification permission granted")

}

}

For web browsers, use the requestPermission() method:

Notification.requestPermission().then(function(permission) {

if (permission === "granted") {

console.log("Notification permission granted");

}

});

Always handle permission denials gracefully. Provide an in-app explanation or settings button to guide users on how to re-enable notifications manually.

5. Retrieve the FCM Registration Token

Each device that receives notifications is assigned a unique registration token by Firebase. This token is required to send targeted messages to that specific device. Retrieve it using the FCM SDK.

On Android, create a service that extends FirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override

public void onNewToken(String token) {

Log.d("FCM", "Refreshed token: " + token);

// Send token to your server

sendTokenToServer(token);

}

private void sendTokenToServer(String token) {

// Implement HTTP POST to your backend

}

}

Declare the service in your AndroidManifest.xml:

<service

android:name=".MyFirebaseMessagingService"

android:exported="false">

<intent-filter>

<action android:name="com.google.firebase.MESSAGING_EVENT" />

</intent-filter>

</service>

On iOS, implement the UNUserNotificationCenterDelegate and FIRMessagingDelegate protocols:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

FirebaseApp.configure()

Messaging.messaging().delegate = self

UNUserNotificationCenter.current().delegate = self

return true

}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {

print("FCM registration token: \(fcmToken ?? "")")

// Send token to your server

}

For web, listen for token refresh events:

messaging.onTokenRefresh(() => {

messaging.getToken().then((currentToken) => {

if (currentToken) {

sendTokenToServer(currentToken);

} else {

console.log('No registration token available. Request permission.');

}

}).catch((err) => {

console.log('An error occurred while retrieving token. ', err);

});

});

Store the token securely on your backend server, associating it with the users account ID. This allows you to send personalized messages to individual users later.

6. Handle Incoming Notifications

When a notification is received, Firebase provides two types: notification messages (handled by the system) and data messages (handled by your app). For maximum control, use data messages.

On Android, override onMessageReceived() in your FirebaseMessagingService:

@Override

public void onMessageReceived(RemoteMessage remoteMessage) {

super.onMessageReceived(remoteMessage);

if (remoteMessage.getData().size() > 0) {

String title = remoteMessage.getData().get("title");

String body = remoteMessage.getData().get("body");

sendNotification(title, body);

}

}

private void sendNotification(String title, String body) {

Intent intent = new Intent(this, MainActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "default")

.setSmallIcon(R.drawable.ic_notification)

.setContentTitle(title)

.setContentText(body)

.setAutoCancel(true)

.setContentIntent(pendingIntent);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0, notificationBuilder.build());

}

On iOS, implement the userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: method in your delegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

let userInfo = response.notification.request.content.userInfo

if let title = userInfo["title"] as? String, let body = userInfo["body"] as? String {

print("Received notification: \(title) - \(body)")

}

completionHandler()

}

For web, use the onMessage() listener:

messaging.onMessage((payload) => {

console.log("Message received: ", payload);

const title = payload.notification?.title || "New Notification";

const options = {

body: payload.notification?.body || "",

icon: payload.notification?.icon || "/icon.png"

};

new Notification(title, options);

});

7. Send Your First Notification

Now that your app is configured, test the setup using the Firebase Console. In the Firebase Console, navigate to Cloud Messaging under the Engage section. Click Create Message.

Select your targeteither a single device (using the token you captured earlier), a topic, or an audience segment. Enter a title and message body. Optionally, add a deep link, image, or custom data payload. Click Review and then Send.

If everything is configured correctly, the notification should appear on your device within seconds. If not, check the Firebase Console logs for errors and verify your token is correctly stored and formatted.

8. Test Across Platforms and Devices

Always test your implementation on multiple devices and OS versions. Android 10+ and iOS 14+ have stricter notification policies. Test on physical devicesnot just emulatorsas background behavior can differ significantly.

For web, test on Chrome, Firefox, Safari, and Edge. Safari requires a website certificate and a valid manifest file for push notifications to work reliably.

Use Firebases built-in analytics to monitor delivery rates, open rates, and click-through rates. Correlate notification sends with user behavior in your app to refine timing and content.

Best Practices

Respect User Privacy and Preferences

Never bombard users with notifications. Overuse leads to notification fatigue, app uninstalls, and permission revocations. Implement opt-in mechanisms that explain the value of notificationssuch as Get instant alerts for order updates or Be the first to know about new features.

Provide users with granular control over notification types. Allow them to toggle categories like promotions, alerts, or newsletters independently. Store these preferences on your backend and use them to filter messages before sending.

Use Data Messages for Full Control

While Firebase allows sending notification messages (handled by the OS), these are less flexible. Use data messages instead. They give you full control over how and when the notification is displayed, allowing you to customize the UI, play sounds, or trigger app logic even when the app is closed.

Data messages also work reliably in background and terminated states on iOS, where system notifications may be delayed or suppressed.

Personalize Content Using User Data

Combine FCM with Firebase Analytics to segment users based on behavior. For example, send a cart abandonment message to users who viewed a product but didnt purchase. Use custom parameters like user_id, last_purchase, or preferred_category to tailor messaging.

Dynamic contentsuch as personalized product recommendations or location-based offerscan increase conversion rates by up to 50% compared to generic blasts.

Optimize Delivery Timing

Schedule notifications based on user activity patterns. If your analytics show users are most active between 79 PM, avoid sending messages at 3 AM. Use Firebases scheduling feature to deliver messages at optimal times.

For global audiences, use time zone-aware delivery. Firebase supports sending notifications based on the users device time zone, eliminating confusion caused by mismatched time settings.

Implement Retry Logic and Error Handling

Not all tokens remain valid. Users may uninstall your app, reset their device, or clear app data. Firebase returns a NotRegistered error when a token becomes invalid. Implement a server-side cleanup routine that removes invalid tokens from your database.

Use exponential backoff when retrying failed deliveries. Avoid overwhelming Firebases API with rapid retries. Most errors are transient and resolve with a single retry after a delay.

Minimize Payload Size

Firebase limits notification payloads to 4KB for data messages. Keep your payloads lean. Avoid embedding large images or JSON blobs. Instead, send a lightweight payload with a reference ID (e.g., product_id: 12345) and fetch the full content from your server when the user opens the notification.

Enable Silent Notifications for Background Sync

Silent notifications (with content_available: true in web or content-available: 1 in iOS) allow your app to wake up in the background without showing a visible alert. Use these to sync data, update content, or pre-load resourcesimproving perceived performance without interrupting the user.

Test with Real Devices and Network Conditions

Emulators often behave differently from real devices, especially regarding background execution and battery optimization. Test on multiple Android OEM devices (Samsung, Xiaomi, Huawei) and iOS models. Use network throttling tools to simulate poor connectivity and ensure your app handles timeouts gracefully.

Tools and Resources

Firebase Console

The primary interface for managing notifications. Offers real-time analytics, message scheduling, audience segmentation, and A/B testing. Accessible at console.firebase.google.com.

Postman or cURL for API Testing

When building custom notification servers, use Postman or cURL to send raw HTTP POST requests to Firebases v1 API endpoint:

POST https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send

Include an OAuth 2.0 access token in the Authorization header and a properly formatted JSON payload.

Firebase Admin SDK

For server-side logic, use the Firebase Admin SDK (available for Node.js, Python, Java, Go, and .NET). It allows you to send notifications programmatically, manage device tokens, and access analytics data.

Example (Node.js):

const admin = require('firebase-admin');

admin.initializeApp();

const message = {

token: 'DEVICE_TOKEN',

notification: {

title: 'Hello',

body: 'This is a test message'

}

};

admin.messaging().send(message)

.then((response) => {

console.log('Successfully sent message:', response);

})

.catch((error) => {

console.log('Error sending message:', error);

});

Notification Design Tools

Use tools like Figma or Adobe XD to design notification templates before implementation. Consider icon sizes, text length limits, and platform-specific guidelines (e.g., iOS caps notification title at 40 characters).

Third-Party Integrations

Integrate FCM with marketing automation platforms like Braze, Iterable, or OneSignal for advanced segmentation, automation workflows, and cross-channel campaigns. These tools often provide visual editors and predictive analytics to enhance notification effectiveness.

Documentation and Support

Official Firebase documentation is comprehensive and regularly updated:

GitHub repositories with sample code are available for all platforms. Search for Firebase Cloud Messaging sample on GitHub to find open-source implementations.

Real Examples

Example 1: E-Commerce App Cart Abandonment

An online retailer uses Firebase to detect when a user adds items to their cart but doesnt complete checkout. Using Firebase Analytics, they create an audience of users who viewed products but didnt purchase in the last 24 hours.

A data message is sent with payload:

{

"title": "Your cart is waiting!",

"body": "Complete your purchase now and get 10% off!",

"action": "open_cart",

"discount_code": "CART10"

}

When the user taps the notification, the app opens directly to their cart with the discount applied. This campaign increased conversion rates by 22% within two weeks.

Example 2: News Portal Breaking News Alerts

A news organization uses topics to segment users by interest: sports, politics, tech. When a breaking story is published, they send a notification to all subscribed topics.

For example:

messaging().sendToTopic('tech', {

notification: {

title: 'Apple Unveils New iPhone',

body: 'The new model features AI-powered camera upgrades.'

}

});

Users receive notifications only on topics theyve opted into, reducing noise and increasing relevance. Open rates for topic-based messages are 35% higher than broadcast messages.

Example 3: Fitness App Personalized Workout Reminders

A fitness app tracks user workout schedules and sends reminders based on their activity history. If a user typically works out at 6 AM on Mondays, the app schedules a silent notification to wake the app at 5:55 AM, triggering a local notification with a motivational message and workout plan.

This approach increases daily active users by 18% and reduces app churn by 30% over three months.

Example 4: Travel App Location-Based Offers

A travel booking app uses geofencing and FCM to send notifications when users enter specific locations. For example, when a user arrives at an airport, they receive a notification: Your flight is boarding in 30 minutes. Check in now.

By combining FCM with Google Maps API and user location history, the app delivers hyper-relevant, context-aware messages that drive immediate action.

FAQs

Do I need a server to use Firebase Push Notification?

You dont need a server to send notifications manually via the Firebase Console. However, to send personalized, automated, or scheduled notifications based on user behavior, youll need a backend server to store tokens, manage audiences, and trigger messages via the Firebase Admin SDK or HTTP API.

Can I send push notifications without user permission?

No. All major platforms (iOS, Android, and web browsers) require explicit user consent before allowing notifications. Attempting to bypass this will result in failed deliveries and potential app store rejection.

Why are my notifications not appearing on iOS?

Common causes include: missing push notification capability in Xcode, incorrect provisioning profile, unregistered device token, or user denying permission. Ensure youve enabled Push Notifications in the Capabilities tab and that your app is signed with a distribution certificate that includes the push notification entitlement.

How long does a Firebase registration token last?

Tokens are generally stable but can change due to app reinstallation, device reset, or security updates. Always listen for token refresh events and update your server accordingly.

Can I send notifications to users who havent opened the app yet?

Yes. Once the app is installed and the FCM token is registeredeven if the user hasnt launched the appyou can send notifications. However, on iOS, the app must be launched at least once for the token to be generated.

Is Firebase Push Notification free?

Yes. Firebase Cloud Messaging is free to use at any scale. Google charges only for other Firebase services like Analytics or Cloud Storage if you exceed free quotas. FCM has no usage limits for message delivery.

How do I track if a user clicked a notification?

On Android and iOS, handle the notification tap in your apps launch intent or notification response handler. Send a custom event to Firebase Analytics with a label like notification_click and include parameters like message ID or campaign name.

Can I send images or rich media in notifications?

Yes. On Android and iOS, you can include image URLs in the data payload and download the image in your notification service to display it as a large icon or expanded view. On web, use the image field in the notification payload.

Whats the difference between FCM and APNs?

FCM is Googles unified messaging platform that supports Android, iOS, and web. APNs (Apple Push Notification service) is Apples proprietary system for iOS and macOS. FCM acts as a bridgeit routes messages to APNs for iOS devices and to Googles servers for Android. You dont need to manage APNs directly when using FCM.

Conclusion

Adding Firebase Push Notification to your application is a transformative step toward building a more engaging, responsive, and user-centric experience. The integration processfrom project setup to token management and message deliveryis well-documented and supported by robust tools. By following the steps outlined in this guide, you can implement a notification system that is reliable, scalable, and aligned with modern user expectations.

Remember: the goal of push notifications is not to interrupt, but to add value. Personalize your messages, respect user preferences, and measure every campaigns impact. Use Firebase Analytics to understand what resonates and refine your strategy over time.

As user attention becomes increasingly fragmented, timely, relevant notifications are among the most effective ways to maintain connection and drive retention. Whether youre launching a new app or optimizing an existing one, Firebase Push Notification provides the infrastructure to turn passive users into active participants.

Start smalltest with one audience segment. Measure results. Iterate. With each iteration, your notification strategy will become sharper, smarter, and more impactful. The technology is ready. Now its time to put it to work.