Firebase

How to set up Firebase Cloud Messaging in a React Native app?

Discover how to effortlessly set up Firebase Cloud Messaging in your React Native app with this straightforward guide. Follow these easy step-by-step instructions to enable push notifications without any hassle.

Developer profile skeleton
a developer thinking

Overview

Getting Firebase Cloud Messaging (FCM) up and running in a React Native app? Not too hard, but a few critical steps. Start by weaving Firebase into your project—create a Firebase project and add those important config files. Then, grab the needed React Native and Firebase libraries. You'll need to set up FCM for both iOS and Android, making sure to cover permissions, services, and notifications. Finally, tackle the logic to receive and handle messages. This setup powers real-time engagement features for your app.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to set up Firebase Cloud Messaging in a React Native app?

Step 1: Set up a Firebase Project

  1. Head over to the Firebase Console.
  2. Click "Add project" and just follow the instructions to create a new project.
  3. Once you're done, go to the project dashboard.

Step 2: Add Firebase to the React Native App

  1. In the Firebase console, go to "Project Settings".
  2. Click the "General" tab, then hit the "Web" icon to add Firebase to your web app.
  3. Register the app and copy the configuration settings (API Key, App ID, etc.).

Step 3: Install Firebase and Dependencies in React Native

  1. Navigate to the root directory of your React Native project.
  2. Install Firebase and its dependencies using npm or yarn:
    ```bash
    npm install @react-native-firebase/app @react-native-firebase/messaging
    ```

Step 4: Configure Firebase in React Native Project

  1. Create a firebase.js file in the project's root:
    ```javascript
    // firebase.js
    import firebase from '@react-native-firebase/app';
    import messaging from '@react-native-firebase/messaging';

    const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
    };

    if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
    }

    export { firebase, messaging };
    ```

Step 5: Set Up Firebase Cloud Messaging (FCM)

  1. In index.js or the entry file, import firebase and messaging:
    ```javascript
    import { firebase, messaging } from './firebase';
    ```

  2. Request permission for notifications (usually in App.js):
    ```javascript
    import React, { useEffect } from 'react';
    import messaging from '@react-native-firebase/messaging';
    import { Alert } from 'react-native';

    const App = () => {
    useEffect(() => {
    const requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    if (authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL) {
    console.log('Authorization status:', authStatus);
    }
    };

    requestUserPermission();

    const unsubscribe = messaging().onMessage(async remoteMessage => {
    Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
    });

    return unsubscribe;
    }, []);

    return (
    // Your app code here
    );
    };

    export default App;
    ```

Step 6: Obtain FCM Token

  1. Get the device token to uniquely identify the user's device for sending notifications:
    ```javascript
    import messaging from '@react-native-firebase/messaging';

    messaging()
    .getToken()
    .then(token => {
    console.log('FCM Token:', token);
    });
    ```

Step 7: Set Up Background Message Handling (Android only)

  1. Create index.js in the root directory if it doesn't exist and add the following:
    ```javascript
    import { AppRegistry } from 'react-native';
    import App from './App';
    import { name as appName } from './app.json';
    import messaging from '@react-native-firebase/messaging';

    messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('Message handled in the background!', remoteMessage);
    });

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

Step 8: Configure AndroidManifest.xml for Notifications (Android)

  1. Open android/app/src/main/AndroidManifest.xml and add the following permissions inside the <manifest> tag:
    ```xml

    \`\`\`
  2. Add the following service inside <application> tag:
    ```xml

    ```

Step 9: Configuration Changes for iOS

  1. Add the required keys to your Info.plist file:
    ```xml
    UIBackgroundModes

    fetch remote-notification \`\`\`
  2. Make sure Push Notification capabilities are enabled in your Xcode project.

  3. Register for remote notifications in App.js:

\`\`\`javascript
useEffect(() => {
  messaging()
    .registerDeviceForRemoteMessages()
    .then(() => {
      console.log('Device registered for remote messages');
    });
}, []);
\`\`\`

Step 10: Test Your Setup

  1. Make sure your app is running on a physical device or simulator/emulator.
  2. Use Firebase Console to send a test message to the registered device and verify the notification is received.

These steps set up Firebase Cloud Messaging in a React Native app effectively. Always check for updates in case of any changes in library implementations or API updates.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.