Communication

Push

Register phones and deliver push notifications to them, as the push driver of Notify.

Push lets your app reach a person's phone. The mobile app registers its device, and Push delivers the push notifications your server code sends through Notify: it is Notify's push driver. Which channels reach a user for each kind of message is Notify's notifyUser, with the choices kept by Preferences.

The package is @frigear-nu/push. It sends to Android through Firebase Cloud Messaging (FCM). It sends to iOS through FCM as well when the app registers its FCM token, and otherwise straight to the Apple Push Notification service (APNs). It talks to FCM with fetch and to APNs with node:http2, each with a signed token, so no provider SDK is installed. On Cloudflare Workers, which have no node:http2, iOS goes through FCM (see iOS through FCM).

What you get

  • Server routes (server mode, on by default): register, list and remove the caller's devices. Staff routes list a user's devices and send a test push.
  • Notify's push driver (server mode): Push sets itself as notify.push.driver, so dispatchPushNotification and the push channel of notifyUser reach the users' devices.
  • Server helpers (server mode): sendPush, and devices of another owner for a module that pairs shared phones.
  • Account page (server mode): /account/devices lists the user's own devices and removes one. It shows up in the Account menu when Menu is installed.
  • Admin tab (with Admin and Widget): a Devices tab on the admin user page, with a Send test push action.
  • Device side (mobile): usePushDevice() and a plugin that registers the device when someone signs in, for a Capacitor app that uses Mobile.
ServerClientMobile
Installed for you (server mode):@frigear-nu/module-kit, Auth, Users, Notify and UI.You add:@nuxthub/core (server mode), and a push plugin in the mobile app: @capacitor-firebase/messaging (the FCM token on iOS and Android) or @capacitor/push-notifications (the APNs token on iOS).Optional:Admin and Widget for the admin tab, Account and Menu for the account page, and Mobile for registration.In client mode (a mobile app without a server) Push installs only Auth and Module Kit. It adds no tables, routes or pages, and pulls in no server module.

Two modes

Push follows the app's authentication.mode, like Authorization.

Server mode (the default)Client mode (the mobile app)
WhereThe app that has the database and the routesThe Capacitor app that signs in at an issuer
AddsThe devices table, routes, access, the admin tab, Notify's push driver, sendPushusePushDevice() and the sign-in plugin
Needs@nuxthub/core, Users, NotifyMobile (optional) and a push plugin

The mobile app registers its device with the server's routes through its bearer token. The server sends the pushes.

Quick setup

Install Push on the server

pnpm add @frigear-nu/push @nuxthub/core
nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxthub/core', '@frigear-nu/push'], // installs Users, Auth and Notify for you
})
Without a migration the push_devices table does not exist, and every route fails.

Generate the migration

pnpm db:generate

Send a notification

Send through Notify, which hands the push to Push:

server/routes/api/remind.post.ts
export default defineEventHandler(async () => {
  return dispatchPushNotification({ userIds: [42], title: 'Your shift tomorrow', body: 'You work 18:00 to 23:00.', url: '/shifts/42' })
  // { sent: 1, failed: 0, revoked: 0 }
})

To respect each user's channel choices, send with Notify's notifyUser instead.

What you should see: with no credentials the log delivery writes the push to the server log, and every device counts as sent.

Credentials

Without credentials sendPush only writes to the server log (the log delivery), so development needs no setup. Set the credentials as private runtime config through environment variables:

VariableWhat it is
NUXT_PUSH_DELIVERYlog or providers. Unset: providers once any credentials are set, otherwise log.
NUXT_PUSH_IOSapns (the default) or fcm: where an iOS device goes when it registered without a provider. See Which provider a device uses.
NUXT_PUSH_FCM_SERVICE_ACCOUNTThe whole service account JSON of your Firebase project (Project settings, Service accounts).
NUXT_PUSH_APNS_KEY_IDThe key id of your APNs authentication key (.p8).
NUXT_PUSH_APNS_TEAM_IDYour Apple developer team id.
NUXT_PUSH_APNS_TOPICThe app's bundle id, for example com.example.app.
NUXT_PUSH_APNS_PRIVATE_KEYThe .p8 key. Literal \n stand for line breaks, so it fits one line.
NUXT_PUSH_APNS_SANDBOXtrue for development builds of the app: sends to api.sandbox.push.apple.com.
NUXT_PUSH_TIMEOUT_MSHow long one provider request may take. Default 10000. A request that takes longer counts as failed.

