Handling Push Notifications with React Native and Firebase Cloud Messaging
Set up a Firebase Cloud Messaging channel in Knock
If you haven't already, create a new Firebase Cloud Messaging channel in the Integrations page of your Knock dashboard. Follow our Firebase Cloud Messaging push notification guide to configure FCM with Knock using your Service Account JSON file.
Set up React Native Firebase
The simplest way to get started with FCM in your React Native app is to use React Native Firebase, which simplifies the process of handling push notifications and device tokens. Follow their Getting Started guide to set up React Native Firebase in your project.
Add KnockPushNotificationProvider to your app
Ensure your app is wrapped with both KnockProvider
and KnockPushNotificationProvider
.
Request permissions
Depending upon the platforms supported by your app, you may need to request permissions to receive push notifications on the user's device. See React Native Firebase's documentation on how to request permissions on Android and how to request permissions on iOS. Alternatively, consider using a third-party library such as react-native-permissions.
Register for push notifications
When your app launches, retrieve the device token using React Native Firebase's getToken
function. Pass this token to the registerPushTokenToChannel
function provided by Knock's usePushNotifications
hook and include the channel ID of your FCM channel.
Additionally, when your app is in the foreground, register a listener using onTokenRefresh
and invoke registerPushTokenToChannel
whenever the token is refreshed.
Handle incoming push notifications
Listen for push notifications using React Native Firebase's getInitialNotification
and onNotificationOpenedApp
functions. See React Native Firebase's Notifications guide for more details on these two functions.
Send a test notification
Use the Knock dashboard or API to send a test notification to ensure your setup is correct. Verify that the notification appears on your device and that tapping on it triggers the expected behavior.
Troubleshooting
- Not Receiving Notifications: Ensure your FCM device token is correctly registered with Knock and that your device's notification settings allow push notifications from your app.
- Handling Silent Notifications: If implementing silent notifications, ensure that your notification payload is correctly configured to not display an alert or sound.
For further assistance, reach out to our support team.