Today, you’ll implement push notifications to alert users when they receive a new message in the chat app. This will be done using Firebase Cloud Messaging (FCM) for real-time notifications.
What You Will Do Today:
- Set up Firebase Cloud Messaging for the chat app.
- Configure notifications for new messages.
- Test notifications on Android and iOS.
Step 1: Set Up Firebase Cloud Messaging
- Install Firebase Messaging:
npm install @react-native-firebase/messaging
- Link Native Modules: For iOS, install CocoaPods dependencies:
cd ios pod install cd ..
- Configure Firebase Messaging:
- Add the
google-services.json
file for Android (if not already added). - Add the
GoogleService-Info.plist
file for iOS (if not already added).
- Add the
Step 2: Configure Notifications in the App
- Request Notification Permissions: Add the following to your
App.js
:
import React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { Alert, Platform } from 'react-native';
const requestFCMPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('FCM Permission granted.');
} else {
Alert.alert('Permission denied', 'You will not receive notifications.');
}
};
const handleNotifications = () => {
messaging().onMessage(async (remoteMessage) => {
Alert.alert('New Message', remoteMessage.notification.body);
});
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Background Message:', remoteMessage);
});
};
export default function App() {
useEffect(() => {
requestFCMPermission();
handleNotifications();
}, []);
return <YourNavigationStack />;
}
- Generate an FCM Token: Add this to the
App.js
useEffect
:
useEffect(() => {
const getToken = async () => {
const token = await messaging().getToken();
console.log('FCM Token:', token);
};
getToken();
}, []);
This token uniquely identifies the user’s device for push notifications.
Step 3: Trigger Notifications for New Messages
- Modify Firestore Rules: Ensure your Firestore rules allow the necessary operations for messages.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /messages/{messageId} {
allow read, write: if request.auth != null;
}
}
}
- Set Up Firebase Functions: Use Firebase Functions to send push notifications when a new message is added to the
messages
collection.- Install the Firebase CLI if not already done:
npm install -g firebase-tools
- Initialize Firebase Functions:
firebase init functions
- Add the following code to
functions/index.js
:
- Install the Firebase CLI if not already done:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotificationOnNewMessage = functions.firestore
.document('messages/{messageId}')
.onCreate(async (snapshot, context) => {
const message = snapshot.data();
const payload = {
notification: {
title: `New Message from ${message.userName}`,
body: message.text,
},
};
try {
await admin.messaging().sendToTopic('chat', payload);
console.log('Notification sent successfully');
} catch (error) {
console.error('Error sending notification:', error);
}
});
- Deploy the function:
firebase deploy --only functions
- Subscribe to Topic: In your app, subscribe the user to the
chat
topic:
useEffect(() => {
messaging()
.subscribeToTopic('chat')
.then(() => console.log('Subscribed to chat topic'));
}, []);
Step 4: Test Notifications
- Send a Test Notification:
- Go to the Firebase Console.
- Navigate to Cloud Messaging > Send your first message.
- Send a message to the
chat
topic and confirm it appears on the device.
- Test with a New Message:
- Add a new message in the chat.
- Verify that a notification is triggered and displayed.
Step 5: Handle Background and Killed App States
- Use the following handlers for background and killed app states:
useEffect(() => {
messaging().onNotificationOpenedApp((remoteMessage) => {
console.log('Notification caused app to open:', remoteMessage);
});
messaging()
.getInitialNotification()
.then((remoteMessage) => {
if (remoteMessage) {
console.log('Notification caused app to open from quit state:', remoteMessage);
}
});
}, []);
Summary
Today, you implemented push notifications using Firebase Cloud Messaging (FCM). Users are now alerted in real-time whenever they receive a new message, even if the app is running in the background or is closed.
Tomorrow, you’ll work on displaying message status (sent, delivered, read) to enhance the chat experience.