How to send push notifications with Firebase and React
Push notifications improve engagement with your app. Firebase provides a way to send them using their Firebase Cloud Messaging service. I'm going to show you how to integrate it in your React app.
What we are building
Get the complete code here.
Ad Placeholder
Create Firebase project
- Add project from the Firebase Console
- Add a Web App to your firebase project
- Press
Continue to console
Add firebase to React app
- Create demo starter app from the terminal
npx create-modern-app --name firebase-messaging-with-react --type demo
- Install dependencies
npm i firebase @useweb/firebase
- Setup firebase in app
npx firebase-tools init hosting
- Click
Use an existing project
- Click
tut-push-notifications (tut-push-notifications)
- Select the following options:
? What do you want to use as your public directory? build
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? Set up automatic builds and deploys with GitHub? No
Firebase initialized 🎉
Firebase will create
firebase.json
and.firebaserc
- Add
gcm_sender_id
property tomanifest.json
. Insert the value below AS IT IS, without changing.
{
"gcm_sender_id": "103953800507"
}
- Create a firebase-messaging-sw.js file in your public folder. This service worker will receive and display notification when your app is in the background.
/* eslint-disable no-undef */
importScripts('https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.6.8/firebase-messaging.js')
const firebaseConfig = undefined // firebaseConfig is required
firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging()
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload)
const notificationTitle = payload.notification.title
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon || payload.notification.image,
}
self.registration.showNotification(notificationTitle, notificationOptions)
})
self.addEventListener('notificationclick', (event) => {
if (event.action) {
clients.openWindow(event.action)
}
event.notification.close()
})
- Replace
firebaseConfig = undefined
infirebase-messaging-sw.js
with your firebase config. Find underProject settings
in the firebase console.
- Create
src/services/Firebase/Firebase.tsx
and add the following code. We are using the@useweb/firebase/useFirebase
package in order to pass necessary data to the@useweb/firebase/useFirebaseMessaging
package we will use later on.
import React from 'react'
import { FirebaseProvider } from '@useweb/firebase/useFirebase'
import { initializeApp } from 'firebase/app'
import { getMessaging, isSupported } from 'firebase/messaging'
const firebaseConfig = undefined // firebaseConfig is required
const firebaseApp = initializeApp(firebaseConfig)
// Messaging is not supported in ios or safari as of 2022
const messagingIsSupported = await isSupported()
const messaging = messagingIsSupported ? getMessaging(firebaseApp) : undefined
const envIsDev = process.env.NODE_ENV === 'development'
const vapidKey = undefined // vapidKey is required
export default function Firebase({ children }) {
return (
<FirebaseProvider
firebaseConfig={firebaseConfig}
firebaseApp={firebaseApp}
envIsDev={envIsDev}
messaging={messaging}
messagingOptions={{
vapidKey,
}}
>
{children}
</FirebaseProvider>
)
}
- Replace
firebaseConfig = undefined
insrc/services/Firebase/Firebase.tsx
with your firebase config. Find underProject settings
in the firebase console.
- Generate firebase messaging
vapidKey
- Open the Cloud Messaging tab in the Firebase console Project Settings and scroll to the Web configuration section.
- In the
Web Push certificates
tab, click theGenerate key pair
button.
Replace
vapidKey = undefined
insrc/services/Firebase/Firebase.tsx
with your generatedvapidKey
Wrap you app with
Firebase.tsx
src/src.tsx
import React from 'react'
import { createRoot } from 'react-dom/client'
import Firebase from './services/Firebase/Firebase'
import Router from './pages/router'
import Theme from './theme/theme'
function App() {
return (
<Firebase>
<Theme>
<Router />
</Theme>
</Firebase>
)
}
const container = document.getElementById('root') as any
const root = createRoot(container)
root.render(
<>
<App />
</>,
)
- We are going to use
@useweb/firebase/useFirebaseMessaging
to retrieve our FCM registration token and handle notifications while the app is in the foreground. Add the following code topages/HomePage/HomePage.tsx
import React, { useEffect } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import LinearProgress from '@mui/material/LinearProgress'
import useFirebaseMessaging from '@useweb/firebase/useFirebaseMessaging'
import Text from '@useweb/ui/Text'
import useSnackbar from '@useweb/ui/Snackbar'
import CopyToClipboard from '../../lib/components/basic/CopyToClipboard/CopyToClipboard'
export default function HomePage() {
const snackbar = useSnackbar()
const firebaseMessaging = useFirebaseMessaging({
onMessage: (message) => {
console.log(`Received foreground message`, message)
snackbar.show({
message: message?.notification?.title || message?.data?.title,
})
},
})
useEffect(() => {
firebaseMessaging.init()
}, [])
return (
<Box>
<Text
text='Firebase Messaging Push Notification Example'
sx={{ fontSize: '21px', fontWeight: 'bold' }}
/>
{firebaseMessaging.initializing && (
<>
<Text
text='Initializing Firebase Messaging (enable notifications for this page)'
sx={{ mb: 2 }}
/>
<LinearProgress />
</>
)}
{firebaseMessaging.error && (
<Text text={firebaseMessaging.error.toString()} sx={{ color: 'red' }} />
)}
{firebaseMessaging.fcmRegistrationToken && (
<>
<Box
sx={{
display: 'grid',
gridAutoFlow: 'column',
justifyContent: 'start',
alignItems: 'center',
mb: 1,
gridGap: '10px',
}}
>
<Text text='FCM Registration Token:' />
<CopyToClipboard text={firebaseMessaging.fcmRegistrationToken}>
<Button>Copy</Button>
</CopyToClipboard>
</Box>
<Text
text={firebaseMessaging.fcmRegistrationToken}
sx={{
width: '100%',
overflowWrap: 'break-word',
fontSize: '14px',
color: 'gray.main',
}}
/>
</>
)}
</Box>
)
}
That is it, now lets test push notifications using the generated FCM registration token
Open
http://localhost:3001/
Open Firebase message composer
Click on
New campaign
buttonClick on
Notifications
button
Add
Notification title
andNotification text
Click
Send test message
Add the registration token generated from
http://localhost:3001/
and click the plus iconClick
Test
🎉 Your app will show a snackbar if the app is in the foreground or it will show the native notification if the app is in the background
Send notification from a cloud function (Advanced)
- Get
FCM registration token
to send cloud messages to.
const messaging = useFirebaseMessaging({
onFcmRegistrationToken: (fcmRegistrationToken) => {
console.log(fcmRegistrationToken)
},
})
- Send message from nodejs function/app
const message = {
data: {
title: `New episodes aired recently!`,
image: `/images/logo/assets/logo.png`,
icon: `/images/logo/assets/logo.png`,
body,
actions: JSON.stringify(actions),
},
tokens: fcmRegistrationToken,
}
functions.logger.info('FCM Message', message)
// https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-multiple-devices
const response = await messaging.sendMulticast(message)