# Push Notifications — React Native

Source: https://www.skillbyai.com/en/react-native/v-push

> Reaching users when the app is closed.

## Tokens, services and handlers

Push notifications are delivered by the platform services: **APNs** for iOS and **Firebase Cloud Messaging (FCM)** for Android. The app asks for notification permission (required on iOS, and on Android 13 and later), then obtains a **device push token** that your server stores per user and device. The **Expo push service** offers a single API that forwards to APNs and FCM using an Expo push token from `expo-notifications`; you can also call APNs and FCM directly. In the app you set a notification handler for foreground display, and listen for responses when a user taps a notification so you can navigate to the right screen. Push generally does not work in simulators the same way as on devices, and Expo Go has limitations, so test with a development build on real devices.

## Registering for push with expo-notifications

A sketch based on the Expo docs; check them for your SDK version.

```typescript
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
import Constants from "expo-constants";

export async function registerForPush(): Promise<string | null> {
  if (!Device.isDevice) return null;   // use a physical device

  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== "granted") return null;

  const projectId = Constants.expoConfig?.extra?.eas?.projectId;
  const { data: token } = await Notifications.getExpoPushTokenAsync({ projectId });

  await fetch("https://api.example.com/push-tokens", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ token }),
  });
  return token;
}

// navigate when the user taps a notification
Notifications.addNotificationResponseReceivedListener((response) => {
  const url = response.notification.request.content.data?.url;
  // router.push(url) after validating it
});
```

## Tokens change

Push tokens can change after reinstalls or restores. Re-register on app start, update the server, and delete tokens the push service reports as invalid.

**Quiz:** Which service delivers push notifications to iOS devices?

- [ ] The Metro bundler
- [ ] Firebase Hosting
- [x] Apple Push Notification service (APNs)
- [ ] AsyncStorage

*Answer:* Apple Push Notification service (APNs). Android uses FCM; iOS uses APNs.
