Notifications

Article · 3:00

Local alerts you schedule yourself, and remote push through Expo or FCM - plus the three app states that change everything.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

A local notification is scheduled by your app and delivered by the operating system - a reminder, a timer, a streak nudge. It needs permission but no server, and it works offline.

A remote push starts on your server. The device registers and gets a token, you store it, and your server sends to it. Expo's push service takes one token format and talks to both APNs and FCM for you, which removes a large amount of per-platform setup; sending directly through FCM is the alternative when you need the control.

The detail that catches people is that behaviour depends on the app's state. In the foreground, nothing is shown unless you say so - you set a handler deciding whether to display a banner. In the background, the system shows it and your code runs only if the reader taps. Terminated is the hardest case: your app is not running, and the tap launches it with the notification attached, which you must read during startup rather than in a listener that has not been registered yet.

Push notifications do not work on a simulator. You need a real device and, on iOS, a paid developer account to generate the APNs key.

TS Example 1 57 lines
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import { useEffect, useRef } from 'react';
import { router } from 'expo-router';

// Foreground behaviour is YOUR decision. Without this, nothing shows.
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowBanner: true,
    shouldPlaySound: false,
    shouldSetBadge: true,
  }),
});

export async function registerForPush(): Promise<string | null> {
  // A simulator will never receive a remote push.
  if (!Device.isDevice) return null;

  const existing = await Notifications.getPermissionsAsync();
  let status = existing.status;
  if (status !== 'granted') {
    status = (await Notifications.requestPermissionsAsync()).status;
  }
  if (status !== 'granted') return null;

  const token = await Notifications.getExpoPushTokenAsync();
  return token.data;        // send this to your server
}

export function useNotificationRouting() {
  const listener = useRef<Notifications.Subscription>();

  useEffect(() => {
    // TERMINATED: the tap launched the app. Read it at startup - no
    // listener was registered in time to catch it.
    Notifications.getLastNotificationResponseAsync().then((response) => {
      const id = response?.notification.request.content.data?.articleId;
      if (id) router.push(`/article/${id}`);
    });

    // BACKGROUND or FOREGROUND: the tap arrives here.
    listener.current = Notifications.addNotificationResponseReceivedListener((response) => {
      const id = response.notification.request.content.data?.articleId;
      if (id) router.push(`/article/${id}`);
    });

    return () => listener.current?.remove();
  }, []);
}

// A local one needs no server at all.
export async function remindInAnHour() {
  await Notifications.scheduleNotificationAsync({
    content: { title: 'Still reading?', body: 'Your article is waiting.' },
    trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 3600 },
  });
}

Open this example in the editor and change it. Nothing you type is saved.