Push Notifications — Mobile

Push Notifications di Mobile Push notification adalah cara utama re-engage user di mobile app. Ada dua layer: local notification (diatur oleh app sendiri) dan r

Push Notifications di Mobile

Push notification adalah cara utama re-engage user di mobile app. Ada dua layer: local notification (diatur oleh app sendiri) dan remote/push notification (dikirim dari server via APNS/FCM).

Setup dengan Expo Notifications

# Install
npx expo install expo-notifications expo-device expo-constants

// app.json config
{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "icon": "./assets/notification-icon.png",
          "color": "#ffffff"
        }
      ]
    ]
  }
}

Request Permission & Get Token

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

async function registerForPushNotifications() {
  // Push notification hanya bisa di device fisik
  if (!Device.isDevice) {
    alert('Push notifications require a physical device');
    return;
  }

  // Request permission
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }

  if (finalStatus !== 'granted') {
    alert('Permission not granted');
    return;
  }

  // Get Expo Push Token
  const token = await Notifications.getExpoPushTokenAsync({
    projectId: Constants.expoConfig?.extra?.eas?.projectId,
  });

  console.log('Push token:', token.data);
  // Kirim token ini ke backend kamu
  await sendTokenToServer(token.data);
}

Handle Incoming Notifications

import { useEffect, useRef } from 'react';

export default function App() {
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    // Notifikasi diterima saat app foreground
    notificationListener.current =
      Notifications.addNotificationReceivedListener(notification => {
        console.log('Received:', notification);
      });

    // User tap notifikasi
    responseListener.current =
      Notifications.addNotificationResponseReceivedListener(response => {
        const data = response.notification.request.content.data;
        // Navigate ke screen yang sesuai
        router.push(data.screen);
      });

    return () => {
      notificationListener.current?.remove();
      responseListener.current?.remove();
    };
  }, []);
}

Kirim dari Backend

// Backend (Node.js / Laravel / any)
// POST ke Expo Push API
const message = {
  to: 'ExponentPushToken[xxxx]',
  sound: 'default',
  title: 'Pesanan Dikirim!',
  body: 'Paket kamu sedang dalam perjalanan.',
  data: { screen: '/orders/123', orderId: 123 },
};

await fetch('https://exp.host/--/api/v2/push/send', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(message),
});

Push Notification Flow

Yang akan kamu pelajari