Setting up Push Notifications on React Native & Expo Go
Introduction
I was prompted to write this article by the fact that there is no example in the Russian-speaking segment of the Internet for setting up push notifications using only the tools provided by Expo Go
Undoubtedly, there are examples of setting up on pure React Native or using the eject command in the case of Expo Go (which in general does not really change the situation from pure React Naitve) =)
And yes, I will say right away that in this article I will not consider how to set up some specific things in the form of setting sounds for notifications, or some other utter rubbishstupidly set up what would work so to speak
Client
Service APNs setting
A little about APNs
The Apple Push Notification Service is a service created by Apple to send notifications from third-party apps to Apple devices.
There is an interesting article on the topic of service
No matter how strange it may sound, but when using EAS we will practically not need to do anything here
Unless at the first deployment of the application, EAS will offer to set up keys for push notifications (of course, after you log in to Apple Developer account), but there you only need to press Enter =)
Setting up an FCM service
Before starting setup FCM(Firebase Cloud Messaging) you already have should be deployed and configured Appendix
More precisely, we need to get (if not, register) the field from app.json android.package
Next, login to firebaseif the project has not yet been created, you need to create it, then you need to add our android application
You can add it by clicking on the android icon on the main screen
If not found then go to settings and exactly the same panel with available platforms can be found there
When adding the most important thing you need to fill in the field android package name according to the field android.package
in app.json
Finally, download the file google-services.json and throw it into our project. After, we open app.json and in the field android.googleServicesFile
write the path to the file relative to our config file
After the done manipulations, we only need to add Cloud Messaging API Server Keygo to project settings > Cloud messaging and in block Cloud Messaging API you can find the field Server Key copy it, we will need it now
If the field was not found, then in the google cloud console you just need to activate Cloud messaging for your project
Before performing the next step, make sure you are registered with expo.dev and authorized in CLI
We go to the terminal and write the command $ expo push:android:upload --api-key <your-token-here>
and save our api key with which EAS can use it to send push notifications
We go to the section Credentials on the expo website, and make sure that the key has been successfully added
If all is well, then we can move on to the next block.
Working with the application
First we need to install the package expo-notifications to interact with notifications in the app, and expo device to determine if it is a device or a simulator/emulator
$ npm i expo-notifications expo-device
Getting a token
To send push notifications, we need to get the token of our application written using ExpoGo
Let’s create methods for working with the library
1. Obtaining permission to be able to receive notifications and request a token if successful
2. Processing event when a notification is clicked
Method one. Request rights and get a token
async function registerForPushNotificationsAsync()
{
if (Device.isDevice) {
const {status: existingStatus} =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const {status} = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
const token = (await Notifications.getExpoPushTokenAsync()).data;
// TODO Используем полученный токен
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
}
Let’s figure out what’s really going on here.
Check if the method is running on the device or on the emulator/simulator
// ...
if (Device.isDevice) {
// ...
Unfortunately, it is impossible to check the operation of push notifications on an emulator/simulator, you will have to build the application to check it, or open the application in Expo Go on your device
Only if you configure the processing of clicking on push notifications in your application so that some sections or some other actions open, then there will be no problems with android, since it opens the application you created separately from ExpoGo, and on IOS it opens directly into the application , so it will be possible to test this functionality only on the assembly
As experience has shown, it is enough to check everything on android
const {status: existingStatus} = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const {status} = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
At this stage, we ask the user for the right to send notifications, if everything is fine, then we can touch further
const token = (await Notifications.getExpoPushTokenAsync()).data;
Getting a push token to send push notifications using the ExpoGo service
The push token will be of the form ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
Then we save it where you need it so that you can later use it for sending
Method two. Handling a click on a notification
import * as Notifications from "expo-notifications";
Notifications.addNotificationResponseReceivedListener(handleNotificationResponse);
function handleNotificationResponse(response)
{
console.log(response);
}
into a variable response
we get a response like
{
"notification": {
"request": {
"trigger": {
"remoteMessage": {
"originalPriority": 2,
"sentTime": 1668781805348,
"notification": null,
"data": {
"message": "test",
"title": "Test",
"body": "{\"test\":1}",
"scopeKey": "@your_accoutn_expo_name/project_name",
"experienceId": "@your_accoutn_expo_name/project_name",
"projectId": "#####-#####-#####-#####-#####"
},
"to": null,
"ttl": 2419200,
"collapseKey": null,
"messageType": null,
"priority": 2,
"from": "###",
"messageId": "0:###%6c62343ef9fd7ecd"
},
"channelId": null,
"type": "push"
},
"content": {
"title": "Test",
"badge": null,
"autoDismiss": true,
"data": {
"test": 1
},
"body": "test",
"sound": "default",
"sticky": false,
"subtitle": null
},
"identifier": "0:###%6c62343ef9fd7ecd"
},
"date": 1668781805348
},
"actionIdentifier": "expo.modules.notifications.actions.DEFAULT"
}
You can read more here
Server
To test push notifications, you can use the services from the same Expo Push Notification Tool
Everything on the page is ingenious and simple, the main thing is to display our token somewhere in the console or write it to the log file so that we can insert it into the field for the token on the tool website
On the documentation page by sending push notifications to devices, you can find libraries for different programming languages
![](https://habrastorage.org/getpro/habr/upload_files/417/15a/5ce/41715a5ce6aafaaca698331bfac38ff9.png)
Clipping from the documentation
When you’re ready to send a push notification, grab the Expo push token from your user record and send it to the Expo API using a plain old HTTPS POST request. You’ll probably do this from your server (you can write a command line tool to send them if you want, or send them directly from your app, it’s all the same) and the Expo team and community took care of it. for you in several languages:
– expo-server-sdk-node for Node.js. Maintained by the Expo team.
– expo-server-sdk-python for Python. Maintained by community developers.
– expo-server-sdk-ruby for Ruby. Maintained by community developers.
– expo-server-sdk-rust for Rust. Maintained by community developers.
– ExpoNotificationsBundle for Symfony. Maintained by SolveCrew.
– exponent-server-sdk-php or expo-server-sdk-php for PHP. Maintained by community developers.
– exponent-server-sdk-golang for golang. Maintained by community developers.
– exponent-server-sdk-elixir for Elixir. Maintained by community developers.
– expo-server-sdk-dotnet for dotnet. Maintained by community developers.
– expo-server-sdk-java for Java. Maintained by community developers.
– laravel-expo-notifier for Laravel. Maintained by community developers.