How to Add Firebase Push Notification

How to Add Firebase Push Notification Firebase Cloud Messaging (FCM), Google’s cross-platform messaging solution, enables developers to send push notifications reliably and efficiently to web, Android, and iOS applications. Adding Firebase push notifications to your app enhances user engagement, improves retention, and delivers timely updates—whether it’s a new message, order status, breaking news

Oct 30, 2025 - 13:38
Oct 30, 2025 - 13:38
 0

How to Add Firebase Push Notification

Firebase Cloud Messaging (FCM), Googles cross-platform messaging solution, enables developers to send push notifications reliably and efficiently to web, Android, and iOS applications. Adding Firebase push notifications to your app enhances user engagement, improves retention, and delivers timely updateswhether its a new message, order status, breaking news, or personalized offer. Unlike traditional notification systems, FCM is free, scalable, and integrates seamlessly with other Firebase services like Analytics and Remote Config. This comprehensive guide walks you through every step required to implement Firebase push notifications, from project setup to deployment and optimization. Whether youre a beginner or an experienced developer, this tutorial provides actionable, up-to-date instructions to ensure your app leverages the full power of push notifications.

Step-by-Step Guide

Prerequisites

Before you begin, ensure you have the following:

  • A Google account (required to access Firebase Console)
  • A working web or mobile application (Android, iOS, or Web)
  • Basic knowledge of JavaScript (for web), Java/Kotlin (for Android), or Swift/Objective-C (for iOS)
  • Development environment set up (Android Studio, Xcode, or your preferred code editor)

These prerequisites ensure a smooth implementation process without unexpected roadblocks.

Step 1: Create a Firebase Project

To begin, navigate to the Firebase Console and sign in with your Google account. Click on Add project to create a new Firebase project.

Enter a project namethis can be your apps name or a descriptive identifier. You may optionally enable Google Analytics for deeper user behavior insights. Click Create project. Firebase will now initialize your project, which may take a few moments.

Once created, youll land on the project overview dashboard. This is your central hub for managing all Firebase services, including Cloud Messaging. From here, click on the gear icon next to Project Overview and select Project settings.

Step 2: Register Your App

Under the Your apps section, click Add app. Youll be prompted to choose your platform: Android, iOS, or Web. Select the appropriate one based on your target environment.

For Android:

  • Enter your apps package name (found in your AndroidManifest.xml or Android Studios build.gradle file).
  • Optionally, add a nickname for easier identification.
  • Click Register app.

Download the google-services.json file. Place it in the app/ directory of your Android project. This file contains your projects configuration credentials and must be included in the source code.

For iOS:

  • Enter your iOS bundle ID (found in Xcode under General > Identity).
  • Optionally, provide an App Store ID if your app is already published.
  • Click Register app.

Download the GoogleService-Info.plist file. Drag and drop it into the root of your Xcode project. Ensure its added to your target by checking the Add to targets checkbox.

For Web:

  • Enter a nickname for your web app (e.g., MyWebsite-Prod).
  • Click Register app.

Firebase will generate a configuration object containing your API keys and project identifiers. Copy this objectyoull need it in the next step.

Step 3: Add Firebase SDK to Your App

Each platform requires a different method to integrate the Firebase SDK.

Android:

In your project-level build.gradle file, ensure the Google Services plugin is included in the dependencies:

dependencies {

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

}

In your app-level build.gradle, apply the plugin at the bottom and add the FCM dependency:

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

dependencies {

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

}

Synchronize your project in Android Studio to download the required libraries.

iOS:

If youre using CocoaPods, add the following to your Podfile:

pod 'Firebase/Messaging'

Run pod install in your terminal. Open the generated .xcworkspace file from now on.

If youre not using CocoaPods, follow the manual installation guide on Firebases documentation to add the SDK via Swift Package Manager or static frameworks.

Web:

Include Firebase in your HTML file via CDN or npm. For CDN, add these scripts before your closing </body> tag:

<script src="https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js"></script>

<script src="https://www.gstatic.com/firebasejs/10.12.2/firebase-messaging.js"></script>

Alternatively, install via npm:

npm install firebase

Then import it in your JavaScript file:

import { initializeApp } from "firebase/app";

import { getMessaging } from "firebase/messaging";

Step 4: Configure Firebase Messaging

Now that the SDK is integrated, configure Firebase Messaging to handle notifications.

Android:

Create a new Java or Kotlin class that extends FirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override

