---
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 tool 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)).

## What your AI tool 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 tool:** Check the following before starting.

- A connected, signed-in AI tool ([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 tool 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 its providers, `apns` and `fcm`, as step 3's call does without Apple's `environment`. 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.

### 3. Configure the providers

Call `configure_push` once for each environment the application has, naming the secrets you stored. Each provider is optional, and a provider set to `null` is removed. The platform checks that each named secret is stored for that environment, and `read_push` returns the configuration with the names alone.

```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"
  }
}
```

Apple's `environment` selects the gateway: `sandbox` for a debug build, `production` for a store build. On an application with one environment, both builds register on the production realm, whose configuration names one gateway at a time, so a debug build gets no push while it names `production`. To test a debug build while production serves the store build, [turn on a development environment](/cloud/guides/turn-on-development-and-promote/) and configure `sandbox` there.

While the manifest's `push` entry names a provider, `configure_push` refuses to change that provider's members or remove it, `manifest_owned_field`. It still sets Apple's gateway for each environment.

### 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.

```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 again whenever 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.

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. 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 tool takes the package as [Use the 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 members and their limits, and `sendToDevices` for named installations. One send can list up to 500 users or installations, and a device whose platform has no configured provider is not accepted. Each accepted delivery counts toward the application's monthly ceiling of 1,000,000 push deliveries, the same for either size. A send that would pass it is refused whole ([Size and usage](/cloud/guides/plan-and-usage/)). A send that accepts no device is never refused for this ceiling.

The client never retries a send. After `push_answer_unreadable`, the send may already be queued; do not repeat it 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 send once to a registered device you own. 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

The send returns a `messageId`, the count of deliveries accepted, and the users or installations that had no registration. The platform's background job sends each accepted delivery to its provider within seconds, retries a transient failure twice, and marks a device the provider reports gone. Such a device receives nothing more until the app registers it again. The platform records a delivery when the provider accepts it; that does not confirm the phone received or displayed the notification.

`read_push` returns the device counts by platform, the deliveries of the last hour by outcome, and the month's accepted count beside the push ceiling. The application's log stream contains one line per delivery under the counters `push_delivered` and `push_failed` ([Read logs and counters](/cloud/guides/read-logs-and-counters/)). A failed line gives its `failure` and a `provider_reason`, which is one of three words, never 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 provider credential named in the configuration could not be read or is not a usable key or file. Store it again with `store_secret`, and call `configure_push` again.

## Refusals

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

Where a `push` entry in the manifest sets the providers, `name_bound_to_setting` comes from `submit_manifest` or `create_environment` instead, and the 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 | A setting binds the name: the manifest's `settings`, the running copy of either environment, or a deploy, promote, or redeploy in flight to one. 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. | Change the entry in the manifest and resubmit it with `submit_manifest`. |
| `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, resubmit it, and register devices after sign-in. |
| `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. |
| `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.
