Cloud Push Notification Service with Expo
Tags: reactnative, expo, pushnotifications
Published: 2023-02-23 11:59:47

---
title: Cloud Push Notification Service with Expo
published: true
description: Cloud Push Notification Service with Expo
tags: reactnative,expo,pushnotifications
#cover_image:https://cdn.hashnode.com/res/hashnode/image/upload/v1685308208129/59fe7f77-05a3-464e-a250-a94a0e3a258c.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-02-23 10:55 +0000
---

Engaging users with notifications after they install an app is important for increasing app retention, reducing churn rate, and communicating with users for new offers, announcements, and more.

Google offers cloud notification service through  Firebase Cloud Messaging(FCM) on Android devices and  Apple Push Notification service (APNs)  for iOS devices.

While you are building with Expo, you don't have direct access to those tools and infrastructure provided by mobile OS vendors.

In this article, we will build our own cloud notification service for the Expo app to be used internally by the marketing or sale team.


### Subscribe and collect device notification push token.

To receive notifications, the app must collect a device push notification token which is unique for each device, and save it in the database to be used later.

Expo offers a package to collect those push tokens - https://docs.expo.dev/versions/latest/sdk/notifications/

```js
import { useState, useEffect, useRef } from "react";
import { Text, View, Button, Platform } from "react-native";
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";

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

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState("");
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    registerForPushNotificationsAsync().then((pushToken) => {
      // Save notification push token on your  database to be used later..

      setExpoPushToken(pushToken);
    });

    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log(response);
      });

    return () => {
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return (
    <View
      style={{
        flex: 1,
        alignItems: "center",
        justifyContent: "space-around",
      }}
    >
      <Text>Your expo push token: {expoPushToken}</Text>
    </View>
  );
}

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === "android") {
    await Notifications.setNotificationChannelAsync("default", {
      name: "default",
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: "#FF231F7C",
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } =
      await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== "granted") {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== "granted") {
      alert("Failed to get push token for push notification!");
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert("Must use physical device for Push Notifications");
  }

  return token;
}

```

### Push notification to subscribed users

Once the user subscribed and the app collects a push token, we can send a notification to those users.


Expo offers Expo's Push API service which is built on top of  Google and Apple's own notification services.

```js
function sendNotification(pushToken, title, body) {
  fetch("https://exp.host/--/api/v2/push/send", {
    method: "POST",
    body: JSON.stringify({
      to: tokenToSend,
      sound: "default",
      title: title,
      body: body,
      data: { title, body },
      channelId: "default",
    }),
  });
}

```

We can use `sendNotification` function  to push various types of notifications to target users.


```js
// Promotion notifications
sendNotification(
  "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "Black Friday 25% OFF",
  "Exclusive for you until Monday"
);

// Event notifications
sendNotification(
  "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "Account upgaraded",
  "You are now eligible for premium features.."
);

```

You can build your dashboard where the marketing team member writes the notification title and body, and select target users to receive that notification or any other automated notification solution.

### Further Reading :

Expo Push Service - https://docs.expo.dev/push-notifications/sending-notifications/

Google Cloud Messaging (FCM) - https://firebase.google.com/docs/cloud-messaging/

 Apple Push Notification service (APNs - https://developer.apple.com/documentation/usernotifications/registering_your_app_with_apns