Notifications
notifications schedules a notification on the device itself — a reminder at a time, a daily one,
or one shown right now — and hears the tap on it. No server is involved: a notification sent from
your backend to a user is the push plugin's (push.md). The device fires a
scheduled notification with the app closed; a tap opens the app and reaches onTap.
- remind the user at a time they chose (a medication, a workout, a deadline)
- a daily or weekly reminder at the same time
- show a notification right now (a download finished, your turn in a game)
- open the right screen when the user taps a notification, also when the tap started the app
- cancel a reminder, or list the ones still pending
- ask for the notification permission earlier, or handle a refusal
Platforms: iOS and Android. On the desktop, the web and in headless tests there are none:
notifications.supported is false, schedule rejects and the rest does nothing.
At a glance
const remindAt = async (when: Date) => {
try {
await notifications.schedule({
id: 'water', // the same id again replaces this reminder
title: 'Time to drink water',
body: 'A glass now keeps the headache away',
at: when,
repeat: 'daily',
data: { screen: 'hydration' },
})
toast('Reminder set')
} catch (e) {
if ((e as Error).message === 'denied') toast('Turn notifications on in Settings')
}
}
notifications.onTap(tap => { // while the app runs, and the tap that started it
if (tap.data?.screen === 'hydration') Router.push(hydrationScreen)
})Schedule a notification: notifications.schedule
notifications.schedule(request): Promise<string> // the id — yours, or a generated one
interface NotificationRequest {
id?: string // the same id scheduled again replaces the earlier notification
title: string
body?: string
at?: Date | number // when it fires; absent or in the past: shown now
repeat?: 'daily' | 'weekly' // again every day / week at that time, until cancelled (needs `at`)
url?: string // a link for the app to open from the tap
data?: { [key: string]: unknown } // yours, at most 2 KB as JSON; handed back with the tap
}schedule shows the notification at at, or now without one. repeat fires it again every day
or every week at the same wall-clock time (the device's time zone) until it is cancelled; a
repeating at in the past is not shown now — the series starts at its next occurrence. The first
call asks the OS for the notification permission — the first reminder the user sets is the moment
they expect the dialog, so there is nothing to ask before it. It resolves with the id: give one
when you will replace or cancel the notification later (one reminder per medication, keyed by it),
or take the generated one.
// show now
await notifications.schedule({ title: 'Export finished', body: 'report.pdf is ready', data: { file: 'report.pdf' } })
// in two hours
await notifications.schedule({ title: 'Your turn', at: Date.now() + 2 * 60 * 60 * 1000 })
// every Monday at 9:00, from the coming one (on a Monday after 9:00: from next week's)
const monday = new Date()
monday.setDate(monday.getDate() + ((8 - monday.getDay()) % 7)) // the coming Monday, under a week ahead (iOS, below)
monday.setHours(9, 0, 0, 0)
await notifications.schedule({ id: 'weekly-review', title: 'Weekly review', at: monday, repeat: 'weekly' })- Rejects with
e.message === 'denied'when the user refused the permission (the way back ispermissions.openSettings(), below),'unavailable'where the host cannot schedule, and before the host for a missing title,repeatwithoutat, ordataover 2 KB. - A notification shows the system banner, also while the app is in the foreground: an app that wants to react to its own timer while it is open sets a timer, not a notification.
- Android fires a scheduled notification within a few minutes of
at(the system's own batching; exact to the second is not promised); iOS at the time. - A repeating notification has no start date on iOS: it first fires at the next occurrence of
at's time (daily) or weekday and time (weekly) from now, so anatmore than a day (a week) ahead fires beforeatthere — Android waits forat. Keep a repeatingatwithin one period of now, as the Monday above does. A series that must start later (a course from the 1st) is a one-shot on its first day, and the repeating one, under the sameid, scheduled when the app next runs after it — fromonTapor at the next start. - One app, one schedule: in the le.codes viewer each project has its own, so
cancelAllandpendingnever touch another project's.
Hear the tap: notifications.onTap
notifications.onTap(handler: (tap: NotificationTap) => void): { close(): void }
interface NotificationTap { id: string, title: string, body?: string, url?: string, data?: { [key: string]: unknown } }onTap hears the tap on one of this app's notifications: while the app runs, and the tap that
started the app — that one is delivered to the first handler right after the code that attached
it, so a handler at the top level of the app may route. Open the screen from data or url
yourself: a notification's url does not arrive as app.launchUrl or the "url" event.
Router.init(home)
notifications.onTap(tap => { // a cold start lands here too, after this line ran
if (tap.url) openURL(tap.url) // or route it: Router.push(screenFor(tap.url))
else if (tap.id === 'weekly-review') Router.push(review)
})- One handler per concern;
close()on the returned subscription stops it. - The tap is heard once: a handler attached later does not hear the one that started the app.
Cancel and list: cancel, cancelAll, pending
notifications.cancel(id: string): void // a pending one; clears it from the shade when shown
notifications.cancelAll(): void // every one of this app
notifications.pending(): Promise<PendingNotification[]> // not fired yet; a repeating one: its next time
interface PendingNotification extends NotificationTap { at: number, repeat?: 'daily' | 'weekly' }const stopReminding = () => notifications.cancel('water')
const showReminders = async () => {
const list = await notifications.pending()
rows.setContent(list.map(n => UIText(`${n.title} — ${date(n.at).format('D MMM HH:mm')}`)))
}The permission
The first schedule asks. To ask earlier — a settings screen with a switch — or to read the state,
use the "notifications" kind of permissions: permissions.query('notifications')
answers 'granted', 'denied' or 'prompt' without a dialog, permissions.request('notifications')
shows it. The same OS permission stands behind remote push: granted once, it covers both.
const row = UIRow()
const refresh = async () => {
const state = await permissions.query('notifications')
row.setContent([state === 'granted'
? UIText('Reminders are on')
: UIButton(UIText('Turn reminders on')).onClick(async () => {
const after = await permissions.request('notifications')
if (after === 'denied') permissions.openSettings() // iOS asks once; Android when it decides
refresh()
})])
}
app.addEventListener('resume', refresh) // back from Settings
refresh()- iOS shows the dialog once; after a refusal only Settings turns it on. Android 13+ has the same dialog; before 13 there is none and the state is the app's notification switch.
- In the le.codes viewer the permission is the viewer's, shared by every project it runs.
See also
- permissions.md —
query,request,openSettings - push.md — notifications sent from your server
- app.md —
"resume",app.launchUrl(which a notification'surldoes not use) - datetime.md —
date()for the times you schedule and show