0
0
FirebaseDebug / FixBeginner · 3 min read

How to Handle Notifications in Foreground with Firebase

To handle notifications in the foreground with Firebase Cloud Messaging, you must listen for messages using onMessage in your app code and then display a custom notification or alert. Firebase does not automatically show notifications when the app is active, so you need to handle this manually.
🔍

Why This Happens

Firebase Cloud Messaging (FCM) automatically shows notifications only when the app is in the background or closed. When the app is open (foreground), FCM delivers the message data to your app but does not display a notification by itself. This is because the app is assumed to be active and able to handle the message directly.

javascript
import messaging from '@react-native-firebase/messaging';

messaging().onMessage(async remoteMessage => {
  // No notification shown here
  console.log('Message received in foreground:', remoteMessage);
});
Output
Message received in foreground: { data: {...}, notification: {...} } // But no notification popup appears
🔧

The Fix

You need to listen for messages in the foreground and then create and show a local notification yourself. This way, users see the notification even when the app is open.

javascript
import messaging from '@react-native-firebase/messaging';
import notifee from '@notifee/react-native';

messaging().onMessage(async remoteMessage => {
  // Show a local notification
  await notifee.displayNotification({
    title: remoteMessage.notification?.title,
    body: remoteMessage.notification?.body,
    android: {
      channelId: 'default',
    },
  });
});
Output
A notification popup appears with the message title and body while the app is open.
🛡️

Prevention

Always implement foreground message handling in your app to ensure users see important notifications anytime. Use libraries like notifee or native notification APIs to show local notifications. Test notifications in both foreground and background states to confirm behavior.

Keep notification channels configured on Android for proper display. Follow Firebase and platform best practices for notification permissions and user experience.

⚠️

Related Errors

Notification not showing in foreground: Happens if you only rely on FCM's automatic display and do not handle onMessage events.

Missing notification channel on Android: Causes notifications to not appear or show silently; always create and use a channel.

Key Takeaways

Firebase does not show notifications automatically when the app is in the foreground.
Use the onMessage listener to catch messages and show local notifications manually.
Use notification libraries like notifee for easy local notification display.
Test notifications in both foreground and background to ensure consistent user experience.
Always configure notification channels on Android for proper notification behavior.