1---
2title: Push notifications setup
3sidebar_title: Setup
4description: Learn how to setup push notifications, get credentials for development and production, and test sending push notifications.
5---
6
7import { Tab, Tabs } from '~/ui/components/Tabs';
8import { Terminal } from '~/ui/components/Snippet';
9import { Step } from '~/ui/components/Step';
10import ImageSpotlight from '~/components/plugins/ImageSpotlight';
11import { BoxLink } from '~/ui/components/BoxLink';
12
13To 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. After going through these steps, you'll be able to test notification sending and receiving notifications on a device.
14
15To get the client-side ready for push notifications, the following things are required:
16
17- The user's permission to send them push notifications.
18- The user's [`ExpoPushToken`](/versions/latest/sdk/notifications/#expopushtoken).
19
20<Step label="1">
21
22## Install libraries
23
24Run the following command to install `expo-notifications` and `expo-device` libraries:
25
26<Terminal cmd={['$ npx expo install expo-notifications expo-device']} />
27
28[`expo-notifications`](/versions/latest/sdk/notifications) library is used to request for a user's permission and to fetch the `ExpoPushToken`. It is not supported on an Android Emulator or an iOS simulator. The [`expo-device`](/versions/latest/sdk/device) is used to check whether the app is running on a physical device.
29
30</Step>
31
32<Step label="2">
33
34## Add a minimal working example
35
36The 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:
37
38```jsx App.js
39import { useState, useEffect, useRef } from 'react';
40import { Text, View, Button, Platform } from 'react-native';
41import * as Device from 'expo-device';
42import * as Notifications from 'expo-notifications';
43
44/* @info This handler determines how your app handles notifications that come in while the app is foregrounded. */
45Notifications.setNotificationHandler({
46  handleNotification: async () => ({
47    shouldShowAlert: true,
48    shouldPlaySound: false,
49    shouldSetBadge: false,
50  }),
51});
52/* @end */
53
54// Can use this function below OR use Expo's Push Notification Tool from: https://expo.dev/notifications
55async function sendPushNotification(expoPushToken) {
56  const message = {
57    to: expoPushToken,
58    sound: 'default',
59    title: 'Original Title',
60    body: 'And here is the body!',
61    data: { someData: 'goes here' },
62  };
63
64  await fetch('https://exp.host/--/api/v2/push/send', {
65    method: 'POST',
66    headers: {
67      Accept: 'application/json',
68      'Accept-encoding': 'gzip, deflate',
69      'Content-Type': 'application/json',
70    },
71    body: JSON.stringify(message),
72  });
73}
74
75async function registerForPushNotificationsAsync() {
76  let token;
77  /* @info You should make sure the app is running on a physical device since push notifications don't work on an emulator/simulator. */
78  if (Device.isDevice) {
79    /* @end */
80    const { status: existingStatus } = await Notifications.getPermissionsAsync();
81    let finalStatus = existingStatus;
82    if (existingStatus !== 'granted') {
83      const { status } = await Notifications.requestPermissionsAsync();
84      finalStatus = status;
85    }
86    if (finalStatus !== 'granted') {
87      alert('Failed to get push token for push notification!');
88      return;
89    }
90    /* @info This provides the ExpoPushToken. */
91    token = (await Notifications.getExpoPushTokenAsync()).data;
92    /* @end */
93    console.log(token);
94  } else {
95    alert('Must use physical device for Push Notifications');
96  }
97
98  /* @info On Android, you need to specify a channel. */
99  if (Platform.OS === 'android') {
100    Notifications.setNotificationChannelAsync('default', {
101      name: 'default',
102      importance: Notifications.AndroidImportance.MAX,
103      vibrationPattern: [0, 250, 250, 250],
104      lightColor: '#FF231F7C',
105    });
106  }
107  /* @end */
108
109  return token;
110}
111
112export default function App() {
113  const [expoPushToken, setExpoPushToken] = useState('');
114  const [notification, setNotification] = useState(false);
115  const notificationListener = useRef();
116  const responseListener = useRef();
117
118  useEffect(() => {
119    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
120
121    /* @info This listener is fired whenever a notification is received while the app is foregrounded. */
122    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
123      setNotification(notification);
124    });
125    /* @end */
126
127    /* @info This listener is fired whenever a user taps on or interacts with a notification (works when an app is foregrounded, backgrounded, or killed). */
128    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
129      console.log(response);
130    });
131    /* @end */
132
133    return () => {
134      Notifications.removeNotificationSubscription(notificationListener.current);
135      Notifications.removeNotificationSubscription(responseListener.current);
136    };
137  }, []);
138
139  return (
140    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
141      <Text>Your expo push token: {expoPushToken}</Text>
142      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
143        <Text>Title: {notification && notification.request.content.title} </Text>
144        <Text>Body: {notification && notification.request.content.body}</Text>
145        <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
146      </View>
147      <Button
148        title="Press to Send Notification"
149        onPress={async () => {
150          await sendPushNotification(expoPushToken);
151        }}
152      />
153    </View>
154  );
155}
156```
157
158</Step>
159
160<Step label="3">
161
162## Test using Expo Go and push notifications tool
163
164> This step allows testing the push notifications when developing your project using Expo Go. If you are using EAS or [development builds](/development/introduction), you can skip this step and move on to the next one to configure credentials for Android and iOS.
165
166To test the example from the previous step, you can use Expo Go to open the project and the [Expo push notifications tool](https://expo.dev/notifications) to send a notification to your device.
167
168<ImageSpotlight
169  alt="Expo push notifications tool overview."
170  src="/static/images/notifications/push-notifications-tool-overview.jpg"
171  style={{ maxWidth: 1200 }}
172/>
173
174Make sure that the development server for your project is running. Then, open the project in the Expo Go app and after the `ExpoPushToken` is generated, enter the value in the Expo push notifications tool with other details (for example, a message title and body) and click on the **Send a Notification** button.
175
176After 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.
177
178<ImageSpotlight
179  alt="An Android device receiving a push notification."
180  src="/static/images/notifications/notification-on-android.jpg"
181  style={{ maxWidth: 360 }}
182/>
183
184</Step>
185
186<Step label="4">
187
188## Get Credentials for development builds
189
190For Android and iOS, there are different requirements to set up your credentials.
191
192### Android
193
194For 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 (unless you are testing your project in Expo Go).
195
196> **warning** FCM is not currently available for `expo-notifications` on iOS.
197
198#### Setting up FCM
199
2001. To create a Firebase project, go to the [Firebase console](https://console.firebase.google.com/) and click on **Add project**.
201
2022. 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.**
203
2043. After registering the app, download the **google-services.json** file and place it in your project's root directory.
205
206   > The **google-services.json** file contains unique and non-secret identifiers of your Firebase project. For more information, see [Understand Firebase Projects](https://firebase.google.com/docs/projects/learn-more#config-files-objects).
207
2084. 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:
209
210   ```json app.json
211   {
212     "android": {
213       "googleServicesFile": "./google-services.json"
214     }
215   }
216   ```
217
2185. 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:
219
220   ```json google-services.json
221   {
222      "client": [
223        {
224          "api_key": [
225            {
226              "current_key" "<your Google Cloud Platform API key>",
227            }
228          ]
229        }
230      ]
231    }
232   ```
233
2346. 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**.
235
2367. 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](https://console.cloud.google.com/apis/credentials) and click on **Show key** to verify their value. It will be marked as **unrestricted**.
237
238   > 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**.
239
240Now you can re-build the development build using the `eas build` command. At this point, if you need to create a development build, see [creating development builds](/development/create-development-builds/#on-a-device).
241
242#### Upload server credentials
243
244For 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.
245
2461. In the Firebase console, next to **Project overview**, click gear icon to open **Project settings**.
247
2482. Click on the **Cloud Messaging** tab in the Settings pane.
249
2503. Copy the token listed next to the **Server key**.
251
252   > Server Key is only available in **Cloud Messaging API (Legacy)**, which is disabled by default. <br/> 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.
253
254   <ImageSpotlight
255     alt="Getting the server key from Firebase console's Cloud messaging tab."
256     src="/static/images/notifications/server-key-from-fcm.jpg"
257     style={{ maxWidth: 760 }}
258   />
259
2604. In your [Expo account's](https://expo.dev/) 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`.
261
262   > For Legacy Application Identifiers, run `expo push:android:upload --api-key your-token-here`, replacing `your-token-here` with the string you just copied. We'll store your token securely on our servers, where it will only be accessed when you send a push notification.
263
2645. Under **Service Credentials** > **FCM Server Key**, click **Add a FCM Server Key** > **Google Cloud Messaging Token** and add the **Server key** from **step 3**.
265
266   > **warning** Having Service Credentials in both Legacy and non-legacy Application Identifiers can prevent push notifications from working on Android devices. If you have a Legacy Application Identifier, you should remove all of its Service Credentials.
267
268### iOS
269
270> **warning** A paid Apple Developer Account is required to generate credentials.
271
272For iOS, make sure you have [registered your iOS device](/development/create-development-builds/#on-a-device) on which you want to test before running the `eas build` command for the first time.
273
274If 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:
275
276- Setup Push Notifications for your project
277- Generating a new Apple Push Notifications service key
278
279<br />
280
281> If you are not using EAS Build, you will need to run `eas credentials` manually.
282
283### Test using the push notifications tool
284
285After creating and installing the development build, you can use Expo's push notifications tool to send a test notification to your device.
286
287</Step>
288
289## Next
290
291<BoxLink
292  title="Send notifications using Expo's Push API"
293  description="Learn how to set your back-end using Expo's Push API, implementation practices, common errors and security best practices."
294  href="/push-notifications/sending-notifications"
295/>
296