When every iOS app registers its FCM token (iOS through FCM), the service account is all the server needs: the NUXT_PUSH_APNS_* variables are only for sending to APNs directly.

How the providers authenticate:

  • FCM (HTTP v1): Push signs a short JWT (RS256) with the service account key, exchanges it for an OAuth access token and keeps the token until a minute before it expires. It sends to https://fcm.googleapis.com/v1/projects/<project_id>/messages:send, for Android and for iOS devices with an FCM token. FCM hands an iOS message on to APNs with the APNs key uploaded to the Firebase project.
  • APNs: Push signs a JWT (ES256) with the key id and team id, keeps it for 50 minutes and sends to https://api.push.apple.com/3/device/<token> over HTTP/2, on one session per host that it reuses and closes when it idles or fails.

Which provider a device uses

Every device is stored with the provider that issued its token, and its pushes go there:

DeviceProvider
AndroidFCM, always.
iOS, registered with provider: 'fcm'FCM. The device side of Push sends this when the app uses @capacitor-firebase/messaging.
iOS, registered with provider: 'apns'APNs. The device side sends this when the app uses @capacitor/push-notifications.
iOS, registered without a providerNUXT_PUSH_IOS: apns unless you set fcm.

NUXT_PUSH_IOS defaults to apns because a client that does not say is one built on @capacitor/push-notifications, whose iOS token is an APNs token. Sending that token to FCM would not just fail: FCM rejects it as invalid, and the device would be revoked. Set fcm only when your own iOS client registers FCM tokens without sending provider.

A device that registers its token again with another provider moves to it. An app update that switches plugin hands out a new token instead (the FCM token in place of the APNs token): the device side then sends the token it registered before as replaces, and the server removes the caller's device with that token, so the phone is not notified twice. Each phone moves at its next start.

iOS through FCM

FCM delivers to iOS too: it hands the message to APNs with an APNs key you upload to Firebase. The server then needs no HTTP/2 and no Apple credentials, which is what makes iOS work on Cloudflare Workers.

Upload your APNs key to Firebase

You do this once per Firebase project, in the Apple developer account and the Firebase console. Push cannot do it for you.

  1. In the Apple developer account, under Certificates, Identifiers & Profiles, Keys, create a key with Apple Push Notifications service (APNs) enabled, download the .p8 file and note its key id and your team id.
  2. In the Firebase console, open Project settings, Cloud Messaging, Apple app configuration, and upload the .p8 file under APNs Authentication Key with the key id and team id. Add the iOS app to the Firebase project first if it is not there (its bundle id, for example com.example.app).

One key serves development and production builds, so there is no sandbox setting on this path.

Register the FCM token in the app

Install @capacitor-firebase/messaging in the mobile app instead of @capacitor/push-notifications, and set it up as The mobile app describes. Push then registers the FCM token with provider: 'fcm', on iOS and on Android.

Set the service account on the server

Set NUXT_PUSH_FCM_SERVICE_ACCOUNT. The NUXT_PUSH_APNS_* variables can stay empty.

APNs needs HTTP/2

APNs refuses HTTP/1.1, and the global fetch of Node speaks only HTTP/1.1. So Push sends to APNs through node:http2, which it imports when the first push to APNs goes out.

Cloudflare Workers have no node:http2 client. There every push to APNs fails (it counts as failed, never as a dead token) and Push logs the reason once. On Workers, register the FCM token on iOS (iOS through FCM). To keep sending to APNs directly, send from a Node runtime, or through a relay: call setPushHttp2Transport(transport) from a Nitro plugin with a function that sends the request ({ origin, path, headers, body, timeoutMs }) to your relay and answers { status, body }.

