Software Crafting

A Practical Guide to Implementing Push Notifications in React Native with Firebase (FCM)

BBadal SinghMobile Development10 min read29 Apr 2026Updated 2026-11-07
A smartphone on a dark surface with glowing cyan and orange light bars rising from its screen, red notification icons and network lines around it

TL;DR: This guide walks through implementing Firebase Cloud Messaging (FCM) in React Native with the @react-native-firebase/messaging package and its modular API. It covers essential cross-platform configurations, including explicitly requesting the POST_NOTIFICATIONS permission for Android 13+ and setting up iOS using a non-expiring .p8 APNs Auth Key instead of legacy .p12 certificates.

Key Takeaways

  • Keep @react-native-firebase/app and @react-native-firebase/messaging on exactly the same version to avoid native build errors.
  • Apply the com.google.gms.google-services plugin in your android/app/build.gradle and place the google-services.json file in the android/app/ directory to link Firebase to Android.
  • Add the <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> tag to your AndroidManifest.xml to support Android 13 (API level 33).
  • Use React Native's PermissionsAndroid.request to explicitly prompt users for the POST_NOTIFICATIONS permission on Android devices running version 33 or higher.
  • Use a .p8 APNs Auth Key instead of .p12 certificates on iOS: one key covers development and production APNs and does not expire (though it can be revoked).
  • Use the modular API (getMessaging(), onMessage(messaging, ...)); the namespaced messaging() style is deprecated in current React Native Firebase releases.

Adding push notifications to a React Native app sounds straightforward: install a library, copy some setup code, and watch the messages roll in.

In practice, there are several places it goes wrong. iOS drops messages because APNs is not configured for the right app or key, Android 13's runtime permission blocks your alerts, or the background handler never runs because it was registered too late in the app lifecycle. The result is that users miss updates that matter to them.

The fix is a careful, step-by-step implementation of Firebase Cloud Messaging (FCM) using the @react-native-firebase/messaging package (React Native Firebase, or RNFB).

In this guide, we walk through an FCM setup for a bare React Native app, focusing on cross-platform quirks, Android 13 permissions, background versus foreground handling, device token management, and deep links. The code uses the modular API that current RNFB releases document; the older namespaced messaging().method() style is deprecated.

Core Setup: Installing React Native Firebase

Before touching notifications, you need the core Firebase app module alongside the messaging module. We assume you have already created a Firebase project in the console and have your bare React Native project ready.

Run the following command to install the required dependencies:

yarn add @react-native-firebase/app @react-native-firebase/messaging

Once installed, you must link the native iOS dependencies:

cd ios && pod install && cd ..

