0
0
React Nativemobile~15 mins

Push notifications with FCM in React Native - Deep Dive

Choose your learning style9 modes available
Overview - Push notifications with FCM
What is it?
Push notifications are messages sent by apps to users even when the app is not open. Firebase Cloud Messaging (FCM) is a service that helps apps send these notifications easily and reliably. It works by sending messages from a server to a device through Google's cloud infrastructure. This lets apps keep users informed and engaged with timely updates.
Why it matters
Without push notifications, apps would have to rely on users opening them to see new information, which reduces engagement and usefulness. FCM solves this by delivering messages instantly, helping apps stay connected with users. This improves user experience, retention, and can even drive important actions like reminders or alerts.
Where it fits
Before learning FCM push notifications, you should understand basic React Native app development and how to use external services. After mastering FCM, you can explore advanced topics like handling notification actions, customizing notifications, and integrating analytics to measure engagement.
Mental Model
Core Idea
Push notifications with FCM let your app send messages through Google's cloud to users' devices anytime, keeping them informed even when the app is closed.
Think of it like...
It's like sending a postcard through the postal service: you write a message, drop it off at the post office (FCM server), and it gets delivered to your friend's mailbox (user's device) even if they're not home (app closed).
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ Your App's   │      │ Firebase      │      │ User's Device │
│ Server       │─────▶│ Cloud Messaging│─────▶│ (App or OS)   │
└───────────────┘      └───────────────┘      └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat Are Push Notifications
🤔
Concept: Introduce the basic idea of push notifications and their purpose.
Push notifications are short messages sent by apps to users. They appear on the device screen or notification center. They can alert users about new messages, reminders, or updates without opening the app.
Result
You understand that push notifications keep users informed and engaged even when the app is not running.
Knowing what push notifications are helps you see why apps use them to communicate instantly and keep users connected.
2
FoundationIntroduction to Firebase Cloud Messaging
🤔
Concept: Explain what FCM is and how it fits into push notifications.
Firebase Cloud Messaging is a free service by Google that sends push notifications to Android, iOS, and web apps. It acts as a middleman between your app's server and the user's device, handling message delivery reliably.
Result
You know FCM is the tool that makes sending push notifications easier and more reliable.
Understanding FCM's role clarifies how push notifications reach devices without you building complex infrastructure.
3
IntermediateSetting Up FCM in React Native
🤔Before reading on: Do you think you need to write native code to use FCM in React Native? Commit to your answer.
Concept: Learn how to add FCM to a React Native app using libraries and configuration.
1. Create a Firebase project and register your app. 2. Download configuration files (GoogleService-Info.plist for iOS, google-services.json for Android). 3. Install React Native Firebase packages: @react-native-firebase/app and @react-native-firebase/messaging. 4. Configure native projects to include Firebase files. 5. Request user permission for notifications. 6. Listen for messages in your React Native code.
Result
Your React Native app is connected to FCM and ready to receive push notifications.
Knowing the setup steps helps you avoid common errors and ensures your app can communicate with FCM properly.
4
IntermediateHandling Notifications in React Native
🤔Before reading on: Do you think notifications arrive only when the app is open? Commit to your answer.
Concept: Understand how to receive and display notifications when the app is in foreground, background, or closed.
Use @react-native-firebase/messaging to listen for messages: - Foreground: Use onMessage listener to show custom UI. - Background: Use setBackgroundMessageHandler to process messages. - Quit state: Notifications are handled by the OS and shown automatically. Also, handle user taps on notifications to navigate inside the app.
Result
Your app can respond to notifications correctly in all app states.
Knowing how notifications behave in different states prevents missed messages and improves user experience.
5
AdvancedCustomizing Notification Appearance
🤔Before reading on: Can you change notification icons and sounds from React Native code alone? Commit to your answer.
Concept: Learn how to customize notification look and behavior on Android and iOS.
On Android, customize notification icons, colors, and sounds by editing native files and using notification channels. On iOS, configure notification categories and sounds in Xcode. Use data messages to send custom payloads and build rich notifications with images or buttons.
Result
Notifications look and behave as you want, matching your app's style and needs.
Understanding platform differences and customization options helps create engaging and branded notifications.
6
AdvancedManaging User Permissions and Token Refresh
🤔
Concept: Handle user permissions and device tokens for reliable messaging.
Request notification permission from users and handle their response. Get the FCM device token to identify the device. Listen for token refresh events to update your server. Handle cases where users revoke permissions or uninstall the app.
Result
Your app respects user choices and maintains correct device tokens for messaging.
Managing permissions and tokens ensures messages reach the right devices and respects privacy.
7
ExpertOptimizing Push Notifications for Production
🤔Before reading on: Do you think sending many notifications quickly is always good? Commit to your answer.
Concept: Learn best practices and pitfalls for using FCM push notifications in real apps.
Avoid spamming users with too many notifications to prevent annoyance. Use topics and device groups to target users efficiently. Implement analytics to track notification open rates. Secure your server keys and validate tokens. Handle message priority and delivery delays carefully.
Result
Your app sends effective, respectful notifications that improve engagement without harming user trust.
Knowing production patterns and limits helps build apps users love and trust.
Under the Hood
FCM works by maintaining a persistent connection between the device and Google's cloud servers. When your app server sends a message to FCM, it queues and routes the message to the device using this connection. The device's OS then displays the notification or delivers the message to the app. This system handles retries, device offline states, and message prioritization automatically.
Why designed this way?
Google designed FCM to offload the complexity of message delivery from app developers. Maintaining persistent connections and handling device states is resource-intensive and error-prone. By centralizing this in FCM, apps can reliably send notifications without building their own infrastructure, saving time and improving reliability.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ App Server   │─────▶│ FCM Cloud     │─────▶│ Device OS     │
│ (Your code)  │      │ (Message Hub) │      │ (Notification │
│              │      │               │      │  Display)     │
└───────────────┘      └───────────────┘      └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think push notifications always arrive instantly? Commit to yes or no.
Common Belief:Push notifications are delivered instantly every time without delay.
Tap to reveal reality
Reality:Delivery depends on device state, network, and OS policies; sometimes notifications are delayed or dropped.
Why it matters:Expecting instant delivery can cause confusion and poor user experience if notifications arrive late or not at all.
Quick: Can you send push notifications without user permission on iOS? Commit to yes or no.
Common Belief:Apps can send push notifications without asking users for permission on iOS.
Tap to reveal reality
Reality:iOS requires explicit user permission before showing notifications; without it, notifications won't appear.
Why it matters:Not requesting permission properly means users never see notifications, reducing app engagement.
Quick: Do you think FCM handles all notification UI automatically on all platforms? Commit to yes or no.
Common Belief:FCM automatically creates and displays notifications exactly the same on Android and iOS.
Tap to reveal reality
Reality:FCM handles notification delivery, but UI customization and behavior differ by platform and often require native setup.
Why it matters:Assuming uniform behavior leads to inconsistent user experience and bugs across devices.
Quick: Is it safe to share your FCM server key publicly? Commit to yes or no.
Common Belief:The FCM server key can be shared freely since it only sends notifications.
Tap to reveal reality
Reality:The server key is sensitive; if leaked, others can send unauthorized notifications or spam users.
Why it matters:Leaked keys can damage your app's reputation and user trust.
Expert Zone
1
FCM message priority affects battery usage and delivery speed; high priority wakes devices but drains battery faster.
2
Data-only messages allow silent background updates but require careful handling to avoid OS restrictions.
3
Notification channels on Android 8+ let users control notification behavior per category, which apps must configure properly.
When NOT to use
Push notifications are not suitable for large data transfers or real-time chat; use WebSockets or other real-time protocols instead. Also, avoid push notifications for non-urgent or excessive messaging to prevent user annoyance.
Production Patterns
In production, apps use topic subscriptions to group users by interest, implement analytics to track notification effectiveness, and use server-side logic to personalize messages. They also handle token refresh and permission changes gracefully to maintain reliable delivery.
Connections
Web Push Notifications
Similar pattern
Understanding FCM helps grasp web push notifications since both use cloud services to deliver messages to devices even when apps or browsers are closed.
Event-Driven Architecture
Builds-on
Push notifications are a form of event-driven communication where servers trigger events (messages) that apps react to asynchronously.
Postal Mail System
Analogy
The postal system analogy helps understand message routing, delivery delays, and the need for addresses (device tokens) in push notifications.
Common Pitfalls
#1Not requesting user permission before sending notifications on iOS.
Wrong approach:import messaging from '@react-native-firebase/messaging'; messaging().onMessage(async remoteMessage => { console.log('Notification received:', remoteMessage); });
Correct approach:import messaging from '@react-native-firebase/messaging'; async function requestPermission() { const authStatus = await messaging().requestPermission(); if (authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL) { console.log('Permission granted'); } } requestPermission();
Root cause:Assuming notifications work without explicit user permission on iOS.
#2Hardcoding device tokens and not handling token refresh.
Wrong approach:const deviceToken = 'abc123'; // Use deviceToken forever without updates
Correct approach:messaging().getToken().then(token => { // Send token to server }); messaging().onTokenRefresh(token => { // Update server with new token });
Root cause:Not realizing device tokens can change and must be updated to maintain delivery.
#3Sending too many notifications quickly to all users.
Wrong approach:// Server sends push to all users every minute sendPushToAllUsers('Check this out!');
Correct approach:// Use topics or user segments sendPushToTopic('news', 'Daily update');
Root cause:Ignoring user experience and server load by spamming notifications.
Key Takeaways
Push notifications keep users engaged by delivering timely messages even when apps are closed.
Firebase Cloud Messaging simplifies sending notifications by handling delivery and device connections.
React Native apps need proper setup, permission handling, and token management to receive notifications reliably.
Customizing notifications requires platform-specific steps to ensure consistent user experience.
In production, thoughtful notification strategy and security practices are essential to maintain user trust and app quality.