Adding Push Notifications in Expo Apps
Introduction
Push notifications increase user engagement by delivering timely updates directly to devices. This guide walks through setting up Expo Push Notifications, including client and server code.
Prerequisites
- Expo project
- Expo CLI
- Basic backend server knowledge
Step 1: Install Dependencies
expo install expo-notifications
npm install axios
Step 2: Configure Notification Handling
Update App.js
:
import React, { useEffect, useRef, useState } from "react";
import { Text, View, Button, Platform } from "react-native";
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
import axios from "axios";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
export default function App() {
const [expoPushToken, setExpoPushToken] = useState("");
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
notificationListener.current =
Notifications.addNotificationReceivedListener(notification => {
console.log("Notification received:", notification);
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener(response => {
console.log("Notification response:", response);
});
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return (
<View className="flex-1 items-center justify-center">
<Text>Your token: {expoPushToken}</Text>
<Button
title="Send Test Notification"
onPress={async () => {
await axios.post("https://your-server.com/send-notification", {
token: expoPushToken,
title: "Test",
body: "This is a test notification",
});
}}
/>
</View>
);
}
async function registerForPushNotificationsAsync() {
let token;
if (Constants.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");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
Step 3: Server Endpoint to Send Notifications
Example Node.js/Express server:
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.json());
app.post("/send-notification", async (req, res) => {
const { token, title, body } = req.body;
try {
await axios.post("https://exp.host/--/api/v2/push/send", {
to: token,
sound: "default",
title,
body,
data: { customData: "info" },
});
res.json({ success: true });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to send notification" });
}
});
app.listen(3000, () => console.log("Server running on port 3000"));
Summary
With Expo Notifications, you can register devices, handle incoming notifications, and send pushes from your server for enhanced user engagement.