Skip to main content

How to Send Cross-Platform Push Notifications with Firebase Admin SDK

 

When I first integrated push notifications into my project, I assumed Firebase Cloud Messaging (FCM) was only for Android. But after some research, I discovered that Firebase Admin SDK can send push notifications to both iOS and Android devices, saving me from managing two separate notification services.

In this article, I’ll share how I set up Firebase Admin SDK in Node.js to send push notifications to iOS and Android apps seamlessly.


Why Firebase Admin SDK?

Firebase Admin SDK is a powerful tool that simplifies sending notifications via Firebase Cloud Messaging (FCM). You don’t need to maintain a separate notification system for iOS and Android — just one codebase.

What You’ll Learn:

✅ How to send push notifications using Firebase Admin SDK.
✅ iOS and Android setup differences.
✅ Common pitfalls and how to avoid them.


Step 1: Setting Up Firebase Admin SDK in Node.js

Before we start, make sure your project is already set up with Firebase and that you’ve linked your Android and iOS apps in the Firebase Console.

Install Firebase Admin SDK:

npm install firebase-admin

Initialize Firebase Admin SDK:

import admin from 'firebase-admin';

// Initialize Firebase Admin
admin.initializeApp({
credential: admin.credential.cert({
type: 'service_account',
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: 'https://accounts.google.com/o/oauth2/auth',
token_uri: 'https://oauth2.googleapis.com/token',
auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
client_x509_cert_url: process.env.FIREBASE_CLIENT_X509_CERT_URL,
}),
});

Step 2: Configuring Your Mobile Apps

For Android:

  1. Add the Firebase SDK to your project.
  2. Register the device token using Firebase.

For iOS:

  1. Add Firebase SDK and enable Push Notifications in Xcode.
  2. Upload your APNs Authentication Key or Certificate in Firebase Console.

Step 3: Sending Notifications with Firebase Admin SDK

Here’s how to send a push notification from your Node.js server:

const sendNotification = async (fcmToken, title, body) => {
const message = {
notification: {
title: title,
body: body,
},
token: fcmToken, // Device FCM token
};

try {
const response = await admin.messaging().send(message);
console.log('Successfully sent message:', response);
} catch (error) {
console.error('Error sending message:', error);
}
};
// Example FCM Token (Replace with a real one)
const testToken = 'YOUR_DEVICE_FCM_TOKEN';
// Send a Test Notification
sendNotification(testToken, 'Hello World!', 'This is a test message.');

Best Practices to Ensure Delivery

  1. Check Your Firebase Setup:
    Ensure APNs Authentication Key is uploaded in Firebase Console (for iOS).
  2. Handle Device Token Registration:
    Register tokens correctly in your mobile apps.
  3. Ask for Notification Permission (iOS):
    Ensure you ask for permission when the app is installed.
  4. Use Production Keys for Production:
    Use APNs Production Key for live deployments.

Common Pitfalls to Avoid

๐Ÿ’ฅ Wrong FCM Token: Ensure the mobile app properly registers the FCM token.

๐Ÿ’ฅ Misconfigured Firebase Project: Double-check that iOS and Android apps are linked in the Firebase Console.

๐Ÿ’ฅ Incorrect APNs Key Upload: If notifications don’t work on iOS, confirm your APNs key upload.


Final Thoughts

By using Firebase Admin SDK, I reduced the complexity of sending notifications to iOS and Android devices. Firebase Admin makes push notifications easy and reliable, even for cross-platform apps. If you’re building a project that requires push notifications, give Firebase Admin SDK a try — you won’t regret it.

Happy coding! ๐Ÿš€๐Ÿ“ฑ๐Ÿ’ฌ

    Popular posts from this blog

    Xcode and iOS Version Mismatch: Troubleshooting "Incompatible Build Number" Errors

    Have you ever encountered a frustrating error while trying to run your iOS app in Xcode, leaving you scratching your head? A common issue arises when your device's iOS version is too new for the Xcode version you're using. This often manifests as an "incompatible build number" error, and looks like this: DVTDeviceOperation: Encountered a build number "" that is incompatible with DVTBuildVersion. This usually happens when you are testing with beta versions of either iOS or Xcode, and can prevent Xcode from properly compiling your storyboards. Let's explore why this occurs and what you can do to resolve it. Why This Error Occurs The core problem lies in the mismatch between the iOS version on your test device and the Software Development Kit (SDK) supported by your Xcode installation. Xcode uses the SDK to understand how to build and run apps for specific iOS versions. When your device runs a newer iOS version than Xcode anticipates, Xcode mi...

    How to Fix the “Invariant Violation: TurboModuleRegistry.getEnforcing(…): ‘RNCWebView’ Could Not Be Found” Error in React Native

    When working with React Native, especially when integrating additional libraries like react-native-signature-canvas , encountering errors can be frustrating. One such error is: Invariant Violation: TurboModuleRegistry. getEnforcing (...): 'RNCWebView' could not be found This error often occurs when the necessary dependencies for a module are not properly linked or when the environment you’re using doesn’t support the required native modules. Here’s a breakdown of how I encountered and resolved this issue. The Problem I was working on a React Native project where I needed to add the react-native-signature-canvas library to capture user signatures. The installation process seemed straightforward: Installed the package: npm install react-native-signature- canvas 2. Since react-native-signature-canvas depends on react-native-webview , I also installed the WebView package: npm install react- native -webview 3. I navigated to the iOS directory and ran: cd ios pod install Everythi...

    Fixing FirebaseMessagingError: Requested entity was not found.

    If you’re working with Firebase Cloud Messaging (FCM) and encounter the error: FirebaseMessagingError: Requested entity was not found. with the error code: messaging/registration-token-not-registered this means that the FCM registration token is invalid, expired, or unregistered . This issue can prevent push notifications from being delivered to users. ๐Ÿ” Possible Causes & Solutions 1️⃣ Invalid or Expired FCM Token FCM tokens are not permanent and may expire over time. If you’re storing tokens in your database, some might be outdated. ✅ Solution: Remove invalid tokens from your database when sending push notifications. Refresh and store the latest FCM token when the app starts. Example: Automatically Refresh Token firebase. messaging (). onTokenRefresh ( ( newToken ) => { // Send newToken to your backend and update the stored token }); 2️⃣ Token Unregistered on Client Device A token might become unregistered if: The app is uninstalled on the user’s device. ...