Learn how to setup push notifications, get credentials for development and production, and test sending push notifications.
Expo Notifications only supports the Cloud Messaging API (Legacy) key at this time. This key is deprecated by Firebase. However, it will continue to work until June 20, 2024. We will provide information on migrating to the new v1 key in the future.
To utilize Expo's push notification service, you must configure your app by installing a set of libraries, implementing functions to handle notifications, and setting up credentials for Android and iOS. Once you have completed the steps mentioned in this guide, you'll be able to test sending and receiving notifications on a device.
To get the client-side ready for push notifications, the following things are required:
ExpoPushToken
.The following steps described in this guide use EAS Build. However, you can use the expo-notifications
library without EAS Build by building your project locally.
1
Run the following command to install the expo-notifications
, expo-device
and expo-constants
libraries:
-
npx expo install expo-notifications expo-device expo-constants
expo-notifications
library is used to request a user's permission and to fetch the ExpoPushToken
. It is not supported on an Android Emulator or an iOS Simulator.expo-device
is used to check whether the app is running on a physical device.expo-constants
is used to get the projectId
value from the app config.2
The code below shows a working example of how to register for, send, and receive push notifications in a React Native app. Copy and paste it into your project:
import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
// Can use this function below or use Expo's Push Notification Tool from: https://expo.dev/notifications
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),
});
}
async function registerForPushNotificationsAsync() {
let token;
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
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({
projectId: Constants.expoConfig.extra.eas.projectId,
});
console.log(token);
} else {
alert('Must use physical device for Push Notifications');
}
return token.data;
}
export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log(response);
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
<Text>Your expo push token: {expoPushToken}</Text>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text>Title: {notification && notification.request.content.title} </Text>
<Text>Body: {notification && notification.request.content.body}</Text>
<Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
</View>
<Button
title="Press to Send Notification"
onPress={async () => {
await sendPushNotification(expoPushToken);
}}
/>
</View>
);
}
projectId
Using the previous example, when you are registering for push notifications, you need to use projectId
. This property is used to attribute Expo push token to the specific project. For projects using EAS, the projectId
property represents the Universally Unique Identifier (UUID) of that project.
projectId
is automatically set when you create a development build. However, we recommend setting it manually in your project's code. To do so, you can use expo-constants
to get the projectId
value from the app config.
token = await Notifications.getExpoPushTokenAsync({
projectId: Constants.expoConfig.extra.eas.projectId,
});
One advantage of attributing the Expo push token to your project's ID is that it doesn't change when a project is transferred between different accounts or the existing account gets renamed.
3
For Android and iOS, there are different requirements to set up your credentials.
For Android, you need to configure Firebase Cloud Messaging (FCM) to get your credentials and set up your Expo project. It is required for all Android apps using Expo SDK.
FCM is not currently available forexpo-notifications
on iOS.
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.
The google-services.json file contains unique and non-secret identifiers of your Firebase project. For more information, see Understand Firebase Projects.
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:
{
"android": {
"googleServicesFile": "./google-services.json"
}
}
For push notifications to work correctly, Firebase requires the API key to either be unrestricted (the key can call any API) or have access to both Firebase Cloud Messaging API and Firebase Installations API. The API key is found under the client.api_key.current_key
field in google-services.json file:
{
"client": [
{
"api_key": [
{
"current_key": "<your Google Cloud Platform API key>"
}
]
}
]
}
Firebase also creates an API key in the Google Cloud Platform Credentials console with a name like Android key (auto-created by Firebase). This could be a different key than the one found in google-services.json.
To be sure that both the current_key
and the Android key in the Credentials console are the same, go to the Google Cloud API Credentials console and click on Show key to verify their value. It will be marked as unrestricted.
Firebase projects with multiple Android apps might contain duplicated data under the
client
array in the google-services.json. This can cause issues when the app is fetching the push notification token. Make sure to only have one client object with the correct keys and metadata in google-services.json.
Now you can re-build the development build using the eas build
command. At this point, if you need to create a development build, see create a development build for a device.
For Expo to send push notifications from our 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 from Cloud Messaging API (Legacy) > Server key.
Server Key is only available in Cloud Messaging API (Legacy), which is disabled by default.
Enable it by clicking the three-dot menu > Manage API in Google Cloud Console and following the steps in the console. Once the legacy messaging API is enabled, you should see Server Key in that section.
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 (Legacy) Server Key, click Add a FCM (Legacy) Server Key > Google Cloud Messaging Token and add the Server key from step 3.
A paid Apple Developer Account is required to generate credentials.
For iOS, make sure you have registered your iOS device on which you want to test before running the eas build
command for the first time.
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 by the EAS CLI:
If you are not using EAS Build, run
eas credentials
manually.
4
After creating and installing the development build, you can use Expo's push notifications tool to quickly send a test notification to your device.
Start the development server for your project:
-
npx expo start --dev-client
Open the development build on your device.
After the ExpoPushToken
is generated, enter the value in the Expo push notifications tool with other details (for example, a message title and body).
Click on the Send a Notification button.
After sending the notification from the tool, you should see the notification on your device. Below is an example of an Android device receiving a push notification.