@molecule/app-push
Native · push · App (browser) · v1.2.3 · Apache-2.0
Client-side push notifications interface for molecule.dev
npm install @molecule/app-pushHow it works
@molecule/app-push bridges the push core to the native platform layer of the app.
import { getToken, onNotificationAction, register, requestPermission } from '@molecule/app-push'
async function enablePush(vapidPublicKey: string): Promise<string | null> {
const permission = await requestPermission() // from a user gesture
if (permission !== 'granted') return null
const token = await register({ vapidPublicKey })
// POST token.value to your API so api-push-notifications can target it
return token.value
}
function handleTaps(open: (data: unknown) => void): () => void {
return onNotificationAction((event) => open(event.notification.data))
}Providers (1): @molecule/app-push-react-native
Works with: @molecule/app-bond, @molecule/app-i18n
Reference
Client-side push notifications interface for molecule.dev.
Provides a unified API for push notifications across platforms (web,
native containers, etc.): permission flow (checkPermission,
requestPermission), registration (register, getToken), incoming
events (onNotificationReceived, onNotificationAction), local
notifications (scheduleLocal), and badges (setBadge, clearBadge).
The device token is what your API's @molecule/api-push-notifications
bond sends to.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { getToken, onNotificationAction, register, requestPermission } from '@molecule/app-push'
async function enablePush(vapidPublicKey: string): Promise<string | null> {
const permission = await requestPermission() // from a user gesture
if (permission !== 'granted') return null
const token = await register({ vapidPublicKey })
// POST token.value to your API so api-push-notifications can target it
return token.value
}
function handleTaps(open: (data: unknown) => void): () => void {
return onNotificationAction((event) => open(event.notification.data))
}
Type
native
Installation
npm install @molecule/app-push @molecule/app-bond @molecule/app-i18n
API
Interfaces
PushToggleHttp
Minimal structural slice of @molecule/app-http's HttpClient used here.
interface PushToggleHttp {
get<T = unknown>(url: string): Promise<{ data: T }>
patch<T = unknown>(url: string, data?: unknown): Promise<{ data: T }>
}
PushToggleDevice
Device row slice returned by GET /api/devices.
interface PushToggleDevice {
id: string
isCurrent?: boolean
hasPushSubscription?: boolean
}
PushToggleToken
Push token slice returned by @molecule/app-push register().
interface PushToggleToken {
value: string
platform: 'web' | 'ios' | 'android'
}
PushNotification
Push notification payload.
interface PushNotification {
/**
* Notification ID.
*/
id: string
/**
* Notification title.
*/
title: string
/**
* Notification body/message.
*/
body?: string
/**
* Notification data payload.
*/
data?: Record<string, unknown>
/**
* Badge count.
*/
badge?: number
/**
* Sound to play.
*/
sound?: string
/**
* Icon URL.
*/
icon?: string
/**
* Image URL.
*/
image?: string
/**
* Click action/URL.
*/
clickAction?: string
/**
* Notification tag (for grouping).
*/
tag?: string
/**
* Whether the notification requires interaction.
*/
requireInteraction?: boolean
/**
* Notification timestamp.
*/
timestamp?: number
/**
* Notification actions (buttons).
*/
actions?: PushNotificationAction[]
}
PushNotificationAction
Notification action button.
interface PushNotificationAction {
/**
* Action ID.
*/
id: string
/**
* Action title.
*/
title: string
/**
* Action icon.
*/
icon?: string
}
PushToken
Push token info.
interface PushToken {
/**
* Token value.
*/
value: string
/**
* Platform the token is for.
*/
platform: 'web' | 'ios' | 'android'
/**
* When the token was obtained.
*/
timestamp: number
}
NotificationReceivedEvent
Notification received event.
interface NotificationReceivedEvent {
/**
* The notification.
*/
notification: PushNotification
/**
* Whether the app was in foreground.
*/
foreground: boolean
}
NotificationActionEvent
Notification action event.
interface NotificationActionEvent {
/**
* The notification.
*/
notification: PushNotification
/**
* Action that was triggered.
*/
actionId?: string
}
LocalNotificationOptions
Options for scheduling a local notification.
interface LocalNotificationOptions {
/**
* Notification ID.
*/
id?: string
/**
* Notification title.
*/
title: string
/**
* Notification body.
*/
body?: string
/**
* Schedule at a specific time.
*/
at?: Date
/**
* Repeat interval.
*/
repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'
/**
* Extra data.
*/
extra?: Record<string, unknown>
/**
* Sound to play.
*/
sound?: string
/**
* Badge count.
*/
badge?: number
/**
* Notification channel (Android).
*/
channelId?: string
/**
* Actions/buttons.
*/
actions?: PushNotificationAction[]
}
PushRegisterOptions
Options for PushProvider.register.
interface PushRegisterOptions {
/**
* VAPID public key (URL-safe base64) used as the `applicationServerKey`
* when subscribing on the web. Chromium rejects keyless subscriptions, so
* web apps should deliver the server's key at runtime (e.g. from
* `GET /api/devices/push/public-key`) and pass it here. Takes precedence
* over any key the provider was constructed with. Ignored by providers
* whose platform does not use VAPID (e.g. FCM/APNs native providers).
*/
vapidPublicKey?: string
}
PushProvider
Push notifications provider interface.
All push providers must implement this interface.
interface PushProvider {
/**
* Checks the current permission status.
*/
checkPermission(): Promise<PermissionStatus>
/**
* Requests notification permission.
*/
requestPermission(): Promise<PermissionStatus>
/**
* Registers for push notifications and gets a token.
*
* @param options - Optional registration options (e.g. a runtime VAPID
* public key for web subscriptions).
*/
register(options?: PushRegisterOptions): Promise<PushToken>
/**
* Unregisters from push notifications.
*/
unregister(): Promise<void>
/**
* Gets the current push token.
* @returns The current token, or `null` if not registered.
*/
getToken(): Promise<PushToken | null>
/**
* Subscribes to notification received events.
*/
onNotificationReceived(listener: NotificationReceivedListener): () => void
/**
* Subscribes to notification action events (taps, button clicks).
*/
onNotificationAction(listener: NotificationActionListener): () => void
/**
* Subscribes to token changes.
*/
onTokenChange(listener: TokenChangeListener): () => void
/**
* Schedules a local notification.
*/
scheduleLocal(options: LocalNotificationOptions): Promise<string>
/**
* Cancels a local notification.
*/
cancelLocal(id: string): Promise<void>
/**
* Cancels all local notifications.
*/
cancelAllLocal(): Promise<void>
/**
* Gets pending local notifications.
*/
getPendingLocal(): Promise<LocalNotificationOptions[]>
/**
* Gets delivered notifications.
*/
getDelivered(): Promise<PushNotification[]>
/**
* Removes delivered notifications.
*/
removeDelivered(ids: string[]): Promise<void>
/**
* Removes all delivered notifications.
*/
removeAllDelivered(): Promise<void>
/**
* Sets the badge count.
*/
setBadge(count: number): Promise<void>
/**
* Gets the badge count.
*/
getBadge(): Promise<number>
/**
* Clears the badge.
*/
clearBadge(): Promise<void>
/**
* Destroys the provider.
*/
destroy(): void
}
Types
PushToggleFailureReason
Why an enable/disable attempt failed (mapped to i18n by the component).
type PushToggleFailureReason =
'permission-denied' | 'server-unconfigured' | 'register-failed' | 'persist-failed'
PushToggleResult
Result of an enable/disable attempt.
type PushToggleResult =
{ ok: true } | { ok: false; reason: PushToggleFailureReason; message?: string }
PermissionStatus
Push notification permission status.
type PermissionStatus = 'granted' | 'denied' | 'default' | 'prompt'
NotificationReceivedListener
Listener invoked when a push notification is received.
type NotificationReceivedListener = (event: NotificationReceivedEvent) => void
event— The received notification and foreground state.
NotificationActionListener
Notification Action Listener type.
type NotificationActionListener = (event: NotificationActionEvent) => void
TokenChangeListener
Token Change Listener type.
type TokenChangeListener = (token: PushToken) => void
Functions
findCurrentDevice(devices)
Picks the caller's own device row: the api flags the session device
isCurrent; fall back to the first row for sessions predating the flag.
function findCurrentDevice(devices: PushToggleDevice[] | undefined): PushToggleDevice | undefined
devices— Rows fromGET /api/devices.
Returns: The current device row, or undefined when the user has none.
subscriptionFromToken(token)
Converts an @molecule/app-push token into the device resource's
pushSubscription shape (web PushSubscription JSON, FCM registration for
Android, APNs registration for iOS).
function subscriptionFromToken(token: PushToggleToken): unknown
token— The push token returned byregister().
Returns: The pushSubscription value to PATCH onto the device row.
enablePushOnCurrentDevice(deps)
Runs the full enable chain: browser permission → runtime VAPID public key
(GET /api/devices/push/public-key) → register({ vapidPublicKey }) →
persist the subscription on the current device row.
Every failure is returned as a typed reason (never thrown) so the UI can show an honest, specific message instead of hanging or silently reverting.
function enablePushOnCurrentDevice(deps: {
http: PushToggleHttp
requestPermission: () => Promise<string>
register: (options?: { vapidPublicKey?: string }) => Promise<PushToggleToken>
}): Promise<PushToggleResult>
deps— The http client + push actions fromusePush().deps.http— Authenticated http client (useHttpClient()).deps.requestPermission—usePush().requestPermission.deps.register—usePush().register.
Returns: { ok: true } or a typed failure.
disablePushOnCurrentDevice(deps)
Disables push: unsubscribes the browser (best-effort — a dev build without a service worker has nothing to unsubscribe) and ALWAYS clears the server state so no further pushes target this device.
function disablePushOnCurrentDevice(deps: {
http: PushToggleHttp
unregister: () => Promise<void>
}): Promise<PushToggleResult>
deps— The http client + push action fromusePush().deps.http— Authenticated http client (useHttpClient()).deps.unregister—usePush().unregister.
Returns: { ok: true } or a typed failure (server state not cleared).
readCurrentDevicePushEnabled(http)
Reads whether push is currently enabled for THIS device (server truth:
the current device row's hasPushSubscription).
function readCurrentDevicePushEnabled(http: PushToggleHttp): Promise<boolean>
http— Authenticated http client (useHttpClient()).
Returns: true when the current device has a stored subscription.
setProvider(provider)
Sets the push provider implementation.
function setProvider(provider: PushProvider): void
provider— The push provider to bond as the active implementation.
getProvider()
Gets the current push provider, creating a default web provider if none is bonded.
function getProvider(): PushProvider
Returns: The active push provider instance.
hasProvider()
Checks if a push provider has been bonded.
function hasProvider(): boolean
Returns: Whether a push provider is currently registered.
checkPermission()
Checks the current notification permission status.
function checkPermission(): Promise<PermissionStatus>
Returns: The current permission status (granted, denied, default, or prompt).
requestPermission()
Requests notification permission from the user.
function requestPermission(): Promise<PermissionStatus>
Returns: The resulting permission status after the user responds.
register(options)
Registers for push notifications and obtains a device token.
function register(options?: PushRegisterOptions): Promise<PushToken>
options— Optional registration options (e.g. a runtime VAPID public key).
Returns: The push token for this device.
getToken()
Gets the current push token.
function getToken(): Promise<PushToken | null>
Returns: The current token, or null if not registered.
onNotificationReceived(listener)
Subscribes to notification received events.
function onNotificationReceived(listener: NotificationReceivedListener): () => void
listener— Callback invoked when a notification is received.
Returns: An unsubscribe function to remove the listener.
onNotificationAction(listener)
Subscribes to notification action events (taps, button clicks).
function onNotificationAction(listener: NotificationActionListener): () => void
listener— Callback invoked when a notification action is triggered.
Returns: An unsubscribe function to remove the listener.
scheduleLocal(options)
Schedules a local notification.
function scheduleLocal(options: LocalNotificationOptions): Promise<string>
options— Configuration for the notification (title, body, schedule time, etc.).
Returns: The notification ID that can be used to cancel it later.
setBadge(count)
Sets the app icon badge count.
function setBadge(count: number): Promise<void>
count— The badge number to display on the app icon.
Returns: A promise that resolves when the badge count is set.
clearBadge()
Clears the app icon badge count.
function clearBadge(): Promise<void>
Returns: A promise that resolves when the badge count is cleared.
createWebPushProvider(vapidPublicKey)
Creates a web push provider using the browser Push API and Notification API.
function createWebPushProvider(vapidPublicKey?: string): PushProvider
vapidPublicKey— Optional VAPID public key for server-authenticated subscriptions.
Returns: A PushProvider backed by the Web Push API.
Available Providers
| Provider | Package |
|---|---|
| React Native Push | @molecule/app-push-react-native |
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1@molecule/app-i18n^1.0.1@molecule/app-pwa-default^1.1.0 (optional)
Runtime Dependencies
-
@molecule/app-bond -
@molecule/app-i18n -
@molecule/app-pwa-default(optional) -
No wiring is needed on web: the first accessor call silently bonds the built-in Web Push provider. In a native app wire
@molecule/app-push-react-native(the one prebuilt bond) viasetProvider()BEFORE any push call — otherwise the web fallback gets bonded and native registration never happens. -
Web
register()has three hard prerequisites: (1) HTTPS (secure context), (2) a registered SERVICE WORKER — the one@molecule/app-pwa-defaultregisters in the production build, which also shows the delivered notifications. It is an optional peer of this package. For web push,mlcl create --packages @molecule/app-push,…andmlcl add @molecule/app-pushadd it, and an app that installed this package some other way runsmlcl add @molecule/app-pwa-default. Dev builds don't ship a worker, so register() throws "need the production app build" (it fails fast instead of hanging), and (3) a VAPID public key (pass viaregister({ vapidPublicKey })) matching your API'sVAPID_PRIVATE_KEY— without it Chrome may register but delivery fails. -
Request permission from a user gesture at the point of value, never on load — a denied browser prompt is remembered forever (no re-prompt).
-
Web
scheduleLocalat a future time uses an in-page timer: it does NOT survive reload/close. WebcancelLocal/cancelAllLocalare no-ops, andgetPendingLocal()is always empty — for reliable scheduled delivery send a real push from the server. -
token.valueon web is a JSON-serialized PushSubscription (not an FCM token) — store it opaquely; platform is intoken.platform. -
A settings toggle for the current device needs no code of its own:
enablePushOnCurrentDevice({ http, requestPermission, register }),disablePushOnCurrentDevice({ http, unregister })andreadCurrentDevicePushEnabled(http)run the whole chain against the molecule device API (GET /api/devices/push/public-key,GET /api/devices,PATCH /api/devices/:id) and return a typed result instead of throwing. Every framework's settings panel package re-exports them.
Translations
Translation strings are provided by @molecule/app-locales-push.