{"id":22497164,"url":"https://github.com/chaudharypraveen98/simple-react-native-push-notification","last_synced_at":"2025-06-15T17:34:02.662Z","repository":{"id":59839491,"uuid":"538169116","full_name":"chaudharypraveen98/Simple-React-Native-Push-Notification","owner":"chaudharypraveen98","description":"Notifications made easy in React Native","archived":false,"fork":false,"pushed_at":"2022-09-18T16:27:21.000Z","size":1669,"stargazers_count":6,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-27T21:33:21.226Z","etag":null,"topics":["fcm","mmkv","react-native"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chaudharypraveen98.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-09-18T16:25:49.000Z","updated_at":"2024-10-13T05:31:52.000Z","dependencies_parsed_at":"2022-09-22T22:21:49.788Z","dependency_job_id":null,"html_url":"https://github.com/chaudharypraveen98/Simple-React-Native-Push-Notification","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaudharypraveen98%2FSimple-React-Native-Push-Notification","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaudharypraveen98%2FSimple-React-Native-Push-Notification/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaudharypraveen98%2FSimple-React-Native-Push-Notification/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaudharypraveen98%2FSimple-React-Native-Push-Notification/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chaudharypraveen98","download_url":"https://codeload.github.com/chaudharypraveen98/Simple-React-Native-Push-Notification/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248844073,"owners_count":21170486,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fcm","mmkv","react-native"],"created_at":"2024-12-06T20:17:04.048Z","updated_at":"2025-04-14T07:51:21.201Z","avatar_url":"https://github.com/chaudharypraveen98.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Simple Firebase React Native Push Notification\nNotifications play an important role in targeting the right users at the right time. It helps in the following ways:-\n* Increasing App Engagement\n* Targeting the right user\n* Enhancing the conversion rate\n* Engaging user retention for a period of time\n\n\u003cimg src=\"./readme_assets/PUSH%20NOTIFICATION1000x420.png\"\u003e\n\n**Libraries used: -**\n\n1. **Firebase Cloud Messaging**: It is a cross-platform messaging solution that lets you reliably send messages at no cost.\n2. **React Native MMKV (Optional)**: A library that allows you to easily use MMKV inside your React Native applications. We will need this if we want to store fcm token locally in a fast manner.\n\n## What we are going to do?\nLet's divide the workflow in easy steps:-\n1. Setting up react native project.\n2. Installing **Firebase** libraries needed for FCM Token generation and notification.\n3. Integrating **React native MMKV** for fast storage. (Optional)\n4. Generating FCM token and storage\n5. Requesting user permission for the notification.\n6. Setting up notification Listener\n7. Testing\n\n## 1. Setting up react native project.\nReact CLI will generate the template for you to get started quickly.\n\n### Initialize Project\n`npx react-native init SimpleReactNativeNotification`\n\nIf you are new to React Native, then follow the [React Native Official Docs](https://reactnative.dev/docs/environment-setup) to setup up the environment.\n\n## 2. Installing Firebase libraries needed for FCM Token generation and notification.\nFirebase libraries provide various method to support the firestore, real-time database firebase, Cloud messaging, and so on.\n\n### Installing the React Native Firebase library \n\n```\n# Using npm\nnpm install --save @react-native-firebase/app\n\n# Using Yarn\nyarn add @react-native-firebase/app\n```\n\n### Additional steps for setup in Android and IOS\n1. Android\n   Visit [Firebase console](https://console.firebase.google.com/) and start a new project.\n\n   Add a new Android application and enter your project details. \n   \u003cimg src=\"readme_assets/start_android_app.png\"\u003e\n\n   Download the **google-services.json** file and place it inside of your project at the following location: `/android/app/google-services.json`.\n\n   [For more info](https://rnfirebase.io/#generating-android-credentials)\n2. I don't have a mac device💻. so you can follow [here](https://rnfirebase.io/#3-ios-setup) 😟\n\n### Adding Firebase messaging libraries along with above parent library\n\n```\n# Install the messaging module\n\nyarn add @react-native-firebase/messaging\n\nor \n\nnpm install --save @react-native-firebase/messaging\n\n# If you're developing your app using iOS, run this command\ncd ios/ \u0026\u0026 pod install\n```\n\n## 3. Integrating **React Native MMKV** for fast storage. (Optional)\n\nWe don't need to generate the FCM token every time, as it is the same most of the time. \n\nThere are some exceptions, but we can handle them and reduce the number of calls to generate the token every time.\n\nValidity of FCM Token\n- The app deletes Instance ID\n- The app is restored on a new device\n- The user uninstalls/reinstalls the app\n- The user clears app data.\n\n### Installing\n\n```\nyarn add react-native-mmkv\nor \nnpm install --save react-native-mmkv\n\ncd ios \u0026\u0026 pod install\n```\n\n### Creating instance to use throughout the app\nCreate a new file 'storage.js'\n\n[storage.js](storage.js)\n```\nimport { MMKV } from 'react-native-mmkv'\n\nexport const storage = new MMKV()\n```\n\nHurray! Our mmkv storage is ready to use\n\n## 4. Generate FCM token and store it\nLet's write a function to generate the FCM token.\n\nImporting the messaging library which we installed earlier  \n\n`import messaging from '@react-native-firebase/messaging';`\n\n### 1. Without storage  \ncreating a function **getFcmToken** - ['./notifications.js'](notifications.js)\n```\nconst getFcmToken = async () =\u003e {\n  try {\n    const newFcmToken = await messaging().getToken();\n    console.log(newFcmToken);\n    return newFcmToken;\n  } catch (error) {\n    console.error(error);\n    return null;\n  }\n};\n```\n\nLet's make changes in [App.js](App.js)\n\n```\nimport {getFcmToken} from './notifications';\n\nconst App = () =\u003e {\n  ....\n  const [generatedToken, setGeneratedToken] = useState();\n\n  useEffect(() =\u003e {\n      const fetchToken = async () =\u003e {\n        const token = await getFcmToken();\n        if (token) {\n          setGeneratedToken(token);\n        }\n      };\n      void fetchToken();\n    }, []);\n  ....\n}\n```\n\n### 2. With Storage\ncreating a function **getFcmTokenFromLocalStorage** - ['./notifications.js'](notifications.js)\n```\nconst getFcmTokenFromLocalStorage = async () =\u003e {\n  const fcmtoken = localStorage.getString('fcmtoken');\n  if (!fcmtoken) {\n    try {\n      const newFcmToken = await messaging().getToken();\n      localStorage.set('fcmtoken', newFcmToken);\n    } catch (error) {\n      console.error(error);\n    }\n  } else {\n    console.log('token found', fcmtoken);\n  }\n};\n```\n\nLet's make changes in [App.js](App.js)\n\n```\nimport {getFcmToken} from './notifications';\n\nconst App = () =\u003e {\n  ....\n  const fcmToken = localStorage.getString('fcmtoken');\n\n  useEffect(() =\u003e {\n      const fetchTokenByLocal = async () =\u003e {\n        await getFcmTokenFromLocalStorage();\n      };\n      void fetchTokenByLocal();\n    }, []);\n  ....\n}\n```\n\nUse Hooks to see the tokens\n```\nuseEffect(() =\u003e {\n  console.log('storage', fcmToken, 'newly generated', generatedToken);\n}, [fcmToken, generatedToken]);\n```\n\n## 5. Requesting user permission for the notification.\niOS prevent notification unless explicitly approved by the user.\n\nOn Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully.\n\nIn Android, we don't need any special permission for notification, but this function can still be called and will resolve successfully\n\n['./notifications.js'](notifications.js)\n```\nconst requestUserPermission = async () =\u003e {\n  const authStatus = await messaging().requestPermission();\n  const enabled =\n    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||\n    authStatus === messaging.AuthorizationStatus.PROVISIONAL;\n\n  if (enabled) {\n    console.log('Authorization status:', authStatus);\n  }\n};\n```\n\n## Setting up notification Listener\nWe can listen for real-time FCM messages on any device.\n\n|    **State**   |                                                                                              **Description**                                                                                              |\n|:--------------:|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n| **Foreground** |                                                                      When the application is open and in view.                                                                      |\n| **Background** | When the application is open, however, in the background (minimized). This typically occurs when the user has pressed the \"home\" button on the device or has switched to another app via the app switcher. |\n| **Quit**       | When the device is locked or the application is not active or running. The user can quit an app by \"swiping it away\" via the app switcher UI on the device.                                                   |\n\nYou can read more about [here](https://rnfirebase.io/messaging/usage#message-handlers).\n\nLet's Handle these three cases: -\n\n['./notifications.js'](notifications.js)\n```\nconst notificationListener = () =\u003e {\n\n  messaging().onNotificationOpenedApp(remoteMessage =\u003e {\n    console.log(\n      'Notification caused app to open from background state:',\n      remoteMessage.notification,\n    );\n  });\n\n  // Quiet and Background State -\u003e Check whether an initial notification is available\n  messaging()\n    .getInitialNotification()\n    .then(remoteMessage =\u003e {\n      if (remoteMessage) {\n        console.log(\n          'Notification caused app to open from quit state:',\n          remoteMessage.notification,\n        );\n      }\n    })\n    .catch(error =\u003e console.log('failed', error));\n\n  // Foreground State\n  messaging().onMessage(async remoteMessage =\u003e {\n    console.log('foreground', remoteMessage);\n  });\n};\n```\n\nFor handling the Background notification, we need to add a handler at the ['./index.js'](index.js)\n\n```\nimport messaging from '@react-native-firebase/messaging';\n\n// Register background handler\nmessaging().setBackgroundMessageHandler(async remoteMessage =\u003e {\n  console.log('Message handled in the background!', remoteMessage);\n});\n\n```\n\n## 7. Testing\nFirst, grab the token from the terminal generated by console.log.\n\nVisit [TestFcm.com](https://testfcm.com/)\n\nWe need the server keys to test. We can get this from the firebase console. \n\nOpen the project and get the server key by following the below steps:-\n\n\n\u003cimg src=\"./readme_assets/OptionServerKey.png\"\u003e\n\nIf your cloud messaging api is not enabled then \n\n\u003cimg src=\"./readme_assets/enableApi.png\"\u003e\n\n## Result\n### Foreground Notification\n\u003cimg src=\"./readme_assets/ForeGroundNotification.png\"\u003e\n\n### Background and Quiet Notification\n\u003cimg src=\"./readme_assets/BackgroundNotification.png\"\u003e\n\n**Resources : -**\n1. [Push Notification In React Native Using Firebase - Android \u0026 IOS Tutorial 2022](https://www.youtube.com/watch?v=Qcxa6dxfUFo)\n2. [React Native Firebase Official Docs](https://rnfirebase.io/)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchaudharypraveen98%2Fsimple-react-native-push-notification","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchaudharypraveen98%2Fsimple-react-native-push-notification","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchaudharypraveen98%2Fsimple-react-native-push-notification/lists"}