Timeouts, dead tokens and misconfiguration

  • Timeouts. Every provider request is aborted after NUXT_PUSH_TIMEOUT_MS (10 seconds). A timeout counts as failed, never as dead, and the next push tries again.
  • FCM dead tokens. A device is revoked only for UNREGISTERED, or INVALID_ARGUMENT about the registration token itself. A bare 404 or NOT_FOUND can be a wrong project, so it is only failed.
  • APNs dead tokens. A device is revoked for 410 Unregistered. 400 BadDeviceToken also means a sandbox token sent to production (or the other way round), so when every device of one call that went to APNs gets it, none is revoked right away and a warning names push.apns.sandbox in the log; it counts as a refused push instead (next point). iOS devices with an FCM token follow the FCM rules above.
  • Three refused pushes in a row revoke a device. Each device keeps a count (push_devices.failures) of the pushes its provider refused for it in a row: a 4xx about the request for that device (BadDeviceToken included), not a timeout, an outage (5xx), bad credentials (401, 403), a payload too large (413) or a rate limit (429), and not a missing provider. A delivered push sets it back to 0; at 3 the device is revoked (counted in revoked). So the only iOS device of a user with a dead token is revoked after three pushes. Registering the device again clears the count and the revocation.
  • One device failing never fails the call, and a revoked device is not sent to again.
  • Misconfiguration is loud, not fatal. The server checks the settings when it starts and logs every invalid one: a NUXT_PUSH_DELIVERY or NUXT_PUSH_IOS it does not know, or a service account that is not valid JSON or lacks a field. Until it is fixed, sendPush logs the error once and counts every device as failed: it never throws into the caller (notifyUser), and it never falls back to the log delivery. Registering a device keeps working, with apns for an iOS device that did not name its provider. The log delivery is only chosen when no credentials are set at all.

Options

OptionTypeDefaultWhat it does
push.settings.delivery'log' | 'providers'unsetHow sendPush delivers. NUXT_PUSH_DELIVERY overrides it. Not the same as Notify's notify.push.driver, which Push fills (see Sending).
push.settings.autoRegisterbooleantrueRegister the device as soon as someone is signed in. false leaves it to your app.
push.pages.devicesboolean | stringtrueThe account devices page. true mounts it at /account/devices, a string at that path, false leaves it out (the routes stay).

Sending

dispatchPushNotification

Feature code sends push through Notify, like email and SMS:

await dispatchPushNotification({ userIds: [42], title: 'Shift tomorrow', body: 'You work 18:00', url: '/shifts/42', data: { shiftId: '42' } })
  // → { sent: 1, failed: 0, revoked: 0 }

Push registers itself as Notify's push driver (notify.push.driver, as a default: a driver your app sets in nuxt.config.ts wins). The driver calls sendPush below, so everything said there applies: the devices, the locale of title and body, the result and the log delivery. Your module depends on Notify only, and push goes out wherever Push is installed; without it, Notify's log driver logs the push.

This sends to the users without asking their channel choices. To respect them, use Notify's notifyUser: its push channel goes through this driver too.

sendPush

sendPush(event, { userIds: [42], title: 'Shift tomorrow', body: 'You work 18:00', url: '/shifts/42', data: { shiftId: '42' } })
  // → { sent: 1, failed: 0, revoked: 0 }

sendPush sends to every active device of the users. url is a path in the app, which opens when the notification is tapped. data values must be strings. It returns how many devices the provider accepted, how many failed, and how many tokens were dead and are now revoked.

title and body can be one text per locale, { da: 'Vagt i morgen', en: 'Shift tomorrow' }: each device gets the text for the locale it registered with (da-DK finds da), else English. notifyUser of Notify takes the same for its push content.

With the log delivery every device counts as sent. It writes the push title and the user and device ids to the server log, never the body, and warns once when it is active in production, where it almost always means credentials are missing.

sendPush and the driver

sendPush is what Push's Notify driver calls, and Push's own routes (the staff test push) call it directly. Feature code calls dispatchPushNotification or notifyUser of Notify, so it does not import from Push and works with any push driver.

Devices of another owner

A device can belong to something other than a user: a shared phone that another module pairs, such as an SMS gateway phone. Its row has no userId; ownerType names the kind of owner in the owning module's terms (sms-device) and ownerId the record. user is not an owner type. These devices never get a user's push, and Push has no routes for them: the owning module exposes its own, checks that the caller may act for the owner, and calls these helpers.