public void onMessageReceived(RemoteMessage remoteMessage) {

super.onMessageReceived(remoteMessage);

// Handle both notification and data payloads

if (remoteMessage.getNotification() != null) {

sendNotification(remoteMessage.getNotification().getTitle(),

remoteMessage.getNotification().getBody());

}

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

// Handle custom data payload

String customData = remoteMessage.getData().get("custom_key");

Log.d("FCM", "Custom data: " + customData);

}

}

private void sendNotification(String title, String body) {

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default_channel_id")

.setSmallIcon(R.drawable.ic_notification)

.setContentTitle(title)

.setContentText(body)

.setAutoCancel(true);

NotificationManagerCompat manager = NotificationManagerCompat.from(this);

manager.notify(1, builder.build());

}

}

Also, create a notification channel for Android 8.0+ (required for notifications to appear):

private void createNotificationChannel() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

CharSequence name = "Firebase Notifications";

String description = "Channel for Firebase Push Notifications";

int importance = NotificationManager.IMPORTANCE_HIGH;

NotificationChannel channel = new NotificationChannel("default_channel_id", name, importance);

channel.setDescription(description);

NotificationManager notificationManager = getSystemService(NotificationManager.class);

notificationManager.createNotificationChannel(channel);

}

}

Call createNotificationChannel() in your main activitys onCreate() method.

Update your AndroidManifest.xml to declare the service:

<service

android:name=".MyFirebaseMessagingService"

android:exported="false">

<intent-filter>

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

</intent-filter>

</service>

iOS:

In your AppDelegate.swift, import Firebase and configure it:

import Firebase

import UserNotifications

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

FirebaseApp.configure()

// Request notification permissions

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

if let error = error {

print("Error requesting authorization: \(error)")

}

}

application.registerForRemoteNotifications()

return true

}

Implement the delegate methods to handle incoming messages:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

Messaging.messaging().apnsToken = deviceToken

}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

print("Received notification: \(userInfo)")

completionHandler(.newData)

}

Web:

Initialize Firebase and request permission for notifications:

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

// Request permission and get token

Notification.requestPermission().then((permission) => {

if (permission === 'granted') {

getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' }).then((currentToken) => {

if (currentToken) {

console.log('Token:', currentToken);

// Send token to your server

} else {

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

}

}).catch((err) => {

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

});

} else {

console.log('Unable to get permission to notify.');

}

});

// Handle incoming messages when app is in foreground

onMessage(messaging, (payload) => {

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

// Display notification manually

const options = {

body: payload.notification.body,

icon: payload.notification.icon

};

new Notification(payload.notification.title, options);

});

Replace YOUR_VAPID_KEY with the public key from your Firebase project settings under Cloud Messaging > Web configuration.

Step 5: Send a Test Notification

Now that your app is configured, test the setup using the Firebase Console.

In the Firebase Console, navigate to Cloud Messaging under Engage. Click Send your first message.

Select your target app (Android, iOS, or Web). Choose Single device and paste the registration token you captured earlier (from Android logs, iOS console, or browser dev tools).

Enter a title and message body. Click Review and then Send message.

If configured correctly, the notification should appear on your device or browser within seconds. If it doesnt, check logs for errorscommon issues include incorrect token, missing permissions, or misconfigured service files.

Step 6: Send Notifications from Your Server

For production use, youll need to send notifications programmatically from your backend. Firebase provides REST APIs and server SDKs for this purpose.

First, generate a server key:

  • In Firebase Console, go to Project Settings > Cloud Messaging.
  • Copy the Server key under Legacy server key.

Use this key to authenticate requests to the FCM HTTP v1 API or legacy HTTP protocol.

Example using cURL (HTTP v1):

curl -X POST \

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

-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \

-H 'Content-Type: application/json' \

-d '{

"message": {

"token": "DEVICE_TOKEN",

"notification": {

"title": "Hello from Server",

"body": "This is a test notification sent from your backend."

}

}

}'

To obtain an access token, use Googles OAuth2 service or Firebase Admin SDK.

Using Firebase Admin SDK (Node.js):

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

admin.initializeApp({

credential: admin.credential.cert(serviceAccount)

});

const message = {

token: 'DEVICE_TOKEN',

notification: {

title: 'New Update',

body: 'Check out the latest features!'

}

};

admin.messaging().send(message)

.then((response) => {

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

})

.catch((error) => {

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

});

Deploy this script to your server, and trigger it via API endpoints, cron jobs, or event listeners (e.g., after a user signup or order placement).

Best Practices

Optimize Notification Timing

Push notifications are most effective when delivered at times users are active. Use Firebase Analytics to track user engagement patternssuch as peak usage hoursand schedule notifications accordingly. Avoid sending notifications during late-night hours unless contextually relevant (e.g., flight alerts).

Personalize Content

Generic messages like Hello! perform poorly. Use user datapurchase history, location, preferencesto craft personalized notifications. For example: Your favorite product is back in stock! or Your workout goal is 90% complete. Personalization can increase click-through rates by up to 50%.

Use Data Payloads for Dynamic Behavior

While notification payloads display text, data payloads allow your app to handle logic. Use data keys like action, redirect_url, or campaign_id to trigger in-app actionssuch as opening a specific screen, playing a sound, or updating UI elementswithout requiring a user to tap the notification.

Respect User Preferences

Always give users control. Implement an in-app settings panel where they can toggle notification types (e.g., promotions, alerts, updates). Respect device-level Do Not Disturb settings and avoid overwhelming users with frequent messages. Too many notifications lead to app uninstalls.

Handle Permissions Gracefully

Dont ask for notification permissions immediately on app launch. Wait until the user has engaged with your apps core value. For example, prompt after a user completes their first purchase or saves a favorite item. Provide a clear explanation: Allow notifications to get real-time updates on your orders.

Test Across Devices and OS Versions

Notification behavior varies between Android versions, iOS versions, and browsers. Test on multiple devices, especially older models and OS versions. Use Firebase Test Lab or BrowserStack to simulate real-world conditions.

Monitor Delivery and Engagement

Use Firebase Analytics to track notification open rates, conversion rates, and user retention. Create custom events to measure outcomes like notification_clicked or purchase_after_notification. This data helps refine future campaigns.

Implement Silent Notifications for Background Sync

Silent notifications (with no visible alert) can trigger background tasks like data refresh, cache updates, or content downloads. Use the content_available: true flag in your payload to enable this. This improves app responsiveness without interrupting the user.

Use Topics for Group Messaging

Instead of sending individual tokens to thousands of users, subscribe users to topics like /topics/sports or /topics/news. Then send one message to the topic, and Firebase delivers it to all subscribed devices. This reduces server load and simplifies targeting.

Ensure Secure Token Handling

Never expose FCM registration tokens in client-side code or logs. Always transmit them securely to your backend over HTTPS. Store tokens in a secure database and associate them with user accounts. Revoke or delete tokens when users log out or uninstall the app.

Tools and Resources

Firebase Console

The primary interface for managing notifications, viewing analytics, and sending test messages. Accessible at console.firebase.google.com.

Firebase Admin SDK

Official server libraries for Node.js, Python, Java, Go, and C

. Enables secure, server-side message sending. Available at Firebase Admin SDK Documentation.

FCM HTTP v1 API Reference

Comprehensive guide to the modern FCM API, including request/response formats and authentication. Found at Firebase HTTP v1 API Docs.

Postman Collections for FCM

Pre-built Postman collections for testing FCM endpoints. Download from Firebases GitHub or create your own using the HTTP v1 specification.

Notification Design Tools

  • Canva Design custom notification icons and banners.
  • Android Asset Studio Generate adaptive icons for Android notifications.
  • IconFinder Source high-quality, royalty-free icons for notification icons.

Testing Platforms

  • Firebase Test Lab Automate testing on real Android devices.
  • BrowserStack Test web push notifications across browsers and OS combinations.
  • TestFlight Distribute iOS beta builds to testers.

Analytics and Monitoring

  • Firebase Analytics Track notification performance and user behavior.
  • Google Analytics 4 Integrate with Firebase for cross-platform insights.
  • LogRocket Record user sessions to see how notifications influence behavior.

Open Source Libraries

  • OneSignal Alternative push platform with free tier and advanced segmentation.
  • Pusher Beams Push notification service built on FCM with easier API integration.
  • react-native-firebase Wrapper for Firebase in React Native apps.

Real Examples

Example 1: E-Commerce App

An online fashion retailer uses Firebase push notifications to notify users when items in their wishlist go on sale. When a user adds a product to their wishlist, the app subscribes them to a topic like /topics/wishlist_user_123. The backend monitors inventory and price changes. When a discount is applied, the server sends a message to the topic with a data payload containing the product ID and discount percentage. The app opens the product detail page directly when the notification is tapped, increasing conversion rates by 27%.

Example 2: News Aggregator

