Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Notifications and Background Tasks

Push Notifications Basics

Set up push notifications in Expo: ask permission, get an Expo push token, send messages through the push API, handle foreground display and taps, and read receipts.

A notification brings a user back to your app when it is closed: a message arrived, an order shipped, a reminder is due. There are two kinds. Local notifications are created by the app itself (next lesson). Push notifications are sent from your server, through Apple's and Google's delivery services, to a specific device.

Expo simplifies push with expo-notifications on the device and one Expo Push API on the server. You send one request in one format, and Expo forwards it to APNs (iOS) or FCM (Android).

What runs on this site. Notifications need a real device and native services, so the app code is read-only. The runnable examples are stand-ins for the server side: building push messages, splitting them into batches and processing receipts with plain Node.js.

The journey of a push

sequenceDiagram
  participant App
  participant Expo as "Expo push service"
  participant Server as "Your server"
  participant OS as "APNs / FCM"
  App->>Expo: "1. Ask for an Expo push token"
  App->>Server: "2. Save the token for this user"
  Server->>Expo: "3. POST message to token"
  Expo->>OS: "4. Forward to Apple or Google"
  OS->>App: "5. Show the notification"

The token is the address of one app install on one device.

Setup

Terminal
npx expo install expo-notifications expo-device expo-constants

Add the plugin and (optionally) an Android icon in app.json:

JSON
{
  "expo": {
    "plugins": [
      ["expo-notifications", { "icon": "./assets/notification-icon.png", "color": "#ffffff" }]
    ]
  }
}

Remote push does not work in Expo Go on Android from SDK 53 on, and never works in simulators. Use a development build (EAS Build) on a physical device. Push also needs credentials: an APNs key for iOS (EAS can create it) and an FCM V1 service account for Android, uploaded with eas credentials.

Ask permission and get a token

JSX
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import { Platform } from 'react-native';

export async function registerForPushAsync() {
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'Default',
      importance: Notifications.AndroidImportance.MAX,
    });
  }

  if (!Device.isDevice) throw new Error('Push needs a physical device');

  let { status } = await Notifications.getPermissionsAsync();
  if (status !== 'granted') {
    ({ status } = await Notifications.requestPermissionsAsync());
  }
  if (status !== 'granted') return null; // user said no

  const projectId = Constants.expoConfig?.extra?.eas?.projectId ?? Constants.easConfig?.projectId;
  const { data: token } = await Notifications.getExpoPushTokenAsync({ projectId });
  return token; // looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
}

Good habits:

  • Ask at the right moment, after the user understands the benefit, not on first launch. On iOS you only get one system prompt.
  • Create the Android channel first; on Android 13+ the permission prompt only appears once a channel exists.
  • Send the token to your server after login and whenever it changes, and delete it on logout.

Show notifications while the app is open

By default a notification that arrives while the app is in the foreground is silent. Choose how to handle it once, at module level:

JSX
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowBanner: true,
    shouldShowList: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

React to notifications

JSX
useEffect(() => {
  const received = Notifications.addNotificationReceivedListener((n) => {
    console.log('arrived while open:', n.request.content.title);
  });
  const tapped = Notifications.addNotificationResponseReceivedListener((r) => {
    const { screen, id } = r.notification.request.content.data;
    router.push(`/${screen}/${id}`); // deep link from the payload
  });
  return () => { received.remove(); tapped.remove(); };
}, []);

Put a small data object in every message ({ screen: 'orders', id: 42 }) so a tap can open the right screen. If the app was killed and a tap launches it, read the tap with Notifications.useLastNotificationResponse().

Sending from a server

The Expo Push API is one endpoint: POST https://exp.host/--/api/v2/push/send. The body is one message or an array of up to 100 messages.

Terminal
curl -X POST https://exp.host/--/api/v2/push/send \
  -H "Content-Type: application/json" \
  -d '{"to":"ExponentPushToken[xxxx]","title":"Order shipped","body":"Arrives Friday","data":{"screen":"orders","id":42}}'

Because a server may notify thousands of users, it must validate tokens and chunk messages. The expo-server-sdk package does this for Node.js. Here is the same logic written by hand.

Node.js Build and batch push messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Tickets and receipts

Sending returns one ticket per message, either { status: "ok", id } or { status: "error", details: { error: "DeviceNotRegistered" } }. Some errors only appear later in receipts, fetched with the ticket ids about 15 minutes after sending. The error you must act on is DeviceNotRegistered: the app was uninstalled, so delete that token from your database.

Node.js Clean up dead tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Test without code

Expo provides a Push Notifications Tool at expo.dev/notifications: paste a token, write a title and body, press send. It is the fastest way to confirm that credentials and the device are set up correctly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an Expo push token?

    You send a message to a token; Expo routes it to the right device through APNs or FCM.
  2. 2. Where does remote push NOT work?

    Remote push needs a physical device with a registration from Apple or Google.
  3. 3. How many messages can one request to the Expo push API contain?

    Up to 100 messages per request, so larger sends must be chunked.
  4. 4. What should you do when a receipt says DeviceNotRegistered?

    The app was uninstalled or the token expired; further sends are wasted.

Summary

  • Push goes from your server to the Expo push service, then to APNs or FCM, then to the device.
  • On the device: create the Android channel, check or request permission, then call getExpoPushTokenAsync with your projectId.
  • Set a notification handler for foreground display, and listen for taps to deep link using data.
  • On the server: validate tokens, send in batches of 100, check receipts and remove DeviceNotRegistered tokens.
  • Test on a physical device with a development build.

Next: Scheduling local notifications