Production Note: Keep all @react-native-firebase/* packages on exactly the same version. Mismatched app and messaging versions commonly cause native build errors. Pin exact versions (no ^) in package.json and upgrade the packages together.

On iOS, current RNFB releases also need two native changes. Add use_frameworks! :linkage => :dynamic to your ios/Podfile (React Native 0.75+ resolves the Firebase Apple SDK through Swift Package Manager, which requires dynamic linkage). Then download GoogleService-Info.plist from the Firebase console, add it to the Xcode project, and call FirebaseApp.configure() at the start of application(_:didFinishLaunchingWithOptions:) in AppDelegate.swift ([FIRApp configure]; in an Objective-C AppDelegate.mm). Run pod install again after editing the Podfile.

Android Configuration and Android 13+ Permissions

Android requires the google-services.json file downloaded from your Firebase console. Place this file inside your android/app/ directory.

Next, enable the Google Services plugin. Update your root android/build.gradle:

buildscript {
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.5.0'
    }
}

Then, apply the plugin at the top of your android/app/build.gradle:

apply plugin: "com.android.application"
// Add this line
apply plugin: "com.google.gms.google-services"

Handling the Android 13 Permission Shift

Historically, Android granted push notification permissions automatically upon installation. Starting with Android 13 (API level 33), you must explicitly request the POST_NOTIFICATIONS permission.

First, declare the permission in your android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Add this line for Android 13+ -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <!-- ... -->
</manifest>

Then request the permission in your React Native code, from a utility function called at a point in onboarding where the user understands why you are asking:

import { PermissionsAndroid, Platform } from 'react-native';

export async function requestAndroidPushPermission() {
  if (Platform.OS === 'android' && Platform.Version >= 33) {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
      {
        title: 'Notification Permission',
        message: 'Allow notifications so we can tell you when your order status changes.',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );

    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('Android push permission granted');
      return true;
    } else {
      console.log('Android push permission denied');
      return false;
    }
  }
  return true; // Auto-granted on older Android versions
}

Configuring iOS APNs and Capabilities

Firebase does not bypass Apple's infrastructure; on iOS, FCM delivers through APNs. To make this work, you must link your Apple Developer account to Firebase.

Instead of dealing with legacy .p12 certificates that expire annually, generate an APNs Auth Key (.p8 file) in your Apple Developer portal. Upload the .p8 key, with its Key ID and your Team ID, to the Firebase Console (Project Settings > Cloud Messaging > Apple app configuration). One key works for both the development and production APNs environments and does not expire, though you can revoke it.

Next, open Xcode, select your project target, navigate to the Signing & Capabilities tab, and add the following:

  1. Push Notifications
  2. Background Modes > Check "Remote notifications" and "Background fetch"

Finally, iOS requires explicit user consent before it shows notifications. RNFB still exposes requestPermission, but it is now marked deprecated in favour of dedicated permission libraries such as react-native-permissions or expo-notifications. It works today; plan to move to one of those libraries:

import {
  getMessaging,
  requestPermission,
  AuthorizationStatus,
} from '@react-native-firebase/messaging';
import { Platform } from 'react-native';

export async function requestIOSPushPermission() {
  if (Platform.OS === 'ios') {
    const authStatus = await requestPermission(getMessaging());
    const enabled =
      authStatus === AuthorizationStatus.AUTHORIZED ||
      authStatus === AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      console.log('iOS push permission granted. Status:', authStatus);
    }
    return enabled;
  }
  return true;
}

Implementing Foreground and Background Message Handlers

This is where many developers stumble. Messages are handled differently in the foreground (app visible on screen) and in the background or quit state (app minimized or not running).

The Background Handler

When your app is in the background or quit, RNFB calls the handler you register with setBackgroundMessageHandler. On Android it runs in a Headless JS task without mounting your root component. On iOS, the system launches the app in the background, the handler runs, and your root component is also mounted (RNFB can pass an isHeadless prop so you can render nothing in that case). Register the handler early, outside your component tree, typically in index.js.

// index.js
import { AppRegistry } from 'react-native';
import { getMessaging, setBackgroundMessageHandler } from '@react-native-firebase/messaging';
import App from './App';
import { name as appName } from './app.json';

// Register background handler early
setBackgroundMessageHandler(getMessaging(), async (remoteMessage) => {
  console.log('Message handled in the background!', remoteMessage.messageId);

  // Example: Update local SQLite database or AsyncStorage here
  // Do NOT attempt to update UI state here!
});

AppRegistry.registerComponent(appName, () => App);

Warning: Do not use UI components, React hooks, or Alerts inside setBackgroundMessageHandler. On Android the component tree does not exist when it runs, and on iOS the app is not visible. Keep the work short: the OS limits how long background execution may take.

The Foreground Handler

When the user is actively using the app, notifications will not appear in the system tray by default. Instead, FCM triggers the onMessage listener. You are responsible for showing an in-app banner or updating the UI manually.

Here is a custom React hook for foreground messages:

// hooks/useFCM.js
import { useEffect } from 'react';
import { Alert } from 'react-native';
import { getMessaging, onMessage } from '@react-native-firebase/messaging';

export function useForegroundFCM() {
  useEffect(() => {
    const unsubscribe = onMessage(getMessaging(), async (remoteMessage) => {
      // In production, use a custom toast UI library rather than Alert
      Alert.alert(
        remoteMessage.notification?.title || 'New Message',
        remoteMessage.notification?.body || 'You received a notification.',
      );

      console.log('Foreground message received:', remoteMessage.data);
    });

    // Clean up the listener on unmount
    return unsubscribe;
  }, []);
}

Keeping background work (storage, sync) separate from foreground UI updates keeps each handler simple and avoids side effects running in the wrong app state.

Architecting FCM Token Management

To send a push notification to a specific user, your backend needs the FCM registration token for each of their devices. Tokens are not permanent: they change when the app is restored on a new device, when the user uninstalls and reinstalls the app, when they clear app data, and occasionally when Firebase refreshes them.

A sound token strategy captures the token after login and listens for refreshes. The backend should take the user from the authenticated request, not from a userId in the body.

import { getMessaging, getToken, onTokenRefresh } from '@react-native-firebase/messaging';
import api from '../services/api'; // Your authenticated backend API client

// Call after login; call the returned function on logout to stop listening
export async function syncFCMToken() {
  const messaging = getMessaging();

  try {
    // 1. Register the current token for the signed-in user
    const token = await getToken(messaging);
    await api.post('/me/devices', { token });
  } catch (error) {
    console.error('Failed to sync FCM token:', error);
  }

  // 2. Keep the backend up to date when the token rotates
  return onTokenRefresh(messaging, async (newToken) => {
    await api.post('/me/devices', { token: newToken });
  });
}

Your backend should maintain a one-to-many relationship between users and devices. When a user logs out, delete that token on the server (and call deleteToken(getMessaging()) on the device) so notifications are not delivered to someone who is no longer signed in there. When a send fails with messaging/registration-token-not-registered, delete that token too, so stale tokens do not pile up.

RNFB also documents an opt-in alternative to registration tokens based on Firebase Installation IDs (register and onRegistered). It is off by default; the token APIs above remain the default path.

Handling Notification Interactions and Deep Linking

Users don't just look at notifications; they tap them. Your app needs to know why it was opened so it can route the user to the correct screen (e.g., opening a specific chat thread or order details view).

There are two routing scenarios to handle:

  1. The app was running in the background and brought to the foreground (onNotificationOpenedApp).
  2. The app was completely killed and launched entirely by the tap (getInitialNotification).
import React, { useEffect } from 'react';
import {
  getMessaging,
  onNotificationOpenedApp,
  getInitialNotification,
} from '@react-native-firebase/messaging';
import { useNavigation } from '@react-navigation/native';

export function NotificationRouter() {
  const navigation = useNavigation();

  useEffect(() => {
    const messaging = getMessaging();

    // Scenario 1: App opened from a background state
    const unsubscribe = onNotificationOpenedApp(messaging, (remoteMessage) => {
      handleNavigation(remoteMessage.data);
    });

    // Scenario 2: App launched from a quit state
    getInitialNotification(messaging).then((remoteMessage) => {
      if (remoteMessage) {
        handleNavigation(remoteMessage.data);
      }
    });

    return unsubscribe;
  }, []);

  const handleNavigation = (data) => {
    if (data?.type === 'ORDER_UPDATE' && data?.orderId) {
      navigation.navigate('OrderDetails', { orderId: data.orderId });
    }
  };

  return null;
}

Structuring the Backend Payload for Cross-Platform Reliability

A common problem is background handlers that work on Android but not on iOS. This usually comes down to how your backend constructs the FCM message.

FCM payloads contain two main objects: notification (handled automatically by the system UI) and data (custom key-value pairs handled by your JavaScript code).

For your background handler to run on iOS, the APNs payload must set the content-available flag. For data-only messages, RNFB's docs also require the APNs headers apns-push-type: background and apns-priority: 5, and on Android data-only messages need priority: 'high' to wake the app.

Here is a message with both a visible notification and data, sent with the modular firebase-admin SDK:

// Backend (Node.js) using firebase-admin
const { initializeApp } = require('firebase-admin/app');
const { getMessaging } = require('firebase-admin/messaging');

// Uses Application Default Credentials (for example GOOGLE_APPLICATION_CREDENTIALS)
initializeApp();

const message = {
  token: deviceToken, // loaded from your devices table
  notification: {
    title: 'Your order has shipped!',
    body: 'Track your delivery in real-time.',
  },
  data: {
    type: 'ORDER_UPDATE',
    orderId: 'ORD-98765',
  },
  android: {
    priority: 'high',
  },
  apns: {
    payload: {
      aps: {
        contentAvailable: true, // sent to APNs as "content-available": 1
        sound: 'default',
      },
    },
  },
};

getMessaging()
  .send(message)
  .then((messageId) => console.log('Sent message:', messageId))
  .catch((error) => console.error('Error sending message:', error.code, error.message));

Setting the platform-specific options (android.priority and apns.payload.aps.contentAvailable) asks both operating systems to deliver the message promptly and wake your background handler. Delivery is still not guaranteed: iOS throttles background pushes, does not wake an app the user has force-quit, and Android can defer work for apps in restricted battery states. Do not use push as the only channel for data your app must have; sync on launch as well.

Debugging Common Production Issues

Even with a correct setup, production brings surprises. Here are the first things to check when push notifications stop working:

  1. Tokens aren't routing: Check that your backend stores the FCM registration token from getToken, not the raw APNs token from getAPNSToken. They are different values, and FCM only accepts the former.
  2. Notifications don't show when the app is open: This is by design. If you want a visual banner while the app is in the foreground, you must build it manually inside the onMessage listener using a library like react-native-toast-message.
  3. Works in development, fails in TestFlight: Check the APNs key, Key ID and Team ID in the Firebase Console, and make sure the Bundle Identifier in Xcode exactly matches the one registered in the Apple Developer Portal and in Firebase. Also confirm the release build's entitlements include aps-environment.
  4. Nothing arrives on the iOS simulator: test on a real device first. Simulator support for remote notifications is limited, and RNFB's docs note that iOS simulators do not handle cloud messages.
  5. Background handler never runs on Android: make sure setBackgroundMessageHandler is called in index.js before AppRegistry.registerComponent, not inside a component.

If push is one part of a larger mobile build, such as a delivery or field-service app where notifications, background sync and deep links all have to agree, that is the kind of work our React Native app development team takes on. For background sync beyond push, see our guide to reliable background processing in React Native.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

How do I handle push notification permissions for Android 13+ in React Native?

Starting with Android 13 (API level 33), push notifications are no longer auto-granted upon installation. You must declare the POST_NOTIFICATIONS permission in your AndroidManifest.xml and explicitly request it using React Native's PermissionsAndroid API during your user onboarding flow.

Should I use a .p12 certificate or a .p8 Auth Key for iOS Firebase push notifications?

Use an APNs Auth Key (.p8 file) instead of .p12 certificates. A .p8 key does not expire (it can be revoked) and works for both the development and production APNs environments, so one key covers every build.

Why am I getting native compilation errors after installing React Native Firebase?

A common cause is mismatched versions between @react-native-firebase/app and @react-native-firebase/messaging. Keep all React Native Firebase packages on exactly the same version in package.json before running pod install. On iOS, also check that your Podfile uses use_frameworks! :linkage => :dynamic, as current RNFB releases require.

What are the core dependencies needed to implement FCM in React Native?

You need to install both the core @react-native-firebase/app module and the @react-native-firebase/messaging module. After adding them via your package manager, you must run pod install in your iOS directory to properly link the native dependencies.

Why doesn't my background handler run on iOS?

The message must set content-available in the APNs payload, and data-only messages also need the apns-push-type: background and apns-priority: 5 headers. Even then, iOS may throttle background pushes and does not wake an app the user has force-quit, so treat background delivery as best effort.

About the author

Badal Singh

Co-founder of SoftwareCrafting

Badal Singh is the Co-founder of SoftwareCrafting in Delhi and writes technical guides about web and mobile development, backend security, cloud infrastructure, DevOps, and developer tooling.

Writes about Next.js, React, Node.js, PostgreSQL, React Native, Flutter.

View author profile

Last updated: 2026-11-07