const owner = { type: 'sms-device', id: 'smd_123' }
await registerPushDeviceForOwner(event, owner, { platform: 'android', token, secret, locale: 'da' })
await sendPushToOwners(event, { owners: [owner], title: 'New message', body: 'Open the outbox', data: { wake: '1' } })
await listPushDevicesOfOwner(owner) // active devices, newest first
await removePushDevicesOfOwner(owner) // all of them; removePushDevicesOfOwner(owner, deviceId) removes one

registerPushDeviceForOwner follows the rules of a user's registration: idempotent per owner, bound to the installation secret, moved from another owner or user only with that secret (else 409 device_owned), replaces removed. It fires push:device:registered with device.userId null and device.owner set. sendPushToOwners has the delivery, locale, revocation and failure rules of sendPush. Nothing cascades when the owner's record is deleted, so the owning module calls removePushDevicesOfOwner.

Channel choices

Push keeps no channel choices. Topics are declared with Notify's extendNotificationTopics, notifyUser picks the channels, and Preferences stores each user's choices and serves the /account/notifications page. See Notifying a user.

The mobile app

Server mode owns the routes. The Capacitor app is a client of them.

Install a push plugin

Install one of the two, never both:

# The FCM token on iOS and Android: iOS goes through FCM, which also works from Cloudflare Workers.
pnpm add @capacitor-firebase/messaging firebase
# Or the APNs token on iOS: the server sends to APNs over HTTP/2 (Node only).
pnpm add @capacitor/push-notifications

npx cap sync

firebase is the web SDK that @capacitor-firebase/messaging imports for its web fallback. Push imports the plugin itself, only when it is installed, so a build without one still works. Without one usePushDevice().supported is false. When both are installed Push uses Firebase Messaging and warns at build time: the Firebase plugin must not run next to another push plugin.

Ask for the scope

A bearer token reaches the device routes only with the push:devices permission, so the app asks for it as a scope:

nuxt.config.ts of the app
export default defineNuxtConfig({
  modules: ['@frigear-nu/mobile', '@frigear-nu/push'],
  authentication: {
    mode: 'client',
    client: {
      scopes: ['openid', 'push:devices'], // plus the scopes the rest of the app asks for
    },
  },
})

The issuer and the API need Push in server mode, so the scope exists there. A token without it gets 403 insufficient_scope.

Set up Firebase and Apple

Both plugins:

  • Android: add your Firebase project's google-services.json to android/app.
  • iOS: in Xcode, add the Push Notifications capability to the app target.