A news app sends breaking news alerts using FCM topics like /topics/politics, /topics/tech, and /topics/sports. Users select their interests during onboarding, and the app subscribes them to relevant topics. During major events (e.g., elections or sports finals), the editorial team sends one message to multiple topics simultaneously. The app uses silent notifications to pre-fetch articles in the background, ensuring instant loading when the user opens the app after receiving a notification.

Example 3: Fitness Tracker

A mobile fitness app sends motivational notifications based on user activity. If a user hasnt logged a workout in three days, the backend triggers a notification: Youre on a 3-day streak! Keep going! The notification includes a data payload with a deep link to the workout screen. The app also uses silent notifications to sync daily step data from Apple Health or Google Fit without user interaction.

Example 4: Web-Based SaaS Dashboard

A project management tool uses web push notifications to alert users when a task is assigned to them or a deadline is approaching. The service subscribes users to a unique topic based on their account ID. When a manager assigns a task, an API call sends a notification to that users topic. The notification includes a deep link to the task board. Users who receive these notifications are 40% more likely to complete tasks on time, improving overall team productivity.

Example 5: Travel Booking Platform

A travel app sends flight status updates using FCM. When a user books a flight, their device token is stored with the booking record. The backend integrates with airline APIs to detect delays or gate changes. When an update occurs, a notification is sent with the new time and a View Details button. The notification includes a data payload that opens the booking confirmation page directly in the app, reducing customer service inquiries by 35%.

FAQs

Can I use Firebase Push Notifications for free?

Yes. Firebase Cloud Messaging is completely free to use, with no usage limits on the number of messages sent. However, advanced features like analytics and remote config may have usage thresholds under the Blaze pay-as-you-go plan.

Why are my notifications not appearing on iOS?

Common causes include: missing APNs certificate in Firebase, incorrect bundle ID, not requesting notification permissions, or running on a simulator (which doesnt support push). Ensure youve uploaded the APNs authentication key to Firebase Console and tested on a real device.

How do I handle notifications when the app is closed?

On Android and iOS, FCM handles notifications even when the app is terminated. The system displays the notification using the apps icon and metadata. When tapped, the app launches and receives the notification payload via the launch intent. For web, notifications only work if the user has granted permission and the service worker is active.

Whats the difference between notification and data payloads?

Notification payloads are handled automatically by the system and display a visible alert. Data payloads are delivered to your app code regardless of state and must be processed manually. Use notification payloads for simple alerts and data payloads for in-app logic.

Can I send notifications without a server?

Yes. The Firebase Console allows manual sending of notifications to individual devices or topics without backend code. However, for automated, scalable, or personalized messaging, a server is required.

How do I update or refresh a device token?

Device tokens can change due to app reinstallation, OS updates, or security resets. Always listen for token refresh events. On Android, override onNewToken() in your messaging service. On iOS, implement messaging:didReceiveRegistrationToken:. On web, use onTokenRefresh().

Do push notifications work on all browsers?

Web push notifications work on Chrome, Firefox, Edge, and Safari (with limitations). Safari requires a website verification file and Apple Push Notification service (APNs) certificate. Always test across browsers.

How long does it take for a notification to be delivered?

Typically under 15 seconds under normal network conditions. Delivery may be delayed if the device is offline, in low-power mode, or if Firebase is under high load. FCM uses a persistent connection for reliable delivery.

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

No. Push notifications require a registered device token, which is only generated after the app is installed and the user grants permission. Use email or SMS for pre-installation outreach.

What happens if a user disables notifications?

If the user disables notifications at the OS level, FCM will no longer deliver messages to that device. Your server should detect failed deliveries (via error responses) and stop sending to that token. You can prompt the user to re-enable notifications via an in-app message.

Conclusion

Adding Firebase push notifications to your application is a powerful way to re-engage users, deliver timely information, and enhance overall user experience. From initial project setup to server-side integration and real-world optimization, this guide has provided a complete, step-by-step roadmap to implement FCM across web, Android, and iOS platforms. By following best practicespersonalizing content, respecting user preferences, and monitoring performanceyou can transform notifications from intrusive alerts into valuable, context-aware interactions.

Remember: the goal isnt just to send more notifications, but to send the right notifications at the right time. Use data to guide your strategy, test rigorously across devices, and iterate based on user feedback. Firebase makes it easy to get started, but true success comes from thoughtful, user-centered implementation.

Start smalltest one use case, measure the impact, then expand. Whether youre building a social app, an e-commerce platform, or a productivity tool, Firebase push notifications can be the bridge between your app and your users daily lives. With the tools and knowledge outlined here, youre now equipped to build a notification system thats not just functional, but truly effective.