{"id":19076161,"url":"https://github.com/gapur/firebase-push-notifications","last_synced_at":"2025-04-30T01:46:32.413Z","repository":{"id":60147196,"uuid":"541281714","full_name":"Gapur/firebase-push-notifications","owner":"Gapur","description":"📬 Push Notifications With React And Firebase","archived":false,"fork":false,"pushed_at":"2023-02-22T20:27:03.000Z","size":2799,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2023-02-27T17:56:15.002Z","etag":null,"topics":["firebase","javascript","notifications","push-notifications","react","reactjs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","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/Gapur.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-25T19:12:00.000Z","updated_at":"2023-02-25T20:52:01.000Z","dependencies_parsed_at":"2023-01-19T18:15:31.362Z","dependency_job_id":null,"html_url":"https://github.com/Gapur/firebase-push-notifications","commit_stats":null,"previous_names":[],"tags_count":null,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gapur%2Ffirebase-push-notifications","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gapur%2Ffirebase-push-notifications/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gapur%2Ffirebase-push-notifications/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gapur%2Ffirebase-push-notifications/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Gapur","download_url":"https://codeload.github.com/Gapur/firebase-push-notifications/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223775953,"owners_count":17200629,"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":["firebase","javascript","notifications","push-notifications","react","reactjs"],"created_at":"2024-11-09T01:57:18.650Z","updated_at":"2024-11-09T01:57:19.854Z","avatar_url":"https://github.com/Gapur.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/logo.png\"\u003e\n\u003c/p\u003e\n\n# Firebase Push Notifications\n\nPush Notifications With React And Firebase\n\nHow to receive push notifications\n\nPush notifications are small pop-up messages sent to a user's device or web app that appear even when the app is not open. They can alert real-time updates or changes to their upcoming plans, bookings, deliveries, and other time-sensitive topics. \n\nSo I'm interested how we can easily add receiving push notifications to our web app. In today's tutorial, I'm going to do it through [Firebase Cloud Messaging (FCM)](https://firebase.google.com/products/cloud-messaging?gclid=Cj0KCQjw4omaBhDqARIsADXULuXjc3usXl7wxVaW_mdNdiv6CLc5p_lCc7Atsz_V6Icjg62Atj5WLmkaAqmKEALw_wcB\u0026gclsrc=aw.ds). It is a cross-platform messaging solution that lets you reliably send messages at no cost.\n\n## Getting Started\n\n1. Clone this repository\n```\ngit clone git@github.com:Gapur/firebase-push-notifications.git\n```\n2. Install dependencies\n```\nnpm install\n```\n3. Launch app\n```\nnpm run start # for npm\n```\n\nor if you want to create\n\nFirst, I’m going to create a new React project through the following lines of code:\n\n```sh\nnpx create-react-app firebase-push-notifications\ncd firebase-push-notifications\nnpm run start\n```\n\nGreat, we’ve successfully created and launched our web app.\n\n## Create a Simple Web App\nAfter creating the project with the initial codebase, we have the src/App.js file for the main page. We need to update it so it looks like this:\n\n```js\nimport { ToastContainer, toast } from 'react-toastify';\n\nimport logo from './sparky-dash-high-five.gif';\n\nexport default function App() {\n  const ToastifyNotification = ({ title, body }) =\u003e (\n    \u003cdiv className=\"push-notification\"\u003e\n      \u003ch2 className=\"push-notification-title\"\u003e{title}\u003c/h2\u003e\n      \u003cp className=\"push-notification-text\"\u003e{body}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n\n  return (\n    \u003cdiv className=\"app\"\u003e\n      \u003cimg src={logo} className=\"app-logo\" alt=\"logo\" /\u003e\n\n      \u003cbutton\n        className=\"btn-primary\"\n        onClick={() =\u003e toast(\u003cToastifyNotification title=\"New Message\" body=\"Hi there!\" /\u003e)}\n      \u003e\n        Show toast notification\n      \u003c/button\u003e\n\n      \u003cToastContainer hideProgressBar /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\nI have used the react-toastify toaster lib to display notifications. You can install it by the following command:\n\n```\nnpm install --save react-toastify\n```\n\nHere’s how it looks:\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example1.gif\"\u003e\n\u003c/p\u003e\n\n## Firebase Setup\n\nIf you don’t already have an account at [Firebase](https://firebase.google.com) yet, you should create one. After successfully creating an account, you will be redirected to [Firebase Console](https://console.firebase.google.com) where you can create a project by clicking the Create a project button and filling in the required fields.\n\nIf you have created a project before, you will have a list of project cards. In this case, you need to click `Add project` to create a new one.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example2.png\"\u003e\n\u003c/p\u003e\n\nAfter clicking `Add project`, we need to give the project an appropriate name.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example3.png\"\u003e\n\u003c/p\u003e\n\nThen we have to enable or disable analytics depending on your preference.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example4.png\"\u003e\n\u003c/p\u003e\n\nAwesome, we have done it. Here we have `iOS`, `Android`, and `\u003c\u003e` web options.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example5.png\"\u003e\n\u003c/p\u003e\n\nNext, we need to register our web app with the firebase project by clicking on the web option `\u003c\u003e` button. It will then generate a firebase config file which we will soon integrate into the React app.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example6.png\"\u003e\n\u003c/p\u003e\n\nLet’s use the `firebase-push-notifications` nickname.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example7.png\"\u003e\n\u003c/p\u003e\n\nThe `firebaseConfig` will be integrated into our React app, which will link it to this particular Firebase project.\n\n## Connect to Firebase Cloud Messaging\n\nTo connect to `Firebase Cloud Messaging` we need to install the [firebase](https://www.npmjs.com/package/firebase) lib by running:\n\n```\nnpm install --save firebase\n```\n\nNext, I will create a new file called `firebase.js` and add the following lines of code:\n\n```js\nimport { initializeApp } from 'firebase/app';\nimport { getToken, getMessaging, onMessage } from 'firebase/messaging';\n\nconst firebaseConfig = {\n  apiKey: process.env.REACT_APP_API_KEY,\n  authDomain: process.env.REACT_APP_AUTH_DOMAIN,\n  projectId: process.env.REACT_APP_PROJECT_ID,\n  storageBucket: process.env.REACT_APP_STORAGE_BUCKET,\n  messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,\n  appId: process.env.REACT_APP_APP_ID\n};\n\nconsole.log('*** Environment ***', process.env.REACT_APP_ENV)\nconsole.log('*** Firebase Config ***', firebaseConfig)\n\nconst firebaseApp = initializeApp(firebaseConfig);\nconst messaging = getMessaging(firebaseApp);\n```\n\nLast but not least, we’ll create a function called `getFirebaseToken` that uses the Firebase `getToken` method. This allows you to receive push notifications. If notification permission has not been granted, this method will request the user for permission to notification. Otherwise, it returns the token or rejects the promise due to an error.\n\nThe `getToken` method requires parameters.\n\n1. Voluntary Application Server Identification or VAPID key\n\nYou can get by clicking `Project overview \u003e Project settings \u003e Cloud Messaging` for your project in the Firebase Console, then scroll to the `Web configuration` section. After that, you can just click on `Generate key pair` in the `Web Push certificates` tab.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example8.png\"\u003e\n\u003c/p\u003e\n\n2. serviceWorkerRegistration\n\nWe will use a service worker to work with push notifications. Service worker is a script that works in the background of the browser without user interaction. We don’t have a [service worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) right now, but we’ll create one in the next section.\n\n```js\nexport const getOrRegisterServiceWorker = () =\u003e {\n  if ('serviceWorker' in navigator) {\n    return window.navigator.serviceWorker\n      .getRegistration('/firebase-push-notification-scope')\n      .then((serviceWorker) =\u003e {\n        if (serviceWorker) return serviceWorker;\n        return window.navigator.serviceWorker.register('/firebase-messaging-sw.js', {\n          scope: '/firebase-push-notification-scope',\n        });\n      });\n  }\n  throw new Error('The browser doesn`t support service worker.');\n};\n\nexport const getFirebaseToken = () =\u003e\n  getOrRegisterServiceWorker()\n    .then((serviceWorkerRegistration) =\u003e\n      getToken(messaging, { vapidKey: process.env.REACT_APP_VAPID_KEY, serviceWorkerRegistration }));\n```\n\nAbove, I created a `getOrRegisterServiceWorker` method to try and get the service worker if it exists, otherwise it will register a new one.\n\nAlso, I’m going to add a banner at the top of the page to show permission for the notification.\n\n```js\nimport { useState } from 'react';\nimport { ToastContainer, toast } from 'react-toastify';\n\nimport logo from './sparky-dash-high-five.gif';\nimport { getFirebaseToken } from './firebase';\n\nexport default function App() {\n  const [showNotificationBanner, setShowNotificationBanner] = useState(Notification.permission === 'default');\n\n  const handleGetFirebaseToken = () =\u003e {\n    getFirebaseToken()\n      .then((firebaseToken) =\u003e {\n        console.log('Firebase token: ', firebaseToken);\n        if (firebaseToken) {\n          setShowNotificationBanner(false);\n        }\n      })\n      .catch((err) =\u003e console.error('An error occured while retrieving firebase token. ', err))\n  }\n  \n  const ToastifyNotification = ({ title, body }) =\u003e (\n    \u003cdiv className=\"push-notification\"\u003e\n      \u003ch2 className=\"push-notification-title\"\u003e{title}\u003c/h2\u003e\n      \u003cp className=\"push-notification-text\"\u003e{body}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n\n  return (\n    \u003cdiv className=\"app\"\u003e\n      {showNotificationBanner \u0026\u0026 \u003cdiv className=\"notification-banner\"\u003e\n        \u003cspan\u003eThe app needs permission to\u003c/span\u003e\n        \u003ca\n          href=\"#\"\n          className=\"notification-banner-link\"\n          onClick={handleGetFirebaseToken}\n        \u003e\n          enable push notifications.\n        \u003c/a\u003e\n      \u003c/div\u003e}\n\n      \u003cimg src={logo} className=\"app-logo\" alt=\"logo\" /\u003e\n\n      \u003cbutton\n        className=\"btn-primary\"\n        onClick={() =\u003e toast(\u003cToastifyNotification title=\"New Message\" body=\"Hi there!\" /\u003e)}\n      \u003e\n        Show toast notification\n      \u003c/button\u003e\n\n      \u003cToastContainer hideProgressBar /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\nWe checked `Notification.permission` property which indicates the current permission granted by the user to display web notifications. If we click `enable push notifications` it will get a firebase token and hide the banner.\n\nCool, we are almost done.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example9.png\"\u003e\n\u003c/p\u003e\n\n# Receive Push Notifications\n\n## Receive messages in the background\n\nIn order to receive push notifications in the background, we should create a `firebase-messaging-sw.js` service worker file in the public folder of our React app with the following code:\n\n```js\nimportScripts('https://www.gstatic.com/firebasejs/9.10.0/firebase-app-compat.js');\nimportScripts('https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging-compat.js');\n\nconst firebaseConfig = {\n  apiKey: \"AIzaSyBFZTdA0uHb7_LMTDJowvRJDjDcmzEoTLQ\",\n  authDomain: \"fir-push-notifications-804ed.firebaseapp.com\",\n  projectId: \"fir-push-notifications-804ed\",\n  storageBucket: \"fir-push-notifications-804ed.appspot.com\",\n  messagingSenderId: \"963673480986\",\n  appId: \"1:963673480986:web:d9d5619c29fede473d56a3\"\n};\n\nfirebase.initializeApp(firebaseConfig);\n\nconst messaging = firebase.messaging();\n\nmessaging.onBackgroundMessage((payload) =\u003e {\n  console.log('Received background message: ', payload);\n\n  const notificationTitle = payload.notification.title;\n  const notificationOptions = { body: payload.notification.body };\n\n  self.registration.showNotification(notificationTitle, notificationOptions);\n});\n```\n\nThis service worker will handle all notifications coming to the app while it is in the background.\n\n## Receive messages in the foreground\n\nFor foreground notifications, we need to add this code to the `firebase.js` file:\n\n```js\nimport { initializeApp } from 'firebase/app';\nimport { getToken, getMessaging, onMessage } from 'firebase/messaging';\n\nconst firebaseConfig = {\n  ...\n};\n\nconst firebaseApp = initializeApp(firebaseConfig);\nconst messaging = getMessaging(firebaseApp);\n\n...\n\nexport const onForegroundMessage = () =\u003e\n  new Promise((resolve) =\u003e onMessage(messaging, (payload) =\u003e resolve(payload)));\n```\n\nLast, We need to use `onForegroundMessage` in `App.js` file:\n\n```js\nuseEffect(() =\u003e {\n    onForegroundMessage()\n      .then((payload) =\u003e {\n        console.log('Received foreground message: ', payload);\n        const { notification: { title, body } } = payload;\n        toast(\u003cToastifyNotification title={title} body={body} /\u003e);\n      })\n      .catch(err =\u003e console.log('An error occured while retrieving foreground message. ', err));\n  }, []);\n```\n\nNow we are all set to receive both foreground and background notifications in our React app!\n\n## Let’s Test Our Push Notifications\n\nWe can test by going to the `Firebase Console \u003e Cloud Messaging \u003e Send First Message`.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example10.png\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example11.png\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/example12.png\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"620px\"src=\"https://raw.githubusercontent.com/Gapur/firebase-push-notifications/main/src/assets/demo.gif\"\u003e\n\u003c/p\u003e\n\n# Conclusion\n\nThanks for reading — I hope you found this piece useful. Happy coding!\n\n## Article on Medium\n\n[Push Notifications With React And Firebase](https://javascript.plainenglish.io/push-notifications-with-react-and-firebase-8f7cf9372ac7)\n\n## How to contribute?\n\n1. Fork this repo\n2. Clone your fork\n3. Code 🤓\n4. Test your changes\n5. Submit a PR!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgapur%2Ffirebase-push-notifications","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgapur%2Ffirebase-push-notifications","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgapur%2Ffirebase-push-notifications/lists"}