How to Use Firebase Cloud Messaging (FCM) with React
To use
Firebase Cloud Messaging (FCM) with React, first install Firebase SDK, initialize Firebase in your app, then request user permission for notifications and handle incoming messages using Firebase messaging APIs. Use onMessage to listen for foreground messages and configure a service worker for background notifications.Syntax
This is the basic pattern to use FCM in React:
- Import and initialize Firebase app and messaging.
- Request permission to send notifications.
- Get the FCM token to identify the device.
- Listen for messages when the app is open.
- Use a service worker for background messages.
javascript
import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage } from 'firebase/messaging'; const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID', messagingSenderId: 'YOUR_SENDER_ID', appId: 'YOUR_APP_ID' }; const app = initializeApp(firebaseConfig); const messaging = getMessaging(app); // Request permission and get token const requestPermissionAndGetToken = async () => { try { const permission = await Notification.requestPermission(); if (permission === 'granted') { const token = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' }); return token; } else { console.error('Notification permission not granted'); } } catch (error) { console.error('Permission or token error:', error); } }; // Listen for foreground messages onMessage(messaging, (payload) => { console.log('Message received in foreground:', payload); });
Example
This example shows a React component that requests notification permission, gets the FCM token, and listens for messages while the app is open.
javascript
import React, { useEffect, useState } from 'react'; import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage } from 'firebase/messaging'; const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID', messagingSenderId: 'YOUR_SENDER_ID', appId: 'YOUR_APP_ID' }; const app = initializeApp(firebaseConfig); const messaging = getMessaging(app); function FcmComponent() { const [token, setToken] = useState(null); const [message, setMessage] = useState(null); useEffect(() => { const requestPermission = async () => { try { const permission = await Notification.requestPermission(); if (permission === 'granted') { const currentToken = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' }); setToken(currentToken); } else { console.log('Notification permission denied'); } } catch (err) { console.error('Error getting token:', err); } }; requestPermission(); const unsubscribe = onMessage(messaging, (payload) => { setMessage(payload.notification?.title || 'New message received'); }); return () => unsubscribe(); }, []); return ( <div> <h2>Firebase Cloud Messaging with React</h2> {token ? <p>Your FCM Token: {token}</p> : <p>Requesting permission...</p>} {message && <p>Message: {message}</p>} </div> ); } export default FcmComponent;
Output
Firebase Cloud Messaging with React
Your FCM Token: <token_string>
Message: <notification_title>
Common Pitfalls
Common mistakes when using FCM with React include:
- Not requesting notification permission before getting the token.
- Using an incorrect or missing
vapidKeywhen callinggetToken. - Not setting up the Firebase service worker for background notifications.
- Ignoring errors when permission is denied or token retrieval fails.
- Not unsubscribing from
onMessagelistener causing memory leaks.
javascript
/* Wrong: Getting token without permission */ const token = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' }); /* Right: Request permission first */ await Notification.requestPermission(); const token = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' });
Quick Reference
Tips for using FCM with React:
- Always initialize Firebase with your project config.
- Request notification permission before getting the token.
- Use
onMessageto handle messages when app is open. - Configure
firebase-messaging-sw.jsfor background messages. - Keep your
vapidKeysafe and correct.
Key Takeaways
Initialize Firebase and messaging with your project config before use.
Always request user permission before retrieving the FCM token.
Use onMessage to handle notifications when the app is in the foreground.
Set up a service worker to receive background notifications.
Handle errors and unsubscribe listeners to avoid memory leaks.