Push #
On this page
Push lets your application's backend send a notification to your users' phones and tablets. Turn Zero Cloud delivers it to iPhones through Apple and to Android devices through Google. Your backend lists the users or the devices, and the platform finds each device your app registered.
This package is your backend's side of that service. Its client sends one message under your application's platform credential. It reports what the platform accepted from the send, and it throws a typed refusal that includes the platform's refusal name.
Use it when #
Use Push when your backend must tell a signed-in user something while the app is closed: a game ended, an order shipped, a turn is waiting. Your app must sign its users in through your application's realm and register each device after sign-in. Send push notifications covers the credentials, the declaration, the device registration, and the send route.
Do not use it for a web page in a browser or for a text message. Neither is offered.
What it provides #
- A client,
createPushClient, which The client describes. The module has no dependencies and keeps no state. - A send to users. The method
send(users, message)queues a delivery for each registered device of the named users that has a configured provider. Use the user identifier returned by the realm. - A send to devices. The method
sendToDevices(installations, message)takes the installation identifiers your app registered. It skips devices without a configured provider for their platform. - The response. Each send returns
messageId,accepted(the number of deliveries queued),unknownUsers, andunknownDevices. The unknown lists give the requested users or installations with no valid registration.acceptedcan be zero even when both lists are empty. - A typed refusal. A platform refusal, or a response whose body the client reads but cannot interpret, makes the send throw a
PushRefusal. Itsrefusalmember gives the refusal name andmembersgives any extra values. - A test double,
createPushDoubleat@turnzero/push/testing, which records calls and accepted sends. Test with the double shows it in use.
| Message member | Required | What it contains |
|---|---|---|
notification.title |
Yes | 1 to 256 characters, counted using JavaScript string length. |
notification.body |
Yes | 1 to 4,000 characters, counted using JavaScript string length. |
notification.badge |
No | A whole number from 0 to 99,999 for the app's icon. |
notification.sound |
No | A bundled sound name or default. Use 1 to 64 letters, digits, dots, dashes, or underscores. |
data |
No | String values for the app, at most 4,096 bytes serialized. Keys have 1 to 64 characters. The key aps is reserved. |
ttlSeconds |
No | How long an offline device's notification is kept. Use a whole number of seconds from 0 through four weeks. The default is one day. |
collapseId |
No | An identifier of 1 to 64 characters the provider uses to combine notifications. It does not prevent every duplicate delivery. |
priority |
No | high by default, or normal. |
With JavaScript string length, some characters, including many emoji, count as two.
Availability #
Version 0.5.5 is the package's current version, and this page describes it. Until the library's next publish, read_library can return an earlier version without every change described here. Use the version it returns.
The entry includes the testing subpath. It also contains the compiled modules, the product statement and detailed contract, and the integration guide. Turn Zero Cloud runs the push service. Call read_push to see device counts, the last hour's outcomes, and the month's count against the application's push ceiling.
Related feature packages #
Account signs users in and tells your backend who they are. Secrets stores the Apple key and the Google service-account file by name. Logging records the delivery counters and one line per delivery.
The client #
The package is published in the library as the npm package @turnzero/push, not on the npm registry; Use the feature package library installs it with one line. Send from the backend shows a send from a backend route, and a test runs it.
The function createPushClient(options) builds the client from one of two forms:
| Option | Meaning |
|---|---|
api, token |
The platform's origin and the application's platform credential, from TURNZERO_CLOUD_API and TURNZERO_CLOUD_APP_TOKEN. |
environment |
development or production, the environment header's value, where a credential needs one. The platform credential takes none, and the route refuses a value that contradicts it. |
fetch |
The fetch-shaped function the client sends through, the global fetch by default. |
transport |
A function you provide, (path, init), that adds the origin and credential. The test double provides one. This option replaces api, token, environment, and fetch. |
Use transport by itself or supply api and token together. Mixed options, a missing token, an invalid HTTP or HTTPS origin, or a missing fetch implementation throw PushClientError with code client_options. If the runtime has no global fetch, pass a fetch option with api and token. The two sends, send(users, message, { signal }) and sendToDevices(installations, message, { signal }), return a promise of { messageId, accepted, unknownUsers, unknownDevices }. A platform refusal rejects with PushRefusal. Errors from the transport or while reading the response pass through to the caller. Refusals lists the named refusals.
Refusals #
Branch on the refusal's name, never on its message. A PushRefusal has refusal, status, detail, and members. These are the refusals a send meets most often; the refusals page lists all of the platform's refusals, with the cause and remedy of each.
| Refusal | Status | Meaning |
|---|---|---|
invalid_request |
400 | A member of the message is malformed, and the detail identifies it; or a member contains a NUL character (U+0000) or an unpaired UTF-16 surrogate, which the detail identifies instead. |
end_user_credential_not_admitted |
403 | The request used an end-user session. The platform refuses it before checking the push route itself. |
platform_credential_required |
403 | The send request used a session or a minted token. |
push_not_configured |
409 | The environment has no provider configured. |
realm_not_declared |
404 | The application declares no accounts service. |
usage_over_quota |
429 | The send would pass the application's monthly push ceiling. |
push_answer_unreadable |
As received | The send may already be queued. read_push gives totals for the environment and cannot identify this send. If you received a message ID, look for it in the delivery logs. If you cannot establish the result, leave it unknown. Retrying automatically can send the notification twice. |
A send refused usage_over_quota queued nothing. Its members give the month's count, the ceiling, and the send's own deliveries.
What an application must do #
Set the service up as Send push notifications describes in its steps 1 to 4, and register each device from your app after sign-in.
Send once for each event. If the network fails or the client cannot read the response, the platform may already have queued the notification. Leave the queued count unknown unless you received it. Do not retry automatically. A collapseId can combine notifications, but a resend can still deliver twice.
Keep a refused send from failing the request that made it. Record the refusal, and respond to the request.
Test with the double #
The factory createPushDouble(options) from @turnzero/push/testing responds to a send as the platform does, from the devices and the monthly quota the test gives it. Build the client with createPushClient({ transport: double.transport }), or pass double.fetch as the client's fetch. Register devices with double.register(device). A test runs this sample over the double.
Read every call in double.calls. Read accepted sends in double.sends, including sends the platform accepts for zero devices.
import assert from 'node:assert/strict';
import { createPushClient, PushRefusal } from '@turnzero/push';
import { createPushDouble } from '@turnzero/push/testing';
// A monthly allowance of one delivery, and one registered phone.
const push = createPushDouble({ quota: 1 });
push.register({ installation: 'phone-1', user: 'user-1', platform: 'ios' });
const client = createPushClient({ transport: push.transport });
const sent = await client.send(['user-1', 'user-2'], { notification: { title: 'Game over', body: 'You stumped it.' } });
assert.equal(sent.accepted, 1);
assert.deepEqual(sent.unknownUsers, ['user-2']);
assert.equal(push.sends.length, 1);
// The month's one delivery is spent, so the next send is refused by name and queues nothing.
await assert.rejects(client.send(['user-1'], { notification: { title: 'Again', body: 'One more.' } }), (error) => error instanceof PushRefusal && error.refusal === 'usage_over_quota');
The double uses the push route's own refusal names, which Refusals lists. It can also simulate a transport failure.
| Result | Cause | Check or remedy |
|---|---|---|
push_not_configured |
The double was created with both providers off, providers: { apns: false, fcm: false }. |
Leave a provider on. |
realm_not_declared |
The double was created with accounts: false. |
Leave the accounts service declared. |
platform_credential_required, end_user_credential_not_admitted |
The double was created with credential: 'session', 'minted', or 'end_user'. |
Leave the credential at the default, 'platform'. |
usage_over_quota |
The sends passed the quota the test gave. |
Raise quota, or reset() between tests. |
| A scripted refusal | refuseNext(name) sets the refusal name. |
Assert the name you supplied. |
| Transport failure | failNext(error) makes the send reject with that error. failNext() defaults to a TypeError with the message fetch failed. There is no refusal name. |
Assert that the send rejects with the error you passed. |