
Expo, part 4: push notifications — expo-notifications, FCM V1, APNs, and privacy
🌐 Machine-translated from Russian. Show original
In this part:
How delivery is arranged#
Ваш сервер ──► Expo Push API ──► FCM (Android) / APNs (iOS) ──► телефон
▲ │
└──────────── приложение регистрирует Expo push-токен ◄────────┘
- The app requests permission and receives an Expo push token in the form
ExponentPushToken[...]. - Sends the token to your server (
POST /api/m/push). - The server sends a request to the Expo Push API during the event, and Expo forwards it to Firebase Cloud Messaging or the Apple Push Notification service.
Plus Expo Push — one API and one token format for both platforms. FCM and APNs keys are stored in EAS, not in your code.
Step 1. Module and plugin#
npx expo install expo-notifications expo-constants
"plugins": [
["expo-notifications", { "icon": "./assets/notification-icon.png", "color": "#2347B5" }]
]
The notification icon on Android is a white silhouette on a transparent background (PNG), and the colored image will turn into a white square.
Step 2. Android: FCM V1#
Without this, the app works, but the Android token is not issued.
- Firebase Console → project (can be a separate app for the app) → Add app → Android, package =
android.packagefrom app.json → downloadgoogle-services.jsonto the root of the project. - In app.json:
"android": { "googleServicesFile": "./google-services.json" }
google-services.json contains only public project identifiers — it can be stored in the repository.
- Firebase → Project settings → Service accounts → Generate new private key — the JSON key of the service account is downloaded. This is a secret: do not put it in the repository (add it to
.gitignore), do not forward it via messengers. - Upload the key to the EAS in one of the following ways:
eas credentials→ Android → production → Google Service Account → Manage your Google Service Account Key for Push Notifications (FCM V1) → Upload a new service account key;- or on expo.dev: Project settings → Credentials → Android → FCM V1 service account key → Add.
After downloading, the key can be deleted from the disk: the copy is stored in EAS.
Step 3. iOS: APNs#
A paid Apple Developer account is required. During the first buildeas build -p ios the EAS CLI will prompt you to enable push and generate the APNs key — agree, the key will be saved in EAS. If you are not building through EAS — eas credentials manually.
Step 4. Receiving the token in the app#
import { Platform } from 'react-native';
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';
async function deviceToken(ask: boolean): Promise<string | null> {
if (Platform.OS === 'web') return null;
const perm = await Notifications.getPermissionsAsync();
const granted = perm.granted || (ask && (await Notifications.requestPermissionsAsync()).granted);
if (!granted) return null;
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('messages', {
name: 'Личные сообщения',
importance: Notifications.AndroidImportance.HIGH,
});
}
const projectId = Constants.expoConfig?.extra?.eas?.projectId ?? Constants.easConfig?.projectId;
if (!projectId) return null;
const { data } = await Notifications.getExpoPushTokenAsync({ projectId });
return data;
}
export async function registerPush(ask = true) {
const token = await deviceToken(ask).catch(() => null);
if (!token) return false;
await api('/api/m/push', { json: { token, platform: Platform.OS } });
return true;
}
- Android channel (
messages) — the user can adjust the sound and importance in the system settings. The server specifies the samechannelId. - projectId — project ID on expo.dev. The token is tied to the project, so each application must have its own project (more details in part 5).
- We ask for permission after logging in (
ask = trueinsignIn), and at regular launch, we only quietly update the token (ask = false). People more often reject requests on the very first screen. - In the app settings — notification toggle: turning off causes
DELETE /api/m/push.
Step 5. Notification when the app is open and tapping#
let activeConversation: string | null = null; // диалог, открытый на экране
Notifications.setNotificationHandler({
handleNotification: async (n) => {
const here = (n.request.content.data as { conversationId?: string } | undefined)?.conversationId === activeConversation;
return { shouldShowBanner: !here, shouldShowList: !here, shouldPlaySound: !here, shouldSetBadge: true };
},
});
If a person is already watching this dialogue, the banner is not shown.
Clicking on the notification opens a dialog. Check the data from the notification before using it in navigation:
const open = (data: unknown) => {
const id = (data as { conversationId?: string } | undefined)?.conversationId;
if (id && /^[a-z0-9]{20,40}$/.test(id)) router.push({ pathname: '/chat/[id]', params: { id } });
};
const sub = Notifications.addNotificationResponseReceivedListener((r) => open(r.notification.request.content.data));
const last = Notifications.getLastNotificationResponse(); // приложение запущено нажатием на уведомление
if (last) open(last.notification.request.content.data);
Step 6. Sending from the server#
const ENDPOINT = 'https://exp.host/--/api/v2/push/send';
export async function sendPush(devices: { id: string; token: string }[], msg: { title: string; body: string; data: Record<string, string> }) {
const headers: Record<string, string> = { 'content-type': 'application/json', accept: 'application/json' };
// токен доступа нужен, только если в проекте expo.dev включена защита отправки push
if (process.env.EXPO_ACCESS_TOKEN) headers.authorization = `Bearer ${process.env.EXPO_ACCESS_TOKEN}`;
const payload = devices.map((d) => ({
to: d.token, title: msg.title, body: msg.body, data: msg.data,
sound: 'default', channelId: 'messages', priority: 'high',
}));
const r = await fetch(ENDPOINT, { method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(8000) });
const tickets = ((await r.json()) as { data?: { details?: { error?: string } }[] }).data ?? [];
// приложение удалено или токен отозван — убираем устройство из базы
const dead = devices.filter((_, i) => tickets[i]?.details?.error === 'DeviceNotRegistered').map((d) => d.id);
await removeDevices(dead);
}
- The response (tickets) arrives immediately and indicates whether Expo has accepted the notification. The final delivery result to FCM/APNs is in receipts: they can be requested later via
/--/api/v2/push/getReceiptsby ID from tickets. For large volumes, receipt processing is mandatory. - Enable push protection by access token in the project settings for expo.dev — then only your server can send notifications to your tokens. The token is in the server environment variable, not in the code.
- Send in batches and not more often than reason: Expo has limits on request frequency.
Privacy: no text in push#
The notification goes through Expo, Google, or Apple servers and is displayed on the lock screen. Therefore, in the Kommit Chat":
- the notification has neither the sender's name nor the text — only "New Private Message" and the dialog id in
data; - the application downloads the text itself from our server after opening — the correspondence does not leave the server in Kazakhstan (see the series "Clouds in Kazakhstan");
- Push is sent only if the message hasn't been read for 8 seconds (the person may already be sitting in the site chat), and no more than once a minute for one dialogue — no "machine gun" from notifications.
This rule applies to any applications with personal data: HR, healthcare, finance. In push — "new is available," details — after login.
Debugging#
- push is checked only on the development build or release build, not in Expo Go on Android;
- test submission — the expo.dev/notifications tool: insert the token and send;
- does not arrive on Android — check if the FCM V1 key is loaded and if the package in Firebase matches
android.package; - comes without sound — the channel is created with low importance; only the user changes the importance of the channel after creation, so for the new importance, a new channel with a different ID is created.
Push checklist#
- FCM V1:
google-services.jsonin the project, service account key only in EAS - APNs key created via EAS
- Permission is requested at a clear moment, there is a toggle in the settings
- Android channel with the necessary importance, white notification icon
- Data from the notification is checked before navigation
- Dead tokens are deleted, receipts are processed
- The notification contains no personal data or message text
- Push protection by access token is enabled
Next — builds: Expo, part 5: builds in EAS — profiles, APK and AAB, signature keys, one project per app, and over-the-air updates.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.