Push Notifications
Push notifications are a powerful way to engage users. They let you send messages to users even when your app isn't open. Let's set up push notifications for both platforms.
How Push Notifications Work
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β Push Notification Flow β
βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Your Server βββ APNs/FCM βββ Device β
β β β
β βΌ β
β ββββββββββββ β
β β Device β β
β β Displays β β
β βNotifi- β β
β βcation β β
β ββββββββββββ β
β β
β APNs = Apple Push Notification service (iOS) β
β FCM = Firebase Cloud Messaging (Android) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
React Native: Firebase Notifications
import messaging from '@react-native-firebase/messaging';
// Request permission
const requestPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
};
// Get device token
const getToken = async () => {
const token = await messaging().getToken();
console.log('Device token:', token);
// Send this token to your server
};
// Handle foreground messages
messaging().onMessage(async remoteMessage => {
console.log('Foreground message:', remoteMessage);
// Show local notification
});
// Handle background messages
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Background message:', remoteMessage);
});
Flutter: Firebase Messaging
import 'package:firebase_messaging/firebase_messaging.dart';
// Request permission
Future<void> requestPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
print('User granted: ${settings.authorizationStatus}');
}
// Get token
Future<void> getToken() async {
String? token = await FirebaseMessaging.instance.getToken();
print('Token: $token');
// Send to your server
}
// Handle messages
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Foreground message: ${message.notification?.title}');
});
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('Background message: ${message.notification?.title}');
}
Best Practices
- Permission: Always ask permission politely before sending notifications
- Relevance: Send personalized, relevant notifications
- Frequency: Don't spam users - quality over quantity
- Action: Notifications should lead to meaningful in-app actions