Skip to main content

Expo push notification setup:

To use Expo's push notification service, you need to configure your app to install a set of libraries, add functions to handle notifications and configure credentials for Android and iOS.

(Note: notification only works on device , not on emulator/simulator)

Install libraries

npx expo install expo-notifications expo-device

After installation import on app start screen (i.e. App.js / index.js)

 import { useState, useEffect, useRef } from 'react'; 
import { Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';

Set Notification handler at the top after import to display notification popup

 Notifications.setNotificationHandler({ 
handleNotification: async () => ({
shouldShowAlert: true, //if true , notification popup will appear
shouldPlaySound: false,
shouldSetBadge: false,
}),
});

Register and get expo token , set listener for notification

export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();

useEffect(() => {
//Registering and getting exp token from registerForPushNotificationsAsync function and setting
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
//Notification listener when notification received
notificationListener.current=Notifications.addNotificationReceivedListener (notification =>
{ setNotification(notification); });
//Notification listener when notification clicked
responseListener.current = Notifications.addNotificationResponseReceivedListener(response =>
{ console.log(response); });

return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};

}, []);

return (<><>)

}

Token register function(function only works on device, not on simulator/emulator)

async function registerForPushNotificationsAsync() { 
let token;
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;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token); }
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',
});
}
return token;
}

For sending push notification to device

    expoPushToken can be an array or single string
expoPushToken = ‘ExpoToken[xyz123456789ZY]’
or
expoPushToken = [‘‘ExpoToken[xyz123456789ZY]’,’‘ExpoToken[xyz123456789MZ]’]

async function sendPushNotification(expoPushToken) {
const message = {
to: expoPushToken,
sound: 'default',
title: 'Original Title', body: 'And here is the body!',
data: { someData: 'goes here' },
};
await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: { Accept: 'application/json', 'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json', },
body: JSON.stringify(message),
});
}

Development setup done , you can test expo notification on local using Expo push notifications tool

Replace graphql and backend url localhost with your ip in env file , go to your app root ,start teminal/cmd and login with expo, remove –localhost from portable device mobile package.json from watch script and start app , Open device scanner,scan qr from terminal and test

(Note:while testing backend and device should be on same network (i.e. wifi)

Credentials configuration for Android and iOS for development(.i.e testflight,android internal testing)/production

For android

Expo uses firebase for sending push notification in android

Setting up FCM

To create a Firebase project, go to the Firebase console and click on Add project.

In the console, click the setting icon next to Project overview and open Project settings. Then, under Your apps, click the Android icon to open Add Firebase to your Android app and follow the steps. Make sure that the Android package name you enter is the same as the value of android.package from your app.json.

After registering the app, download the google-services.json file and place it in your project's root directory.

In app.json, add an android.googleServicesFile field with the relative path to the downloaded google-services.json file. If you placed it in the root directory, the path is:
    app.json:
{
"android": {
"googleServicesFile": "./google-services.json",
}
}

Upload server credentials for android

For Expo to send push notifications from expo servers and use your credentials, you'll have to upload your secret server key to your project's Expo dashboard.

In the Firebase console, next to Project overview, click gear icon to open Project settings.

Click on the Cloud Messaging tab in the Settings pane.

Copy the token listed next to the Server key.

If server key not found , then it is not enabled so for enabling go to Cloud Messaging API (Legacy) Console (google) and enable it

In your Expo account's dashboard, select your project, and click on Credentials in the navigation menu. Then, click on your Application Identifier that follows the pattern:com.company.app.

Under Service Credentials > FCM Server Key, click Add a FCM Server Key > Google Cloud Messaging Token and add the Server key

For ios

Expo uses apple push notification service(apn) for sending push notification in ios

For iOS, make sure you have registered your iOS device on which you want to test before running
the eas build command

For registering ios device , ios device uuid is needed , get ios device uuid

. Go to apple developer console -> account -> Certificates, IDs & Profiles -> . Devices -> click + button and add your uuid . Profiles -> click on your profile(com.app.test.) -> edit and add your device to this profile and save

If you create a development build for the first time, you'll be asked to enable push notifications. Answer yes to the following questions when prompted:

    Setup Push Notifications for your project
Generating a new Apple Push Notifications service key

For existing build:

. Go to apple developer console  -> account -> Certificates, IDs & Profiles -> 
. Devices -> click + button and add your uuid
. Profiles -> click on your profile(com.app.test.) -> edit and add your device to this profile and save
. Identifiers -> click on your identifier(com.app.test) -> check Push Notifications in capabilities and
configure(For notification to run upload new certificate for development and production)
. Keys -> click on + button to create key -> download created p8 file -> save

Now go to expo.dev -> your project -> Credentials -> click ios tab -> Bundle Identifiers (click your identifier) -> com.app.test -> edit Push Key -> Push Key File (upload your downloaded p8 file), Key Identifier(your key id) -> save

Now notification can be tested on testflight