Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 71 ยท Native Features

Push Notifications

Learn local and remote notifications in React Native: permissions, Expo push tokens, foreground handlers, Android channels, taps and what happens in the background.

A notification is the one way your app can speak when nobody has it open. That makes it powerful and easy to abuse: a useful reminder brings people back, and a noisy one gets your app uninstalled. In React Native you build notifications with the expo-notifications library, and the concepts carry over to any other library too.

There are two very different kinds. A local notification is scheduled by your own app on the device ("remind me in ten minutes"). A remote (push) notification starts on a server, travels through Apple's or Google's delivery network, and wakes the phone. This lesson covers both, the permission and token steps, how a foreground app decides whether to show a banner, and what happens to messages when the phone is off.

Read-only and stand-in. A real push needs a physical device, store-level credentials and Apple's and Google's servers, so the library code is shown in plain blocks. The TryIts run stand-ins: a delivery queue that models offline devices and expiry, and a handler that decides what to do with a message. They explain the behavior, not the real network.

Local versus remote

Local Remote (push)
Who starts it Your app, on the device Your server (or a dashboard)
Needs a token No Yes, a push token per device
Needs internet No Yes
Typical use Reminders, timers, daily habits Chat messages, news, order updates
Works if the app is closed Yes, the OS fires it at the set time Yes, the OS shows it on arrival

Both kinds need the user's permission, and both appear through the same system notification area.

Two roads to a banner

Local Scheduled by the app on the phone.
Remote Sent by your server through APNs or FCM.

Same permission, same notification area.

1 / 2

Permission and Android channels

Ask for permission when it makes sense, such as after the user turns on reminders, and handle every answer exactly as in Camera, Location and Sensors.

TSX
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';

export async function ensureNotificationPermission(): Promise<boolean> {
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'General',
      importance: Notifications.AndroidImportance.DEFAULT,
    });
  }

  const current = await Notifications.getPermissionsAsync();
  if (current.granted) return true;
  if (!current.canAskAgain) return false;

  const asked = await Notifications.requestPermissionsAsync();
  return asked.granted;
}

Android adds two rules. First, since Android 8 every notification belongs to a channel, a category such as "Messages" or "Promotions" that the user can mute separately in system settings. Create channels before you send anything, and choose the importance with care, because it controls sound and pop-up behavior and the user's later changes override it. Second, since Android 13 the notification permission is a runtime prompt, and the prompt only appears after the app has created at least one channel. That is why the code above creates the channel first.

Local notifications

To show something later, hand the OS the content and a trigger. The OS keeps the promise even if your app is closed.

TSX
import * as Notifications from 'expo-notifications';

export async function remindIn(seconds: number, text: string) {
  return Notifications.scheduleNotificationAsync({
    content: {
      title: 'Reminder',
      body: text,
      data: { screen: 'reminders' }, // your own payload
    },
    trigger: {
      type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL,
      seconds,
    },
  });
}

The call returns an identifier that you can pass to cancelScheduledNotificationAsync to withdraw it. There are also calendar-style and daily triggers for "every morning at 8:00". Keep the data object small and plain: it is the only way to carry context from the moment you schedule to the moment the user taps.

Remote notifications and push tokens

For a remote push, the device first needs an address: a push token. Expo wraps the platform tokens (APNs on iOS, FCM on Android) into one string that looks like ExponentPushToken[...].

TSX
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';

export async function registerForPush(): Promise<string | null> {
  if (!(await ensureNotificationPermission())) return null;

  const projectId = Constants.expoConfig?.extra?.eas?.projectId;
  const token = await Notifications.getExpoPushTokenAsync({ projectId });
  return token.data; // send this to your own server and store it per user
}

Your server stores the token against the user, then sends a message by posting JSON to Expo's push service:

JSON
{
  "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "title": "Order shipped",
  "body": "Your package leaves the warehouse today.",
  "data": { "orderId": 4821 }
}

The service replies with a ticket for each message, and later you can ask for receipts to learn whether Apple or Google accepted it. Two habits keep a push system healthy. Delete tokens that the receipts report as no longer valid, because uninstalled apps leave dead tokens behind, and never fire a push for something the user cannot act on.

