DEV Community

Fiston Emmanuel
Fiston Emmanuel

Posted on • Edited on

1

Cloud Push Notification Service with Expo

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/

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;
}

Enter fullscreen mode Exit fullscreen mode

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.

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",
    }),
  });
}

Enter fullscreen mode Exit fullscreen mode

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

// 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.."
);

Enter fullscreen mode Exit fullscreen mode

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay