Push notifications are a great way to keep users engaged in your app. Whether you're sending order updates, chat messages, or general alerts, they help users stay informed. In this guide, I'll show you how to integrate push notifications in a React Native app using Expo and Firebase Cloud Messaging (FCM).
Setting Up an Expo Project
First, install Expo CLI if you haven’t already:
npm install -g expo-cli
Now, create a new Expo project:
expo init MyPushApp
cd MyPushApp
Next, install the necessary dependencies:
npx expo install expo-notifications expo-device expo-application
These packages handle push notifications, device identification, and permissions.
Configuring Firebase Cloud Messaging (FCM)
Expo requires Firebase Cloud Messaging (FCM) for push notifications on Android. Follow these steps:
- Go to Firebase Console and create a new project.
- Enable Cloud Messaging in your project settings.
- Add an Android app and set the package name (e.g.,
com.myapp.pushnotifications
). - Download the
google-services.json
file and place it insideandroid/app/
.
Now, install Firebase in your project:
npm install firebase
Create a Firebase configuration file:
// firebaseConfig.js
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "yourproject.firebaseapp.com",
projectId: "yourproject",
storageBucket: "yourproject.appspot.com",
messagingSenderId: "your-messaging-id",
appId: "your-app-id",
};
export const firebaseApp = initializeApp(firebaseConfig);
Replace the placeholder values with your Firebase credentials.
Requesting Notification Permissions
Before sending notifications, ask the user for permission. Add this to App.js
:
import { useEffect, useState } from "react";
import { View, Text, Button } from "react-native";
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
export default function App() {
const [pushToken, setPushToken] = useState("");
useEffect(() => {
getPushToken();
const listener = Notifications.addNotificationReceivedListener((notification) => {
console.log("Received notification:", notification);
});
return () => listener.remove();
}, []);
async function getPushToken() {
if (!Device.isDevice) {
alert("Push notifications only work on physical devices.");
return;
}
const { status } = await Notifications.getPermissionsAsync();
if (status !== "granted") {
const { status: newStatus } = await Notifications.requestPermissionsAsync();
if (newStatus !== "granted") {
alert("Permission denied!");
return;
}
}
const token = (await Notifications.getExpoPushTokenAsync()).data;
setPushToken(token);
console.log("Expo Push Token:", token);
}
return (
<View style={{ marginTop: 50, padding: 20 }}>
<Text>Push Notifications Setup</Text>
<Button
title="Send Test Notification"
onPress={() => {
Notifications.scheduleNotificationAsync({
content: {
title: "Hello!",
body: "This is a test notification.",
},
trigger: null,
});
}}
/>
</View>
);
}
Sending Push Notifications
To send a notification, use Expo’s API. Create a file send.js
:
const fetch = require("node-fetch");
async function sendNotification() {
const message = {
to: "ExponentPushToken[your-token-here]",
sound: "default",
title: "Notification Title",
body: "This is a test notification!",
};
await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(message),
});
}
sendNotification();
Run the script with:
node send.js
Your phone should receive the notification.
Using Firebase to Send Notifications
For an alternative method, use Firebase Cloud Messaging (FCM). First, get your Server Key from Firebase settings.
Then, send a test notification using cURL:
curl -X POST "https://fcm.googleapis.com/fcm/send" -H "Authorization: key=YOUR_SERVER_KEY" -H "Content-Type: application/json" -d '{"to": "ExponentPushToken[your-token-here]", "notification": {"title": "Hello!", "body": "Sent via Firebase!"}}'
If successful, Firebase will return { "success": 1 }
.
Conclusion
That’s it! You’ve set up push notifications in React Native with Expo using both Expo’s API and Firebase Cloud Messaging.
Next steps:
- Handle notifications in the background.
- Implement scheduled notifications.
- Use Firebase Cloud Functions for automated notifications.
Let me know if you run into any issues! 🚀