Remote push has practical limits. It requires a physical device for real testing, and tokens belong to one app install, so a user with two phones has two tokens. Recent Expo SDKs also expect a development build rather than Expo Go for Android remote push, so plan your tooling around custom dev clients.

Never put secrets or sensitive details in a notification body. It can appear on a locked screen, and the payload passes through third-party delivery networks. Send an identifier in data and fetch the sensitive content inside the app after the user opens it.

What happens when a notification arrives

The behavior depends on where the app is:

  • Background or closed: the operating system shows the notification itself. Your JavaScript does not run just because it arrived (with narrow exceptions for special background-task setups).
  • Foreground: the OS shows nothing by default. Your app decides, with a handler that runs for each incoming notification.
TSX
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowBanner: true,
    shouldShowList: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

Set this once, at the top of your app's entry file. A chat app, for example, might return shouldShowBanner: false when the notification belongs to the conversation that is already open on screen.

Then there are two listeners. One fires when a notification arrives while the app is open, and one fires when the user taps a notification:

TSX
useEffect(() => {
  const received = Notifications.addNotificationReceivedListener((notification) => {
    // update an in-app badge, refresh a list, ...
  });

  const tapped = Notifications.addNotificationResponseReceivedListener((response) => {
    const { screen } = response.notification.request.content.data;
    if (screen) router.push(`/${screen}`);
  });

  return () => {
    received.remove();
    tapped.remove();
  };
}, []);

If the tap launched the app from a closed state, the listener may not exist yet, so also read the tap that started the app with Notifications.useLastNotificationResponse(). Routing from a tap is the same problem as handling a link: see Deep Linking and Authentication Flows.

Stand-in: a push delivery queue

Delivery networks are store and forward. If the phone is off, the message waits, but only until its time to live (TTL) runs out. The stand-in below uses a simulated clock in seconds so that every run prints the same lines.

Push delivery with an offline device and TTL

The flash-sale message was useless after ten seconds, so a short TTL is the right choice for it, while the shipping notice is still worth delivering an hour later. Choosing a TTL per message type is one of the simplest ways to make a push system feel considerate.

Stand-in: the foreground handler and a tap

This second stand-in applies the foreground rules from earlier. A pure function decides what to do with each incoming message from the app state and the open conversation, and a second function turns a tap into a screen name.

Foreground handler decisions and tap routing

In the real library, the first function is the body of handleNotification and the second is the body of your tap listener. Keeping both as small pure functions makes them easy to test (see Testing React Native Apps).

Good notification habits

  • Ask for permission after the user has seen the value, with a pre-permission screen on iOS where you only get one system prompt.
  • Offer settings inside the app for categories, and map them to Android channels.
  • Use a short TTL for time-sensitive messages and a long one for receipts.
  • Treat the token as personal data: store it per user, remove it on logout and when receipts say it is dead.
  • Never rely on a notification arriving. Always let the app fetch the truth when it opens.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A notification arrives while your app is in the foreground and you have not set a notification handler. What is the default behavior?

    In the foreground the OS leaves the decision to the app. Without a handler configured, no banner appears.
  2. 2. Why does the permission code create an Android channel before asking for permission?

    Every Android notification belongs to a channel, and the runtime permission prompt is tied to having created one.
  3. 3. What is the main purpose of a TTL on a push message?

    TTL (time to live) tells the delivery network how long to keep trying. Time-sensitive messages should have a short one.
  4. 4. How do you carry the screen to open from a notification to the moment the user taps it?

    The data object travels with the notification, and the tap listener reads it from response.notification.request.content.data.

Summary

  • Local notifications are scheduled by the app; remote notifications start on a server and travel through APNs or FCM, addressed by a push token.
  • Ask for permission in context. Android needs a channel first, and Android 13+ shows a runtime prompt.
  • In the foreground, a handler decides whether to show a banner; in the background the OS shows it.
  • Listeners fire on arrival and on tap. Carry routing information in a small data object and remove listeners on cleanup.
  • Use TTLs, clean up dead tokens, and never put secrets in the body.
  • Real pushes need a physical device and, on Android, usually a development build.

Next, see what to do when JavaScript is not enough in Native Modules, Expo Modules and Config Plugins.