With @capacitor-firebase/messaging (the plugin's setup guide has the details):

  • iOS: add the iOS app to the Firebase project and its GoogleService-Info.plist to ios/App/App in Xcode. Add the didRegisterForRemoteNotificationsWithDeviceToken, didFailToRegisterForRemoteNotificationsWithError and didReceiveRemoteNotification handlers the guide lists to AppDelegate.swift: they hand the APNs token to Firebase, which swaps it for the FCM token.
  • Upload your APNs key to Firebase (iOS through FCM). Without it FCM accepts the token but cannot deliver to the phone.
  • To show a notification while the app is open on iOS, set plugins.FirebaseMessaging.presentationOptions (for example ['badge', 'sound', 'alert']) in capacitor.config.

With @capacitor/push-notifications (the Capacitor guide):

  • iOS: create an APNs authentication key in the Apple developer account and set the four NUXT_PUSH_APNS_* variables on the server. Use NUXT_PUSH_APNS_SANDBOX=true for builds installed from Xcode. The server must run on Node (APNs needs HTTP/2).
  • To show a notification while the app is open on iOS, set plugins.PushNotifications.presentationOptions in capacitor.config.

Firebase Messaging returns the FCM token on both platforms. The Capacitor plugin returns the FCM token on Android and the APNs device token on iOS. Push sends the token together with the provider that issued it, which decides where the server sends (Which provider a device uses).

Register and unregister

With @frigear-nu/mobile installed, a plugin registers the device whenever someone is signed in: after a sign-in and when a stored session is restored at start. It asks for permission, registers with the OS and sends the token to POST /api/push/me/devices. Registering the same token again is harmless. It remembers the token it registered last, and when the OS hands out another one (a rotated token, or the FCM token after a switch from @capacitor/push-notifications) it sends the old one as replaces, so the server drops it.

The first time, it also generates the installation secret: 32 random bytes, kept in the app's local storage (frigear-push-installation) for as long as the app is installed. It goes with every registration and unregistration. The server stores only its SHA-256 hash, next to the token, and uses it to tell the installation apart from somebody who merely knows the token:

  • A token registered to another user moves to the caller only with the same secret: the phone changed hands and the next person signed in on it. Anyone else gets 409 device_owned, and the device stays where it was.
  • The same user registering the same token again is fine, with or without the secret.
  • replaces and POST /api/push/me/devices/unregister need the secret, and only remove the caller's device bound to that secret (or to none: a device registered without one).

Your own client (without usePushDevice) generates a secret of at least 16 characters once per installation, keeps it, and sends it as secret.

Set push.settings.autoRegister: false to ask at a better moment, and call it yourself:

const push = usePushDevice()
push.supported       // a native app with a push plugin installed
push.permission      // 'unknown' | 'unsupported' | 'prompt' | 'granted' | 'denied'
await push.register()   // asks for permission when needed, resolves false without it
await push.unregister() // removes this device on the server and forgets the token
Call unregister()beforeuseAuth().logout(). The server removes the device with the signed-in user's token, which is gone once the logout is done: the call then answers 401 and the phone stays registered to the previous user. A phone that is registered by someone else later moves to them (the app sends the same installation secret), but until then it would still receive the previous user's notifications.

Push does not send web push to a website (a service worker).

Account page

/account/devices lists the signed-in user's active devices: the platform, the provider (FCM or APNs), when each was last seen and when it was registered. Remove device asks for confirmation and calls DELETE /api/push/me/devices/:id. A removed phone is registered again the next time someone signs in to the app on it with notifications allowed.

Removing needs push:devices, like registering, so the app's token with the push scope can remove devices too. It is not session only: the app signs out with that token through POST /api/push/me/devices/unregister.

Admin tab

The Devices tab on the admin user page lists the user's devices, revoked ones included, with the provider each one's pushes go to (FCM or APNs; Server default for an iOS device registered before providers were stored, which follows NUXT_PUSH_IOS), and has a Send test push action that calls POST /api/admin/push/test. The action only shows for staff who hold push:send, and the test text follows each device's language.

Routes

Typed builders for every URL are in pushApi from @frigear-nu/push/api.

RouteNeedsWhat it does
GET /api/push/me/devicespush:devicesThe caller's active devices, newest first.
POST /api/push/me/devicespush:devicesRegisters a device: { platform, token, secret?, provider?, replaces?, appId?, locale? }. secret is the installation secret (16 to 256 characters). provider is fcm or apns (apns on Android is a 400). replaces is the token this installation registered before: the caller's device with it and the same secret is removed (replaces without secret is a 400). 409 device_owned when the token is another user's and secret does not match. Answers 201.
DELETE /api/push/me/devices/:idpush:devicesRemoves one of the caller's devices (204). Another user's device answers 404.
POST /api/push/me/devices/unregisterpush:devicesRemoves the caller's device by { token, secret } (204), also when it is unknown, another user's or bound to another secret (then nothing is removed).
GET /api/admin/users/:id/push-devicespush:manageA user's devices, revoked ones included.
POST /api/admin/push/testpush:sendSends a test push to { userId } and answers { sent, failed, revoked }.

A token is never part of a device in a response.

Registering a token the caller already has makes it active again. A token registered to another user moves to the caller only with the installation secret it is bound to (see Register and unregister): a phone that changes hands belongs to whoever signed in last on it, and knowing a token is not enough to take it.

Permissions and scopes

PermissionWhoWhat it allows
push:devicesevery signed-in userTheir own devices. A policy keeps it to the user's own devices.
push:managethe admin roleSee other users' devices.
push:sendthe admin roleSend a test push.

The push scope holds push:devices. Use it, or the permission itself, in a token or in authentication.client.scopes. See Auth and scopes.

Hooks

HookContextWhen
push:device:registered{ event, device }A device registered or registered again, after it is stored. device has no token; device.userId is null for a device of another owner (device.owner).

Next steps

  • Notify – dispatchPushNotification, notifyUser and the topic registry.
  • Preferences – where users choose their channels per topic.
  • Mobile – the Capacitor app that registers devices.
  • Shifts – a module that sends reminders and swaps on its topics.
Copyright © 2026