Mobile development · Intermediate · 26 min
Remind Larkfield patients with local and push notifications in Expo
By Padding · Updated 18 Nov 2026
Expo SDK 58 · expo-notifications 58.1 · Node.js 26
You will have the Larkfield app schedule reminders 24 hours and 2 hours before each appointment, ask for notification permission only after a booking, cancel reminders with the booking, open the right appointment from a tap, and receive server-sent messages through the Expo push service.
On this page
A clinic loses time and money on missed appointments, and a reminder at the right moment is one of the cheapest fixes. This part of the series gives the Larkfield app two kinds of notification. Local notifications are scheduled on the phone itself: the app books an appointment, then asks the operating system to show a message 24 hours and 2 hours before it. They need no server and no data connection when they fire. Push notifications are sent by a server, through Apple's and Google's push services, for messages the phone cannot know in advance, such as "Dr Okafor is running 20 minutes late".
Local reminders carry most of the weight here, on purpose. Many Larkfield patients use prepaid data that runs out, or keep mobile data off to save it. A reminder scheduled at booking time still appears when the phone is offline. Push is the extra channel for news that changes on the day.
You use expo-notifications 58.1 throughout. Every scheduling decision lives in small functions that Jest tests with the native module mocked, so you can check the times, the cancellation and the Android channel without a phone.
Step 1 · Install expo-notifications and add its config plugin
Install the library and expo-constants, which the push step uses to read your EAS project ID. npx expo install picks the versions that match SDK 58:
cd ~/larkfield-app-demo
npx expo install expo-notifications expo-constantsexpo-notifications ships a config plugin. It writes the native settings a build needs: the Android notification icon and colour, the iOS push entitlement, and the default Android channel for push messages that do not name one. Add it to app.json with the channel you are about to create. This small Node script edits the file the same way whatever else it holds, and replaces any earlier expo-notifications entry:
node -e '
const fs = require("fs")
const app = JSON.parse(fs.readFileSync("app.json", "utf8"))
const others = (app.expo.plugins ?? []).filter((p) => (Array.isArray(p) ? p[0] : p) !== "expo-notifications")
app.expo.plugins = [...others, ["expo-notifications", { defaultChannel: "appointment-reminders" }]]
fs.writeFileSync("app.json", JSON.stringify(app, null, 2) + "\n")
'Config plugins only run when native projects are generated, so this change takes effect in your next development build, not in a running app.
Check it worked
Ask Expo for the resolved configuration and print the notifications entry:
npx expo config --type prebuild --json | node -e 'let s = ""; process.stdin.on("data", (d) => (s += d)).on("end", () => console.log(JSON.stringify(JSON.parse(s).plugins.filter((p) => JSON.stringify(p).includes("expo-notifications")))))'The output is [["expo-notifications",{"defaultChannel":"appointment-reminders"}]]. package.json now lists expo-notifications at ~58.1.10 or a later 58.1 patch.
Step 2 · Plan and schedule the two reminders
Keep the arithmetic apart from the native calls. planReminders is a plain function: it takes an appointment and the current time, and returns the reminders that are still in the future. scheduleReminders hands those to the operating system.
Three decisions are built in:
- Each reminder gets a fixed identifier,
appointment-42-24handappointment-42-2h. You never need to store the IDs the system hands back, because you can always rebuild them from the appointment ID. Scheduling twice replaces the old reminders instead of stacking duplicates. - The trigger is a date trigger with an absolute moment in time.
startsAtis an ISO 8601 string with a time zone, so a patient who travels between Lagos and Nairobi still gets the reminder 2 hours before, not 2 hours off. - The text says who and when, never why. A notification shows on the lock screen, where anyone holding the phone can read it. "Your appointment with Dr Amina Okafor is tomorrow" is fine; the reason for the visit is not.
Create src/notifications/reminders.ts:
mkdir -p src/notifications/__tests__
cat > src/notifications/reminders.ts <<'TS'
import * as Notifications from 'expo-notifications'
import { Platform } from 'react-native'
export const REMINDER_CHANNEL_ID = 'appointment-reminders'
export type ReminderAppointment = {
id: string
startsAt: string // ISO 8601 with a time zone, such as 2026-12-03T10:30:00Z
practitionerName: string
}
export type PlannedReminder = {
identifier: string
date: Date
title: string
body: string
url: string
}
const HOUR = 60 * 60 * 1000
const OFFSETS = [
{ key: '24h', before: 24 * HOUR, when: 'tomorrow' },
{ key: '2h', before: 2 * HOUR, when: 'in 2 hours' },
] as const
export function reminderIdentifier(appointmentId: string, key: string) {
return `appointment-${appointmentId}-${key}`
}
export function planReminders(appointment: ReminderAppointment, now = new Date()): PlannedReminder[] {
const start = new Date(appointment.startsAt)
if (Number.isNaN(start.getTime())) throw new Error(`Bad appointment time: ${appointment.startsAt}`)
const time = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(start)
return OFFSETS.map((offset) => ({
identifier: reminderIdentifier(appointment.id, offset.key),
date: new Date(start.getTime() - offset.before),
title: 'Larkfield Clinic',
body: `Your appointment with ${appointment.practitionerName} is ${offset.when}, at ${time}.`,
url: `/appointments/${appointment.id}`,
})).filter((reminder) => reminder.date.getTime() > now.getTime() + 60_000)
}
export async function ensureReminderChannel(os: string = Platform.OS) {
if (os !== 'android') return
await Notifications.setNotificationChannelAsync(REMINDER_CHANNEL_ID, {
name: 'Appointment reminders',
description: 'The day before and 2 hours before a Larkfield appointment',
importance: Notifications.AndroidImportance.HIGH,
})
}
export async function cancelReminders(appointmentId: string) {
await Promise.all(
OFFSETS.map((offset) =>
Notifications.cancelScheduledNotificationAsync(reminderIdentifier(appointmentId, offset.key)),
),
)
}
export async function scheduleReminders(appointment: ReminderAppointment, now = new Date()) {
await ensureReminderChannel()
await cancelReminders(appointment.id)
const plans = planReminders(appointment, now)
for (const plan of plans) {
await Notifications.scheduleNotificationAsync({
identifier: plan.identifier,
content: { title: plan.title, body: plan.body, data: { url: plan.url } },
trigger: {
type: Notifications.SchedulableTriggerInputTypes.DATE,
date: plan.date,
channelId: REMINDER_CHANNEL_ID,
},
})
}
return plans.map((plan) => plan.identifier)
}
export function appointmentPathFrom(data: unknown): string | null {
const url = (data as { url?: unknown } | null | undefined)?.url
if (typeof url !== 'string') return null
return /^\/appointments\/[A-Za-z0-9-]+$/.test(url) ? url : null
}
TSOn Android 8 and later every notification belongs to a channel, which the patient can switch off or make silent in the system settings without turning off the whole app. ensureReminderChannel creates "Appointment reminders" with high importance, so the reminder can appear as a heads-up banner. Once a channel exists, your code can rename it but cannot raise its importance: the patient's choice wins. Pick the importance before the first release. On iOS there are no channels, so the function returns early. appointmentPathFrom is used in a later step to decide which screen a tap opens.
Now the tests. They replace expo-notifications with Jest mock functions, so they check what your code asks the system to do:
cat > src/notifications/__tests__/reminders.test.ts <<'TS'
import * as Notifications from 'expo-notifications'
import {
REMINDER_CHANNEL_ID,
appointmentPathFrom,
cancelReminders,
ensureReminderChannel,
planReminders,
scheduleReminders,
} from '../reminders'
jest.mock('expo-notifications', () => ({
scheduleNotificationAsync: jest.fn(async () => 'scheduled'),
cancelScheduledNotificationAsync: jest.fn(async () => undefined),
setNotificationChannelAsync: jest.fn(async () => null),
SchedulableTriggerInputTypes: { DATE: 'date' },
AndroidImportance: { HIGH: 6 },
}))
const now = new Date('2026-12-01T08:00:00Z')
const appointment = { id: '42', startsAt: '2026-12-03T10:30:00Z', practitionerName: 'Dr Amina Okafor' }
beforeEach(() => jest.clearAllMocks())
test('plans reminders 24 hours and 2 hours before the appointment', () => {
const plans = planReminders(appointment, now)
expect(plans.map((p) => p.identifier)).toEqual(['appointment-42-24h', 'appointment-42-2h'])
expect(plans.map((p) => p.date.toISOString())).toEqual([
'2026-12-02T10:30:00.000Z',
'2026-12-03T08:30:00.000Z',
])
expect(plans[0].url).toBe('/appointments/42')
})
test('skips reminders whose time has already passed', () => {
const inFiveHours = planReminders({ ...appointment, startsAt: '2026-12-01T13:00:00Z' }, now)
expect(inFiveHours.map((p) => p.identifier)).toEqual(['appointment-42-2h'])
expect(planReminders({ ...appointment, startsAt: '2026-12-01T09:00:00Z' }, now)).toEqual([])
})
test('names the practitioner and the day, nothing more', () => {
const [first] = planReminders(appointment, now)
expect(first.body).toContain('Dr Amina Okafor')
expect(first.body).toContain('tomorrow')
})
test('schedules date triggers on the reminders channel after clearing old ones', async () => {
await scheduleReminders(appointment, now)
const cancel = jest.mocked(Notifications.cancelScheduledNotificationAsync)
const schedule = jest.mocked(Notifications.scheduleNotificationAsync)
expect(cancel).toHaveBeenCalledWith('appointment-42-24h')
expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(schedule.mock.invocationCallOrder[0])
expect(schedule).toHaveBeenCalledTimes(2)
const first = schedule.mock.calls[0][0]
expect(first.identifier).toBe('appointment-42-24h')
expect(first.trigger).toEqual({
type: 'date',
date: new Date('2026-12-02T10:30:00Z'),
channelId: REMINDER_CHANNEL_ID,
})
expect(first.content.data).toEqual({ url: '/appointments/42' })
})
test('cancel removes both reminders for one appointment', async () => {
await cancelReminders('42')
expect(jest.mocked(Notifications.cancelScheduledNotificationAsync).mock.calls).toEqual([
['appointment-42-24h'],
['appointment-42-2h'],
])
})
test('creates the Android channel with high importance, and nothing on iOS', async () => {
await ensureReminderChannel('android')
expect(Notifications.setNotificationChannelAsync).toHaveBeenCalledWith(
'appointment-reminders',
expect.objectContaining({ name: 'Appointment reminders', importance: 6 }),
)
jest.clearAllMocks()
await ensureReminderChannel('ios')
expect(Notifications.setNotificationChannelAsync).not.toHaveBeenCalled()
})
test('only opens appointment screens from notification data', () => {
expect(appointmentPathFrom({ url: '/appointments/42' })).toBe('/appointments/42')
expect(appointmentPathFrom({ url: 'https://example.com/login' })).toBeNull()
expect(appointmentPathFrom({ url: '/appointments/../profile' })).toBeNull()
expect(appointmentPathFrom(undefined)).toBeNull()
})
TSCheck it worked
npx jest src/notifications --ciJest reports Tests: 7 passed, 7 total. If the date test fails by a whole number of hours, check that startsAt in your data carries a time zone (Z or +01:00): a string without one is read as the phone's local time.
Step 3 · Ask for permission after the booking, not on first launch
iOS shows the system permission prompt once. If the patient taps "Don't Allow", the app cannot ask again; only the Settings app can change it. Android 13 and later work the same way after a refusal or two. So ask at the moment the request makes sense to the patient: straight after they book, with a sentence that says what they get. A prompt on first launch, before the app has done anything useful, is the one most people refuse.
There is an Android detail too. On Android 13 the system prompt does not appear until the app has created at least one notification channel, so the permission function creates the channel first.
Create src/notifications/permission.ts:
cat > src/notifications/permission.ts <<'TS'
import * as Notifications from 'expo-notifications'
import { ensureReminderChannel } from './reminders'
export async function askForReminderPermission(): Promise<boolean> {
await ensureReminderChannel()
const current = await Notifications.getPermissionsAsync()
if (current.granted) return true
if (!current.canAskAgain) return false
const answer = await Notifications.requestPermissionsAsync()
return answer.granted
}
TSThe card the patient sees comes next. It explains the offer in plain words, asks only when "Remind me" is pressed, and has a way forward if notifications are off: a button to the app's page in system settings. Create src/notifications/ReminderPrompt.tsx:
cat > src/notifications/ReminderPrompt.tsx <<'TSX'
import { useState } from 'react'
import { Linking, Pressable, StyleSheet, Text, View } from 'react-native'
import { askForReminderPermission } from './permission'
import { registerPushToken } from './push'
import { scheduleReminders, type ReminderAppointment } from './reminders'
type State = 'offer' | 'busy' | 'on' | 'off' | 'dismissed'
type Props = { appointment: ReminderAppointment; patientId: string }
export function ReminderPrompt({ appointment, patientId }: Props) {
const [state, setState] = useState<State>('offer')
async function turnOn() {
setState('busy')
const allowed = await askForReminderPermission()
if (!allowed) {
setState('off')
return
}
await scheduleReminders(appointment)
setState('on')
registerPushToken(patientId)
.then((token) => {
if (__DEV__ && token) console.log('Expo push token:', token)
})
.catch((error) => console.warn('Push registration failed', error))
}
if (state === 'dismissed') return null
if (state === 'on') {
return (
<View style={styles.card} accessibilityLiveRegion="polite">
<Text style={styles.text}>Reminders are on: the day before and 2 hours before.</Text>
</View>
)
}
if (state === 'off') {
return (
<View style={styles.card} accessibilityLiveRegion="polite">
<Text style={styles.text}>
Notifications are off for Larkfield. You can turn them on in your phone's settings.
</Text>
<Pressable accessibilityRole="button" onPress={() => Linking.openSettings()} style={styles.secondary}>
<Text style={styles.secondaryText}>Open settings</Text>
</Pressable>
</View>
)
}
return (
<View style={styles.card}>
<Text style={styles.title}>Want a reminder?</Text>
<Text style={styles.text}>
We can remind you the day before and 2 hours before your appointment. Your phone will ask
you to allow notifications.
</Text>
<View style={styles.row}>
<Pressable
accessibilityRole="button"
disabled={state === 'busy'}
onPress={turnOn}
style={styles.primary}
>
<Text style={styles.primaryText}>Remind me</Text>
</Pressable>
<Pressable accessibilityRole="button" onPress={() => setState('dismissed')} style={styles.secondary}>
<Text style={styles.secondaryText}>Not now</Text>
</Pressable>
</View>
</View>
)
}
const styles = StyleSheet.create({
card: { gap: 12, padding: 16, borderRadius: 12, backgroundColor: '#f1f2f4' },
title: { fontSize: 18, fontWeight: '600', color: '#0b0c0e' },
text: { fontSize: 16, color: '#2a2d33' },
row: { flexDirection: 'row', gap: 12 },
primary: { minHeight: 48, justifyContent: 'center', paddingHorizontal: 20, borderRadius: 8, backgroundColor: '#0b0c0e' },
primaryText: { fontSize: 16, color: '#ffffff', fontWeight: '600' },
secondary: { minHeight: 48, justifyContent: 'center', paddingHorizontal: 20 },
secondaryText: { fontSize: 16, color: '#0b0c0e' },
})
TSXThe card imports ./push, which you write in the push step. Create a placeholder now so the app builds, and replace it later:
cat > src/notifications/push.ts <<'TS'
export async function registerPushToken(_patientId: string): Promise<string | null> {
return null
}
TSRender the card where the patient sees the booking they just made. Since part 3, the submit handler on part 2's booking details screen saves the booking and opens the Appointments tab, so put the card on whichever screen your app shows after a booking, under the confirmation text, and add the import at the top of that file. appointment is the booking you just saved, with its id as a string (String(id) for a row from part 3's appointments table), and patientId is the ID your app holds for the patient (demo-patient with part 4's mock API, until the app has sign-in):
import { ReminderPrompt } from '@/notifications/ReminderPrompt'
// inside the screen, under the confirmation message:
<ReminderPrompt appointment={appointment} patientId={patientId} />Now a React Native Testing Library test of the card. It mocks the three modules the card calls, so it tests only the card's decisions:
cat > src/notifications/__tests__/ReminderPrompt.test.tsx <<'TSX'
import { render, screen, userEvent } from '@testing-library/react-native'
import { askForReminderPermission } from '../permission'
import { registerPushToken } from '../push'
import { ReminderPrompt } from '../ReminderPrompt'
import { scheduleReminders } from '../reminders'
jest.mock('../permission', () => ({ askForReminderPermission: jest.fn() }))
jest.mock('../push', () => ({ registerPushToken: jest.fn(async () => 'ExponentPushToken[test-device]') }))
jest.mock('../reminders', () => ({ scheduleReminders: jest.fn(async () => []) }))
const appointment = { id: '42', startsAt: '2030-01-15T10:30:00Z', practitionerName: 'Dr Amina Okafor' }
beforeEach(() => jest.clearAllMocks())
test('asks for permission only when the patient chooses reminders', async () => {
jest.mocked(askForReminderPermission).mockResolvedValue(true)
const user = userEvent.setup()
await render(<ReminderPrompt appointment={appointment} patientId="patient-7" />)
expect(askForReminderPermission).not.toHaveBeenCalled()
await user.press(screen.getByRole('button', { name: 'Remind me' }))
expect(await screen.findByText(/Reminders are on/)).toBeOnTheScreen()
expect(scheduleReminders).toHaveBeenCalledWith(appointment)
expect(registerPushToken).toHaveBeenCalledWith('patient-7')
})
test('offers the settings screen after a refusal', async () => {
jest.mocked(askForReminderPermission).mockResolvedValue(false)
const user = userEvent.setup()
await render(<ReminderPrompt appointment={appointment} patientId="patient-7" />)
await user.press(screen.getByRole('button', { name: 'Remind me' }))
expect(await screen.findByText(/turn them on in your phone's settings/)).toBeOnTheScreen()
expect(screen.getByRole('button', { name: 'Open settings' })).toBeOnTheScreen()
expect(scheduleReminders).not.toHaveBeenCalled()
})
test('"Not now" hides the card without a prompt', async () => {
const user = userEvent.setup()
await render(<ReminderPrompt appointment={appointment} patientId="patient-7" />)
await user.press(screen.getByRole('button', { name: 'Not now' }))
expect(screen.queryByText('Want a reminder?')).toBeNull()
expect(askForReminderPermission).not.toHaveBeenCalled()
})
TSXAdd tests for the permission function, covering the three states the system can report:
cat > src/notifications/__tests__/permission.test.ts <<'TS'
import * as Notifications from 'expo-notifications'
import { askForReminderPermission } from '../permission'
jest.mock('expo-notifications', () => ({
getPermissionsAsync: jest.fn(),
requestPermissionsAsync: jest.fn(),
setNotificationChannelAsync: jest.fn(async () => null),
SchedulableTriggerInputTypes: { DATE: 'date' },
AndroidImportance: { HIGH: 6 },
}))
const current = jest.mocked(Notifications.getPermissionsAsync)
const request = jest.mocked(Notifications.requestPermissionsAsync)
beforeEach(() => jest.clearAllMocks())
test('does not prompt again when already allowed', async () => {
current.mockResolvedValue({ granted: true, canAskAgain: true, status: 'granted' } as never)
await expect(askForReminderPermission()).resolves.toBe(true)
expect(request).not.toHaveBeenCalled()
})
test('prompts when the patient has not decided yet', async () => {
current.mockResolvedValue({ granted: false, canAskAgain: true, status: 'undetermined' } as never)
request.mockResolvedValue({ granted: true, canAskAgain: true, status: 'granted' } as never)
await expect(askForReminderPermission()).resolves.toBe(true)
expect(request).toHaveBeenCalledTimes(1)
})
test('gives up without a prompt when the system will not ask again', async () => {
current.mockResolvedValue({ granted: false, canAskAgain: false, status: 'denied' } as never)
await expect(askForReminderPermission()).resolves.toBe(false)
expect(request).not.toHaveBeenCalled()
})
TSCheck it worked
npx jest src/notifications --ciJest reports three test suites and Tests: 13 passed, 13 total. On a phone, book an appointment: the card appears under the confirmation, and the system prompt shows only after you press "Remind me".
Step 4 · Cancel the reminders when the booking goes away
A reminder for an appointment that no longer exists sends a patient to the clinic for nothing. There are three places in the app where a booking ends or moves, and each needs one line:
- The patient cancels: after the cancel request succeeds, call
cancelReminders(appointment.id). - The outbox from part 4 marks a pending booking as rejected (the slot was taken): call
cancelReminders(String(booking.appointmentId))inrecordinsrc/sync/sync-outbox.ts, where the row's status is set to rejected. The reminders are named after the appointment on the phone, not after the outbox row. - The patient moves the appointment: call
scheduleReminders(updatedAppointment). It cancels the old pair first, because the identifiers are the same.
import { cancelReminders, scheduleReminders } from '@/notifications/reminders'
// after a successful cancel, or when the outbox marks a booking rejected
await cancelReminders(appointment.id)
// after a successful reschedule
await scheduleReminders(updatedAppointment)Scheduled notifications survive an app restart, and on most phones a reboot as well, so do not schedule reminders again every time the app opens. If a booking can change on the server without the phone knowing (the clinic cancels it), run scheduleReminders or cancelReminders for each appointment when your sync from part 4 brings down the new list.
Check it worked
Run only the cancellation and rescheduling tests:
npx jest src/notifications --ci -t "cancel|clearing old ones"Two tests pass and the rest are reported as skipped. On a phone, book an appointment more than a day ahead, turn reminders on, cancel the booking, and the reminders do not arrive. To see what is still queued while you develop, log the result of Notifications.getAllScheduledNotificationsAsync(): the two appointment-<id> identifiers disappear after the cancel.
Step 5 · Open the appointment when the patient taps a reminder
A tap on a notification should land on that appointment, not on the home tab. Each reminder carries data.url, such as /appointments/42, and Expo Router already maps that path to the appointment screen. The hook below handles both cases: a tap that launches the app from closed (getLastNotificationResponse) and a tap while it is running (the listener).
It also checks the path. Notification data is input from outside your code, especially once a server sends push messages, so the hook only opens paths that match /appointments/<id>. The appointment screen must still check with the API that the signed-in patient may see that appointment.
The hook also sets the foreground handler. Without one, a notification that arrives while the app is open is not shown at all.
Create src/notifications/useReminderTaps.ts:
cat > src/notifications/useReminderTaps.ts <<'TS'
import * as Notifications from 'expo-notifications'
import { router, type Href } from 'expo-router'
import { useEffect } from 'react'
import { Platform } from 'react-native'
import { appointmentPathFrom } from './reminders'
export function useReminderTaps() {
useEffect(() => {
if (Platform.OS === 'web') return
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowBanner: true,
shouldShowList: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
})
function open(response: Notifications.NotificationResponse | null) {
const path = appointmentPathFrom(response?.notification.request.content.data)
if (!path) return
router.push(path as Href)
Notifications.clearLastNotificationResponse()
}
open(Notifications.getLastNotificationResponse())
const subscription = Notifications.addNotificationResponseReceivedListener(open)
return () => subscription.remove()
}, [])
}
TSCall it from the root layout, src/app/_layout.tsx, so it is active whichever screen is showing. Add the import and make the hook the first line of the layout component. Leave the rest of the layout from parts 1, 3 and 4 as it is:
import { useReminderTaps } from '@/notifications/useReminderTaps'
export default function RootLayout() {
useReminderTaps()
// ...the existing layout from parts 1, 3 and 4
}clearLastNotificationResponse stops the same tap from opening the screen again when the layout remounts. The hook does nothing on the web, where notifications are not part of this app.
Check it worked
The path check is covered by the test only opens appointment screens from notification data, which passed in the second step. Check that the layout and every route still bundle:
npx expo export --platform web --output-dir dist-check
ls dist-checkThe export finishes with Exported: dist-check, and the listing shows client and server, because the template sets web.output to server: the JavaScript bundles and assets are in dist-check/client, and dist-check/server holds the route manifest and the server renderer that builds each page when it is requested. On a phone, close the app completely, wait for a reminder (or schedule one a minute ahead while you test), tap it, and the app opens on that appointment with a back button to the home screen.
Step 6 · Get an Expo push token and store it on the clinic API
A push message needs an address. getExpoPushTokenAsync returns one for this install of the app, a string like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]. The Expo push service maps it to the Apple or Google device token behind it. The app sends the token to the clinic's notify service, which keeps it next to the patient's ID.
The token is tied to your EAS project ID, which eas init writes to app.json under extra.eas.projectId. Without it there is no token, so the function returns null and logs why, and local reminders carry on working. As before, the Android channel must exist before you ask for a token.
Replace the placeholder src/notifications/push.ts:
cat > src/notifications/push.ts <<'TS'
import Constants from 'expo-constants'
import * as Notifications from 'expo-notifications'
import { ensureReminderChannel } from './reminders'
const NOTIFY_API_URL = process.env.EXPO_PUBLIC_NOTIFY_API_URL ?? 'http://127.0.0.1:4100'
export async function registerPushToken(
patientId: string,
fetchImpl: typeof fetch = fetch,
): Promise<string | null> {
const projectId = Constants.expoConfig?.extra?.eas?.projectId ?? Constants.easConfig?.projectId
if (!projectId) {
console.warn('No EAS project ID: run eas init before using push notifications.')
return null
}
await ensureReminderChannel()
const { data: token } = await Notifications.getExpoPushTokenAsync({ projectId })
const response = await fetchImpl(`${NOTIFY_API_URL}/push-tokens`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ patientId, token }),
})
if (!response.ok) throw new Error(`Saving the push token failed: ${response.status}`)
return token
}
TS127.0.0.1 on a phone is the phone itself. When you run the app on a device, create a .env file in the project with EXPO_PUBLIC_NOTIFY_API_URL=http://<your computer's Wi-Fi address>:4100 and restart npx expo start. Anything named EXPO_PUBLIC_ is built into the app where anyone can read it, so a URL is fine there and a secret never is.
The card from the earlier step already calls registerPushToken after the patient allows notifications, and in development it logs the token. Test the function with the token call and the network mocked:
cat > src/notifications/__tests__/push.test.ts <<'TS'
import * as Notifications from 'expo-notifications'
import { registerPushToken } from '../push'
jest.mock('expo-constants', () => ({
__esModule: true,
default: { expoConfig: { extra: { eas: { projectId: 'larkfield-test-project' } } } },
}))
jest.mock('expo-notifications', () => ({
getExpoPushTokenAsync: jest.fn(async () => ({ type: 'expo', data: 'ExponentPushToken[test-device]' })),
setNotificationChannelAsync: jest.fn(async () => null),
SchedulableTriggerInputTypes: { DATE: 'date' },
AndroidImportance: { HIGH: 6 },
}))
test('sends the Expo push token to the notify service', async () => {
const fetchMock = jest.fn(async (_url: string, _init: RequestInit) => ({ ok: true, status: 204 }))
const token = await registerPushToken('patient-7', fetchMock as unknown as typeof fetch)
expect(token).toBe('ExponentPushToken[test-device]')
expect(Notifications.getExpoPushTokenAsync).toHaveBeenCalledWith({ projectId: 'larkfield-test-project' })
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/push-tokens$/)
expect(JSON.parse(init.body as string)).toEqual({
patientId: 'patient-7',
token: 'ExponentPushToken[test-device]',
})
})
test('reports a failed save instead of hiding it', async () => {
const fetchMock = jest.fn(async () => ({ ok: false, status: 503 }))
await expect(registerPushToken('patient-7', fetchMock as unknown as typeof fetch)).rejects.toThrow('503')
})
TSCheck it worked
npx jest src/notifications --ciJest reports four test suites and Tests: 15 passed, 15 total. On a development build with an EAS project, press "Remind me" and the Metro terminal prints Expo push token: ExponentPushToken[...]. In Expo Go on Android no token arrives: push needs a development build there from SDK 53, while the local reminders still work.
Step 7 · Send a push message through the Expo push service
The clinic's notify service is a small Node 26 server with no dependencies. It stores tokens by patient and sends messages to the Expo push service's HTTP API at https://exp.host/--/api/v2/push/send. Expo then hands each message to Apple's APNs or Google's FCM. It is a stand-in, kept apart from part 4's mock clinic API so you do not have to edit that file: it has no sign-in and keeps tokens in memory. A real clinic API checks that the caller is clinic staff before sending anything, and stores tokens in its database.
Three parts of Expo's documented behaviour shape the code:
- One request can carry up to 100 messages, so all of a patient's devices go in one array.
- The answer is a list of push tickets, in the same order as the messages. A ticket with
status: "ok"means Expo accepted the message, not that the phone showed it. - A ticket with
details.errorset toDeviceNotRegisteredmeans the app was removed or notifications were turned off. Stop sending to that token. The service deletes it.
Create notify-service/server.mjs in the project:
mkdir -p notify-service
cat > notify-service/server.mjs <<'JS'
import { createServer } from 'node:http'
const PORT = Number(process.env.PORT ?? 4100)
const HOST = process.env.HOST ?? '127.0.0.1'
const EXPO_PUSH_URL = process.env.EXPO_PUSH_URL ?? 'https://exp.host/--/api/v2/push/send'
const TOKEN_PATTERN = /^Expo(nent)?PushToken\[[^\]]+\]$/
const tokensByPatient = new Map()
function reply(res, status, body) {
res.writeHead(status, { 'Content-Type': 'application/json' })
res.end(body === undefined ? undefined : JSON.stringify(body))
}
async function readJson(req) {
let raw = ''
for await (const chunk of req) raw += chunk
try {
return JSON.parse(raw || '{}')
} catch {
return null
}
}
async function sendToPatient(patientId, { title, body, url }) {
const tokens = [...(tokensByPatient.get(patientId) ?? [])]
if (tokens.length === 0) return []
const messages = tokens.map((to) => ({
to,
title,
body,
data: { url },
sound: 'default',
channelId: 'appointment-reminders',
}))
const headers = {
Accept: 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/json',
}
if (process.env.EXPO_ACCESS_TOKEN) headers.Authorization = `Bearer ${process.env.EXPO_ACCESS_TOKEN}`
const response = await fetch(EXPO_PUSH_URL, { method: 'POST', headers, body: JSON.stringify(messages) })
if (!response.ok) throw new Error(`Expo push service answered ${response.status}`)
const { data: tickets } = await response.json()
tickets.forEach((ticket, i) => {
if (ticket.status === 'error' && ticket.details?.error === 'DeviceNotRegistered') {
tokensByPatient.get(patientId).delete(tokens[i])
}
})
return tickets
}
createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost')
const parts = url.pathname.split('/').filter(Boolean)
try {
if (req.method === 'GET' && url.pathname === '/health') return reply(res, 200, { ok: true })
if (req.method === 'POST' && url.pathname === '/push-tokens') {
const input = await readJson(req)
if (!input || typeof input.patientId !== 'string' || !TOKEN_PATTERN.test(String(input.token))) {
return reply(res, 400, { error: 'patientId and an Expo push token are required' })
}
if (!tokensByPatient.has(input.patientId)) tokensByPatient.set(input.patientId, new Set())
tokensByPatient.get(input.patientId).add(input.token)
return reply(res, 204)
}
if (parts[0] === 'patients' && parts.length === 3) {
const patientId = decodeURIComponent(parts[1])
if (req.method === 'GET' && parts[2] === 'push-tokens') {
return reply(res, 200, { count: tokensByPatient.get(patientId)?.size ?? 0 })
}
if (req.method === 'POST' && parts[2] === 'notify') {
const input = await readJson(req)
if (!input?.title || !input?.body) return reply(res, 400, { error: 'title and body are required' })
return reply(res, 200, { tickets: await sendToPatient(patientId, input) })
}
}
reply(res, 404, { error: 'not found' })
} catch (error) {
reply(res, 502, { error: error.message })
}
}).listen(PORT, HOST, () => console.log(`Notify service on http://${HOST}:${PORT}`))
JSStart it in a second terminal, from the project folder, and leave it running. It listens on 127.0.0.1 only. To reach it from a phone on your Wi-Fi, start it with HOST=0.0.0.0 instead, on a network you trust:
cd ~/larkfield-app-demo
node notify-service/server.mjsIn your first terminal, register a token for patient 7. Put the token your phone printed in the previous step in place of the example value:
TOKEN='ExponentPushToken[test-device]' # replace with your phone's token
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:4100/push-tokens \
-H 'Content-Type: application/json' \
-d "{\"patientId\":\"patient-7\",\"token\":\"$TOKEN\"}"
curl -s http://127.0.0.1:4100/patients/patient-7/push-tokensThe first command prints 204 and the second {"count":1}. Now send the kind of message only a server can know about:
curl -s -X POST http://127.0.0.1:4100/patients/patient-7/notify \
-H 'Content-Type: application/json' \
-d '{"title":"Larkfield Clinic","body":"Dr Okafor is running about 20 minutes late today.","url":"/appointments/42"}'The payload, including data, must stay under 4096 bytes. In practice that means a short text and an ID, never a whole appointment record. Because the message names the appointment-reminders channel and carries a url, a tap on it goes through the same hook and the same path check as a local reminder.
Check it worked
With your phone's real token, the answer is {"tickets":[{"status":"ok","id":"..."}]} and the phone shows the message within a few seconds. Tap it and the app opens appointment 42. If the token was made up, Expo answers with an error instead, and nothing is sent.
A ticket only says that Expo accepted the message. To learn whether Apple or Google accepted it, your production notify service saves the ticket IDs and, about 15 minutes later, posts them to https://exp.host/--/api/v2/push/getReceipts. Receipts can report DeviceNotRegistered too, and that token should be deleted the same way. Press Ctrl+C in the second terminal to stop the notify service.
Step 8 · Keep FCM and APNs credentials in EAS, not in the repository
Delivery through Expo needs two sets of credentials. Google needs an FCM V1 service account key from your Firebase project for Android. Apple needs an APNs key from a paid Apple Developer account for iOS. Both are private keys: anyone who has one can send notifications to your users as you. Upload them to EAS, which stores them on Expo's servers and uses them when it sends, so they never sit in Git, on a laptop that gets lost, or in the app bundle:
eas credentials --platform android
eas credentials --platform iosFor Android, choose the FCM V1 service account key option and upload the JSON file you downloaded from the Firebase console, then delete your local copy. For iOS, eas build offers to create an APNs key the first time you build with push enabled; answer yes. Expo's FCM credentials guide walks through the Firebase console screens.
Make sure the key files cannot be committed by accident. Append these lines to .gitignore:
cat >> .gitignore <<'TXT'
# Push credentials live in EAS (eas credentials), never in the repository
*.p8
*-firebase-adminsdk-*.json
fcm-service-account*.json
TXTThe same reasoning covers the Expo access token. If you turn on enhanced push security in the Expo dashboard, the push API only accepts requests that carry a token. That token belongs to the server, in its secret store, read as EXPO_ACCESS_TOKEN as the notify service above does. Never put it in the app or in an EXPO_PUBLIC_ variable, because everything built into the app can be read by anyone who installs it.
Check it worked
grep -Fx -e '*-firebase-adminsdk-*.json' -e 'fcm-service-account*.json' .gitignore
npx expo export --platform webThe grep prints the two Firebase key patterns back, so both lines are in place. The export ends with Exported: dist, which shows the whole app, with the confirmation card and the root layout hook, still bundles. Then try the full flow on a development build:
npx expo startBook an appointment two hours and ten minutes ahead, press "Remind me" and allow notifications. Only the 2-hour reminder is queued (log Notifications.getAllScheduledNotificationsAsync() to see it), because the 24-hour one is already in the past. On Android, check that Settings, then Apps, then your app, then Notifications lists "Appointment reminders".
On Android, the default bestEffort delivery means some phones, particularly low-cost models with aggressive battery savers, can show a reminder a few minutes late. That is fine for a 2-hour reminder. Exact alarms need one of two permissions. USE_EXACT_ALARM is one Google Play only allows for alarm, timer and calendar apps. SCHEDULE_EXACT_ALARM is granted by the user in system settings, and it is denied by default for new installs on Android 14 and later. A booking app does not need either for a reminder that can arrive a few minutes late, so do not ask for them.
Next steps
- Let a text message open the same appointment screen with deep links, universal links and app links, the next part of this series.
- Revisit how bookings reach the server in the offline-first outbox, where a rejected booking now cancels its reminders.
- Decide when a message should be a notification at all, rather than a toast or a banner, with design toasts, banners and notifications.
- Build the development build that push needs, and later the store build, with build and submit an app with EAS.
Related tutorials
- Sync Larkfield bookings offline first with an outbox queueYou will have a Larkfield app that saves every booking to an SQLite outbox first, sends it to a mock clinic API with an idempotency key when the phone is online or back in the foreground, retries with capped backoff and jitter, and offers the next free slot when a time has gone, all proven by Jest tests.
- Design toasts, banners and notificationsYou will have a message pattern table that gives every Larkfield Clinic message a channel by urgency and persistence, plus Figma frames for the inline, banner, toast, push and SMS forms, each with a rule for when it goes away.
- How to Build and Submit an Expo App to the App Stores with EASYou will set up EAS for an Expo SDK 58 app, build it for testers with an internal distribution profile, build a production release, and submit it to TestFlight and Google Play, with the costs, the accounts you need and the places where credentials stay out of your repository.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials