Using Expo's Push Notification API
Push notifications are a powerful way to engage users and keep them updated with your app's latest information. Expo provides a straightforward API for implementing push notifications.
Push notifications are a powerful way to engage users and keep them updated with your app's latest information. Expo provides a straightforward API for implementing push notifications in your React Native applications. In this article, we'll explore how to set up and use Expo's Push Notification API.
Prerequisites
Before we begin, make sure you have:
- An Expo account
- A React Native project set up with Expo
Setting Up Push Notifications
- Step 1: Configure app.json
First, we need to configure our app.json
file to include the necessary permissions for push notifications:
{
"expo": {
"name": "Your App Name",
"version": "1.0.0",
"android": {
"useNextNotificationsApi": true
},
"ios": {
"bundleIdentifier": "com.kodaschool.yourappname"
}
}
}
- Step 2: Install Required Packages
Install the expo-notifications
package:
expo install expo-notifications
Try Kodaschool for free
Click below to sign up and get access to free web, android and iOs challenges.
Implementing Push Notifications
- Step 1: Request Notification Permissions
We need to request permission from the user to send push notifications. Add the following code to your main App component:
import React, { useEffect } from 'react';
import { Text, View } from 'react-native';
import * as Notifications from 'expo-notifications';
export default function App() {
useEffect(() => {
registerForPushNotificationsAsync();
}, []);
async function registerForPushNotificationsAsync() {
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;
}
const token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Push Notifications Demo</Text>
</View>
);
}
This code requests permission to send notifications and retrieves the Expo push token, which you'll need to send notifications to this device.
- Step 2: Handle Incoming Notifications
To handle incoming notifications, we need to set up a notification handler:
import React, { useEffect } from 'react';
import { Text, View } from 'react-native';
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
export default function App() {
useEffect(() => {
const subscription = Notifications.addNotificationReceivedListener(notification => {
console.log('Notification received:', notification);
});
return () => subscription.remove();
}, []);
// ... rest of the component
}
This sets up a handler for incoming notifications and logs them to the console.
- Step 3: Sending a Test Notification
To test our setup, we can use the Expo push notification tool. Go to https://expo.dev/notifications and enter your Expo push token.
You can send a test notification with the following payload:
{
"to": "YOUR_EXPO_PUSH_TOKEN",
"sound": "default",
"title": "Test Notification",
"body": "This is a test notification from Expo!"
}
- Step 4: Handling Notification Taps
To handle what happens when a user taps on a notification, add the following code:
import React, { useEffect, useRef } from 'react';
import { Text, View } from 'react-native';
import * as Notifications from 'expo-notifications';
export default function App() {
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => {
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
console.log('Notification received:', notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log('Notification tapped:', response);
// Handle the notification tap here
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
// ... rest of the component
}
This code sets up listeners for both receiving notifications and handling notification taps.
Best Practices
- Token Storage: Store the Expo push token securely on your server to send notifications to specific devices.
- Error Handling: Implement proper error handling for cases where permissions are denied or token retrieval fails.
- Customization: Use the
Notifications.setNotificationHandler
to customize how notifications are presented to the user. - Testing: Test your notifications thoroughly on both iOS and Android devices.
- Server-side Implementation: Implement a server-side solution to send notifications. You can use Expo's push notification service or implement your own using Firebase Cloud Messaging (FCM) or Apple Push Notification service (APNs).
Implementing push notifications in your Expo-based React Native app is straightforward with the Expo Push Notifications API. By following these steps, you can keep your users engaged and informed about important updates in your app.
Remember to respect your users' preferences and provide value with each notification you send. Overusing push notifications can lead to users disabling them or uninstalling your app.
As you continue to develop your app, explore more advanced features like scheduling notifications, setting badges, and implementing rich notifications with images or actions.