---
title: Send push notifications
description: Store the provider credentials as secrets, declare the push service, register devices from the app, and send a notification from the backend.
slug: /guides/send-push-notifications
order: 13
visibility: public
redirects_from: []
---

# Send push notifications

Prompt:

> Let our backend send push notifications to the users of our iPhone and Android app.

Also works: "Notify a user when their order ships." "Push to every device a user has signed in on." "Stop sending to phones that uninstalled the app."

Your AI assistant stores each provider's credential ([step 1](#1-store-the-credentials-as-secrets)), declares the push service ([step 2](#2-declare-the-push-service)), and, unless the manifest names the providers, configures them with `configure_push` ([step 3](#3-configure-the-providers)). The app then registers each device after sign-in ([step 4](#4-register-the-device-from-the-app)), and the backend sends with the Push package ([step 5](#5-send-from-the-backend)).

Before sending a test notification, check the phone and its backend.

- Confirm which build is installed and which app hostname it calls.
- Sign in on the phone and confirm the device is registered in that environment.
- Call `read_push` for that environment. On iPhone, match the Apple gateway to the installed build's `aps-environment`. On Android, confirm that the build uses the configured Firebase project.

## What your AI does

- Reads the `mobile-backend` [skill](/cloud/concepts/glossary/#skill) (`read_context`, id `skill:mobile-backend`) and follows its push rule.
- Stores each provider's credential from its file with `store_secret`, as step 1 describes.
- Confirms the configuration and the registered devices with `read_push`.
- Writes the backend's send with the [Push](/cloud/backend-packages/push/) package's client, as step 5's sample does, and tests it over the package's [test double](/cloud/concepts/glossary/#test-double).
- Asks you for the Apple team and key identifiers, the bundle identifier, and the Firebase project, where the prompt does not give them.

## What you need

- An app whose users sign in through the realm ([Sign in from a native app](/cloud/guides/sign-in-from-a-native-app/)), so each device is registered under a user.
- For iPhone: an Apple Push Notifications signing key, the `.p8` file, with its key identifier, your team identifier, and the app's bundle identifier.
- For Android: a Firebase project with a service-account JSON file that may send messages.

## Before your AI starts

**For the AI assistant:** Check the following before starting.

- A connected, signed-in AI assistant ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)).
- An application whose manifest declares the accounts service, submitted.
- The credential file for each provider you will use: Apple's `.p8` key for iPhone, Firebase's service-account JSON for Android, or both. The command line `store_secret` returns reads each file on the developer's machine; do not read its contents into a chat or a tool call.

## Steps

### 1. Store the credentials as secrets

Store the Apple key's text and the Google file's text as secrets of the application, under names such as `apns-key` and `fcm-service-account`. Your AI assistant calls `store_secret` with each file as `value_file` and runs the command line the call returns, because a key file's text was never in the conversation. [Store a secret](/cloud/getting-started/store-a-secret/#2-supply-the-value-without-exposing-it) describes the line. Store each secret in every environment that sends push notifications. The same secret name can hold a different value in each environment.

### 2. Declare the push service

Add `{"kind": "push"}` to the manifest's `services` and resubmit it. The declaration provisions nothing by itself; it makes the configuration and the routes available.

