techStackGuru

Firebase Push Notification


Firebase Console

Step 1: Create a New Firebase Project

https://console.firebase.google.com/u/0/?pli=1
  • Click on Add Project
  • Enter Project Name and Continue
  • You can now see the Dashboard

    Step 2: Project Settings

  • Click on Project Settings
  • Click on Cloud Messaging tab
  • Click on Firebase Cloud Messaging API (V1) settings
  • Now click on Manage API in Google Cloud Console
  • You will see Product detais.
  • Click on enable button
  • Step 3: Installation

    npm install @react-native-firebase/app @react-native-firebase/messaging

    Step 4: Configuration

    Update your android/app/build.gradle. In dependencies add below

    implementation 'com.google.firebase:firebase-messaging'

    Step 5: Create file index.js or similar

    import messaging from '@react-native-firebase/messaging';
    
    async function requestUserPermission() {
        const authStatus = await messaging().requestPermission();
        const enabled =
            authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
            authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    
        if (enabled) {
            console.log('Authorization granted');
        } else {
            console.log('Authorization declined');
        }
    }
    
    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
        console.log('Message handled in the background:', remoteMessage);
    });
    
    export default requestUserPermission;

    Foreground Message Handling

    import messaging from '@react-native-firebase/messaging';
    
    async function registerForegroundListener() {
        messaging().onMessage((message) => {
            // Process the message data and display any notifications or actions
            console.log('Got foreground message:', message);
        });
    }
    
    // Call the listener somewhere in your app's initialization (e.g., main component)
    registerForegroundListener();

    Background Message Handling (Optional):

    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
        // Process the message data and schedule or display notifications
        console.log('Message handled in the background:', remoteMessage);
    });