The entry can also name the `apns` and `fcm` providers, as the call in step 3 does. Leave out Apple's `environment` when you name the providers here. Each submission then configures each environment the application has, and `create_environment` configures development when it adds it, so step 3 is needed only to change Apple's gateway. [Author the manifest](/cloud/guides/author-the-manifest/#configure-sign-in-and-push-in-the-manifest) shows the entry. If you submit the manifest before storing a named credential, the configuration can still be recorded. If it is still missing at deployment, check the outcome for `provider_credentials_missing` in the affected environment, then store the named credential there.

### 3. Configure the providers

Read `read_push` for each environment before changing it. If the manifest sets a provider, edit its entry and call `submit_manifest`. `configure_push` can change settings the manifest leaves open, including Apple's gateway. Omit a provider to keep its setting. To switch off a provider the manifest sets, remove its entry and submit the manifest first. This leaves the saved provider in place. Then pass `null` to `configure_push` for that provider in each environment where it should stop. Check `read_push` in each one. A delivery already being processed may finish.

```json
{
  "application": "<application id>",
  "environment": "production",
  "apns": {
    "team_id": "ABCDE12345",
    "key_id": "KEYID12345",
    "bundle_id": "com.example.app",
    "key_secret_name": "apns-key",
    "environment": "production"
  },
  "fcm": {
    "project_id": "example-app-12345",
    "service_account_secret_name": "fcm-service-account"
  }
}
```

Set Apple's `environment` to match the installed build's `aps-environment` entitlement. Use `sandbox` for `development` and `production` for `production`. Apple sets the entitlement from the provisioning profile by default. Check the entitlement on the build you will install. See [Apple's APS Environment entitlement](https://developer.apple.com/documentation/bundleresources/entitlements/aps-environment).

With one Turn Zero environment, both builds register on the production realm, which uses one Apple gateway at a time. A build registered with one Apple gateway cannot receive notifications sent through the other. To test a build with the development entitlement while production serves a build with the production entitlement, [turn on a development environment](/cloud/guides/turn-on-development-and-promote/) and configure `sandbox` there. Point the debug build at the development hostname, then sign in to the development realm and register the device there.

`configure_push` returns `manifest_owned_field` if you try to change or remove a provider the manifest sets. It can still set Apple's gateway for each environment. After saving, Cloud checks the credential names again. If a name has disappeared or is now bound to an app setting, Cloud tries to restore that provider's previous setting. The other provider's change can stay. If setup fails after saving or you lose the reply, call `read_push` for that environment before retrying.

### 4. Register the device from the app

After sign-in, the app asks the device's operating system for a device token and registers it under the signed-in user. Send a `PUT` to `/__account/devices/<installation id>` on the application's own hostname, with the bearer token or the cookie from sign-in. The app creates the installation identifier once and keeps it. Use a random value such as a UUID, never derived from user IDs, device names, or other guessable information. Use 1 to 128 letters, digits, dots, dashes, or underscores. A new registration returns HTTP 201. An update returns HTTP 200. Both responses include the device details.

In an Expo app, get the native token from `expo-notifications` with `getDevicePushTokenAsync()` and send its `data` value as `token`. `getExpoPushTokenAsync()` returns a token for Expo's push service, which this route does not accept. See [Expo's guide to sending directly through FCM and APNs](https://docs.expo.dev/push-notifications/sending-notifications-custom/).

```json
{
  "platform": "ios",
  "token": "<the device token as the platform handed it>",
  "client_id": "com.example.app"
}
```

Set `platform` to `ios` for an iPhone or `android` for an Android device. Include `client_id` only where the app signed in through a [native client](/cloud/concepts/glossary/#native-client) the realm declares. A registration is kept even if its platform has no provider configured yet. Once you configure that provider, new sends can include the device; earlier sends did not queue a delivery for it.

Register after each new sign-in, even if the device token stays the same. Register again if the operating system issues a new token. A user can have at most twenty registrations, and a twenty-first ends the oldest. A token another user registers moves to that user. A `DELETE` on the same route removes a registration.

For `PUT /__account/devices/<installation id>`, an installation already registered to another user of the same app and environment must still have the same platform and device token to move. A different platform or token returns HTTP 409 `installation_held_by_another_user`. This also applies when the provider reported the standing registration gone. The refusal changes no registration and reveals no details about the other user or registration. Create a new installation ID on this device, save it, and use it to register again. Give your backend the new ID to replace the old one.

A user can update their own installation with a new token and receive HTTP 200. When another person signs in on the same device and the platform and token still match, the registration moves and the reply includes `moved: true`.

A registration ends with the session it was made under: sign-out, a revoke from the session list, or a suspension with `set_end_user_standing` removes it, and the app registers again after the next sign-in. A session that merely expires leaves it in place. A sign-out made offline does not reach the platform, so the session and its registration stay until the user ends that session from the session list. Deleting a user removes their registrations, their waiting deliveries, and the records of those already sent.

### 5. Send from the backend

The backend sends with the [Push](/cloud/backend-packages/push/) package's client, built once from `TURNZERO_CLOUD_API` and `TURNZERO_CLOUD_APP_TOKEN`, the [platform credential](/cloud/concepts/glossary/#platform-credential). The credential identifies the application and its environment. Your AI assistant takes the package as [Use the feature package library](/cloud/guides/use-the-library/) describes.

This module tells a user their order shipped, on every device they registered. A test runs this sample over the Push package's test double and checks the send, an unregistered user, and a refused send.

```js
// src/notify.mjs: notifyShipped(userId, order) pushes "Your order shipped" to the user's devices.
import { createPushClient, PushRefusal } from '@turnzero/push';

// The platform's origin and this copy's credential, from the settings it receives.
const push = createPushClient({ api: process.env.TURNZERO_CLOUD_API, token: process.env.TURNZERO_CLOUD_APP_TOKEN });

export async function notifyShipped(userId, order) {
  try {
    const sent = await push.send([userId], {
      notification: { title: 'Your order shipped', body: `Order ${order.id} arrives ${order.eta}.` },
      data: { order_id: order.id },
      collapseId: `order-${order.id}`,
    });
    // accepted counts the deliveries queued; unknownUsers had no registered device.
    return { accepted: sent.accepted, unregistered: sent.unknownUsers };
  } catch (error) {
    // Record the error without retrying; an unreadable answer leaves the send outcome unknown.
    if (!(error instanceof PushRefusal)) throw error;
    console.error(`push send error ${error.refusal}: ${error.detail}`);
    return { refused: error.refusal };
  }
}
```

[Push](/cloud/backend-packages/push/#what-it-provides) lists the message's fields and limits and explains `sendToDevices` for named installations. One send can list up to 500 users or installations. A device whose platform has no configured provider is skipped. Each queued delivery counts toward the application's monthly push limit. Both sizes start with a limit of 1,000,000 deliveries. Check the current limit with `read_push` ([Size and usage](/cloud/guides/plan-and-usage/)). If the send would pass that limit, the platform refuses the whole send.

The client never retries a send. After `push_answer_unreadable`, a network error, or an error reading the response, the send may already be queued. Do not repeat the send automatically. The sample returns no `accepted` count when an error leaves that count unknown.

[Deploy the changed backend](/cloud/getting-started/ways-to-deploy/), then register a device you own against the same environment's realm and send once to it. If development is on, deploy there first, check the send, and [promote the tested version to production](/cloud/guides/turn-on-development-and-promote/#promote-to-production) once the owner agrees.

## Expected result

Check what happened at three points.

1. **Queued.** The send returns a `messageId`, a queued count, and any users or installations with no valid registration. If the count is zero and those lists are empty, check that the environment has a provider for the devices' platform.
2. **Accepted by the provider.** Call `read_push` for the same environment. Its `delivered` count records provider acceptance.
3. **Shown on the phone.** Check the test device itself to confirm it displays the notification.

A background job sends queued notifications and retries a transient failure twice. If the provider says a device is gone, the device receives nothing more until the app registers it again.

`read_push` returns device counts and one hour of delivery outcomes for the selected environment. `delivered` counts notifications the provider accepted. The device may still fail to receive or display one. `pending` includes deliveries waiting in the queue and deliveries being attempted, regardless of age. The monthly accepted count and quota cover the whole app.

Read `push_delivered` and `push_failed` for [counter totals](/cloud/guides/read-logs-and-counters/). The platform also logs delivery outcomes. A delivery means the provider accepted it. A failed line gives its `failure`. When cleanup ends a delivery whose claim was left unfinished, the line gives `failure: orphaned` and omits `provider_reason`. Other failed lines may carry a `provider_reason`, one of the three words below in place of the provider's own message.

- `provider_refused`: the provider refused the notification or its provider token through the last attempt, or reported the device gone.
- `provider_unreachable`: the provider could not be reached, or kept returning a transient failure, through the last attempt.
- `credential_unreadable`: the delivery job could not read the provider credential, or the key or file was missing or unusable. The job retries failed reads. It stops that delivery if the store confirms the credential is missing or the value is unusable. Check the provider and the credential name with `read_push`. Store the correct value in the affected environment. If the name must change, update it in the manifest or through `configure_push`, depending on which one sets that provider.

## Refusals

See the [refusals reference](/cloud/reference/refusals/) for other platform errors.

If a setting takes over a push credential name after the platform records the manifest's `push` providers, `submit_manifest` or `create_environment` returns `name_bound_to_setting`. The submitted manifest stays recorded ([Author the manifest](/cloud/guides/author-the-manifest/#refusals)).

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `push_not_declared` | 409 | `configure_push` or `read_push` on an application whose manifest declares no push service. | Add `{"kind": "push"}` to the manifest's services and resubmit it. |
| `custody_entry_missing` | 409 | A named secret is not stored at that environment's scope. | Store it with `store_secret` for the application and the environment, then configure again. |
| `name_bound_to_setting` | 409 | The name is already bound in the manifest's `settings`, in the app version running in either environment, or in an ongoing deploy, promote, or redeploy to either environment. The `detail` names the setting and where it is bound. | Store the credential under another name and configure with that name. A running copy keeps the binding until that environment's next deploy or promote of a manifest without it. |
| `manifest_owned_field` | 409 | `configure_push` would change or remove a provider the manifest's `push` entry names. The `detail` names each field. | To change the provider's settings, edit the manifest and submit it. To switch it off, remove its entry and submit the manifest, then pass `null` for that provider to `configure_push` in each affected environment. |
| `push_not_configured` | 409 | A send reached an environment with no provider configured. | Configure a provider with `configure_push`. |
| `realm_not_declared` | 404 | A send reached an application whose manifest declares no accounts service, so no device is registered under a user. | Add `{"kind": "accounts"}` to the manifest's `services` and call `submit_manifest`. Register devices after sign-in before retrying the send. |
| `platform_credential_required` | 403 | A send arrived under a session or a minted token. | Send under the platform credential from the backend. |
| `usage_over_quota` | 429 | The send would pass the application's monthly push ceiling. | Wait until the next UTC month starts. |
| `plan_quantity_unset` | 409 | The app has no configured monthly push limit. The send queues nothing, even if there are no eligible devices. | Check `quota` in `read_push` and ask the platform operator about the missing limit. |
| `installation_held_by_another_user` | 409 | Another user of this app and environment already registered this installation with a different platform or device token. The service changes no registration. | Create a new installation ID on this device, save it, and use it to register again. Give your backend the new ID to replace the old one. |
| `invalid_request` | 400 | A send's or a registration's body has a malformed member, which the `detail` names, or a registration with the session cookie came from another origin. | Correct the named member, or register from the application's own origin or with the session as a bearer. |
| `session_required` | 401 | A device registration or removal had no end-user session. | Register after sign-in, with the session as the cookie or as a bearer. |
| `invalid_client` | 400 | A registration named a `client_id` the realm does not declare. | Pass the declared client the app signed in through, or no client. |

## Related

- [Push](/cloud/backend-packages/push/) describes the client, the message's members, its refusals, and its test double.
- [Sign in from a native app](/cloud/guides/sign-in-from-a-native-app/) opens the sessions the device routes are registered under.
- [Manage end users](/cloud/guides/manage-end-users/) covers the realm the registrations live in and the users' deletion.
- [Size and usage](/cloud/guides/plan-and-usage/) gives the monthly push ceiling and the other application limits.
- [Read logs and counters](/cloud/guides/read-logs-and-counters/) explains how to read the delivery counters and lines.
