whitebear
← direct-push

v1.0.3 · MIT · la documentación está en inglés

direct-push v1 Docs

npm install direct-pushv1.0.3

Push notifications from your own backend. Straight to Apple (APNs), Google (FCM HTTP v1) and the browsers (Web Push), with no Firebase Admin SDK, no Expo, no third-party service and zero dependencies: WebCrypto and fetch, on Deno, Node, Bun and Workers.

npx direct-push init
# → asks which platforms, takes the .p8 and the service account, checks them with Apple and Google,
#   makes the Web Push keys, writes it all to .env, and asks where the server runs: for Supabase or
#   Cloudflare Workers it shows the secrets command and runs it if you say so (no value is ever printed)

npx direct-push app
# → in an app's folder: finds the web, Android and iOS/macOS projects, and adds the client to those you
#   check (the web's sw.js, JitPack and the Gradle dependency, the Swift package), once; the rest as steps

npx direct-push vapid-keys
# → VAPID_PUBLIC_KEY=… and VAPID_PRIVATE_KEY=…, a key pair for Web Push

APNS_KEY_ID=… APNS_TEAM_ID=… APNS_BUNDLE_ID=com.example.app APNS_PRIVATE_KEY="$(cat AuthKey_ABC123DEFG.p8)" \
  npx direct-push send --apns <device token> --title "Hello"
# → what APNs answered, as JSON: sent (and which environment the token belongs to), or why not

Nothing to sign up for but what the platforms themselves ask: an Apple developer team (for its key) and a Firebase project (for its service account); Web Push takes a key pair you make yourself. Beside the senders it has a server that keeps each user's devices and an outbox with retries, on the database you already have, and small clients for iOS, Android and the web that register a device with it.

Runtime APNs FCM and Web Push From
Deno, Supabase Edge Functions Yes: Deno's fetch speaks HTTP/2 Yes direct-push (npm:direct-push)
Node 22.18+ (a server, Vercel and Netlify functions, AWS Lambda), Bun Yes, over node:http2: their global fetch speaks HTTP/1.1, which APNs refuses Yes direct-push/node
Cloudflare Workers No: a Worker's fetch reaches APNs over HTTP/1.1 Yes direct-push/worker
Browsers The subscription, and showing what arrives direct-push/web, direct-push/sw

What each one gets from APNs' sandbox (a POST to /3/device/00 with no provider token, which APNs answers 403 {"reason":"MissingProviderToken"} over HTTP/2), checked in November 2026: Deno 2.9.8's fetch gets that answer. Node 24.13.1's global fetch fails with HTTPParserError: Response does not match the HTTP/1.1 protocol, Bun 1.3.14's with Malformed_HTTP_Response, and on both direct-push/node gets the answer. A Worker under wrangler dev (workerd, wrangler 4.50 and 4.169) fails with Network connection lost or invalid HTTP version parsed, while FCM answers it normally; a deployed Worker wasn't tried. On Node and Bun the root's apns() says so in its result (config, with a reason that points at direct-push/node), so it is never retried for nothing.

Database (for the server) Adapter
SQLite (a file: node:sqlite, better-sqlite3, bun:sqlite) direct-push/sqlite
Postgres (Supabase, Neon, Vercel Postgres, RDS, local, PGlite) direct-push/postgres
Cloudflare D1 direct-push/d1

Why straight to the services

Every service already has an HTTP API: APNs takes a JWT signed with the team's .p8 key, FCM an access token Google trades for a JWT signed with a service account's key, a browser's push service a message encrypted for its subscription with a JWT of its own (VAPID). None of it needs an SDK, a relay or an account with somebody else, and sending from here means the answers come back here: which device is gone, which environment a token belongs to, which key is wrong. Those answers are where push goes wrong, so they are where the care went.

What it does, and why:

  • An APNs token's environment is learnt, not guessed. A token from an Xcode build lives in the sandbox, one from TestFlight or the App Store in production, and a Release build signed for development is the one that catches people out. A device of unknown environment is tried in the default one, a BadDeviceToken is always tried in the other (even when the device said which it was: trusting the label deleted good tokens), and the result says which one took it, for the server to keep.
  • Dead means certainly dead. APNs' 410 (with when, so a token registered again since is kept), BadDeviceToken from both environments, FCM's UNREGISTERED, a push service's 404 or 410. A failure that can work later (429, 5xx, the network, a timeout) is retried; one on our side (a key, the topic, the project, a JWT a push service refuses) is reported, and never deletes a device.
  • A wrong setting can't wipe the devices. A wrong bundle id makes APNs call every token DeviceTokenNotForTopic, a wrong Firebase project makes FCM call every token SENDER_ID_MISMATCH, a new VAPID key makes a push service say every subscription is another key's: each looks like a dead device, and believing them would delete every one. So such an answer is believed only once the same setting has had a push go through there (on the web, through that push service): a wrong setting never has, so one test phone or a thousand, a fresh process or one that has run for weeks, nothing is deleted, and the results say config. And when at least three of the recent answers say so, and they are at least half of them, they count as our side even then.
  • At least once. The outbox leases what it sends and writes down how it went only afterwards, so a crash, a timeout or a 503 means the push goes again later instead of being lost, and a dedupe key keeps a job that runs twice from queueing twice.
  • Nothing for a user to lean on. Whoever registers a browser picks the address the server sends to, so only the browsers' push services are sent to (Chrome's FCM, Firefox's, Safari's and Edge's), and only the first 4 KB of an answer is read. A user keeps twenty devices at most, a tick stops starting pushes after a minute (the rest wait for the next one, without losing a try), and a test push a user asks for never raises an alert.
  • The small print. Each sender makes its token once however many pushes ask for it at the same time (twenty signings at a cold start is how APNs answers TooManyProviderTokenUpdates); on Node each key keeps one HTTP/2 connection to APNs, reused, with one token on it, as Apple asks (never two teams on one connection, never a token renewed every request); every push has a lifetime (a day unless given), so a phone that was off for a week isn't woken by last week; sizes are checked before sending; and RFC 8291's own example is one of the tests.

Quick start

On Supabase

Edge Functions run on Deno, whose fetch reaches APNs as it is. One function is the server: the devices and the outbox in your project's own Postgres (push_devices, push_outbox, beside your tables, so your SQL can queue pushes too), the routes your apps register at, and /push/tick, which pg_cron calls every minute. See examples/supabase, which also has a function that only sends.

// supabase/functions/push/index.ts
import postgres from "npm:postgres@3";
import { pushFromEnv } from "npm:direct-push@1";
import { createPushServer } from "npm:direct-push@1/server";
import { postgresJsSql } from "npm:direct-push@1/postgres";

const server = createPushServer({
  sql: postgresJsSql(postgres(Deno.env.get("SUPABASE_DB_URL")!, { prepare: false })),
  push: pushFromEnv((name) => Deno.env.get(name)),
  authorize: signedIn,                     // the user's id from their session: see the example
  cronSecret: Deno.env.get("PUSH_CRON_SECRET"),
});
Deno.serve((req) => server.fetch(req));
supabase functions deploy push --no-verify-jwt     # it checks the session itself; pg_cron sends the cron secret
supabase secrets set APNS_KEY_ID=… APNS_TEAM_ID=… APNS_BUNDLE_ID=… APNS_PRIVATE_KEY="$(cat AuthKey_ABC123DEFG.p8)"
supabase secrets set FCM_SERVICE_ACCOUNT="$(cat service-account.json)" PUSH_CRON_SECRET=…

On a server, with Node

import { createPush, pushFromEnv } from "direct-push/node";
import { createPushServer } from "direct-push/server";
import { openSqlite } from "direct-push/sqlite";

const server = createPushServer({
  sql: await openSqlite("./push.db"),           // Node's node:sqlite; on Bun, or with better-sqlite3, sqliteSql(new Database("push.db"))
                                                // from direct-push/sqlite; or pgSql(new pg.Pool(…)) from direct-push/postgres
  push: createPush(pushFromEnv(process.env)),   // direct-push/node's: APNs over HTTP/2
  authorize: (req) => userIdFrom(req),          // your sign-in: the user's id, or null
});

setInterval(() => server.tick().catch(console.error), 60_000);   // the clock: sends what is due

Give the server a push made by direct-push/node's createPush: given only options it makes its own with the root's, whose APNs pushes go through the global fetch. Its connections to APNs (one for each key in use) let the process exit when nothing else holds them; await apnsFetch.close() closes them now.

server.fetch is a plain Request → Response, and Node's node:http speaks neither: examples/node has the dozen lines between them (or hand fetch to Hono, or a Next.js route handler), and a script that only sends. On Bun, Bun.serve({ fetch: server.fetch }) takes it as it is; openSqlite needs node:sqlite, which Bun 1.3 doesn't have, so the database there is sqliteSql(new Database("push.db")) with bun:sqlite's Database.

A push can, rarely, arrive twice. direct-push/node sends a request once more only when APNs provably never read it (refused, or past the last stream a GOAWAY says it took), or when it went out on a kept connection that died without a word (a NAT that forgot it): that one most likely never got there, but may have. And Bun's node:http2 drops a request in flight when the server ends the connection with a GOAWAY that would have let it finish: APNs has it, its answer never comes, and the result is a retryable failure, which the outbox sends again.

On Cloudflare Workers

FCM and Web Push: a Worker can't reach APNs (above), so its iOS devices belong to a server that can.

npm install direct-push
npx wrangler d1 create push
// src/index.ts
import { pushWorker } from "direct-push/worker";
export default pushWorker((env) => ({ authorize: (req) => userIdFrom(req, env) }));
# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "push"
database_id = "…"          # from `wrangler d1 create`

[triggers]
crons = ["* * * * *"]      # only wakes it: what goes out, and when, is the outbox's
npx wrangler secret put FCM_SERVICE_ACCOUNT < service-account.json
npx wrangler secret put VAPID_PUBLIC_KEY          # and VAPID_PRIVATE_KEY, VAPID_SUBJECT, ADMIN_TOKEN
npx wrangler deploy

The services come from the Worker's secrets under the names pushFromEnv reads, and ADMIN_TOKEN and CRON_SECRET from them too. See examples/cloudflare.

Just sending

The library alone, with no server and nothing kept: createPush sends one message to any mix of devices, each to its own service, twenty at a time, and answers one result per device.

import { createPush, pushFromEnv } from "direct-push";   // direct-push/node on Node and Bun

const push = createPush(pushFromEnv(process.env));       // or { apns: {…}, fcm: {…}, web: {…} }
const results = await push.send(
  [
    { platform: "apns", token: "a1b2…" },                // env left out: learnt, and said in the result
    { platform: "fcm", token: "dGhp…" },
    { platform: "web", endpoint: "https://fcm.googleapis.com/fcm/send/…", p256dh: "BN…", auth: "k3…" },
  ],
  { title: "Your order is on its way", body: "It left at 10:42.", data: { orderId: "1234" } },
);
for (const r of results) {
  if (r.dead) await forget(r.device);                    // gone: delete it
  if (r.env) await keepEnvironment(r.device, r.env);     // APNs: the environment that took the token
}

pushFromEnv reads APNS_KEY_ID, APNS_TEAM_ID, APNS_PRIVATE_KEY, APNS_BUNDLE_ID (and APNS_ENV), FCM_SERVICE_ACCOUNT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY and VAPID_SUBJECT, an object or a function ((name) => Deno.env.get(name)). A platform whose variables are missing is left out, and its devices answer not-configured. One whose variables are there but malformed fails loudly: createPush throws for a service account or VAPID keys it can't read, and an APNs key that won't load answers config on every push. Each sender is also its own export, apns(), fcm() and webPush(), for one service or several apps in one process.

Anywhere else

createPushServer({ sql, push }) from direct-push/server gives fetch(request) and tick(now). Hand fetch to whatever serves requests, as it is or as (req) => server.fetch(req) (Deno's Deno.serve, Bun's Bun.serve, Hono, a Next.js route handler, a Vercel function; on Node and Bun with direct-push/node's createPush) and call tick from whatever keeps time: a timer, a cron, or a request to /push/tick with the cron secret. Vercel Cron calls with GET and Authorization: Bearer $CRON_SECRET, which is what cronSecret checks. A database is three functions (src/server/sql.ts), so another one is a few lines.

The message

One Message, written once, goes to every kind of device:

await push.send(devices, {
  title: "Ana commented", body: "Looks great!",
  data: { postId: "42" },                 // the app's own, to route a tap by
  collapseId: "post-42",                  // a newer push with this id replaces this one
  channelId: "comments",                  // Android
  url: "/posts/42",                       // the web: what a tap opens
});
Field APNs FCM Web Push
title, body aps.alert notification the payload's title, body
subtitle aps.alert.subtitle
data keys next to aps (one called aps is dropped) data, every value a string (others as JSON) the payload's data
sound aps.sound, "default" unless given; null is a quiet alert android.notification.sound, the same null makes the notification silent
badge aps.badge android.notification.notification_count the payload's appBadge (the app icon's count)
threadId aps.thread-id (how Notification Center groups)
collapseId apns-collapse-id (a hash past 64 bytes) android.collapse_key (one still waiting for an offline phone) and android.notification.tag (one already shown) Topic (a hash unless it fits), and the notification's tag
channelId android.notification.channel_id
category aps.category (actions)
image mutable-content and image next to aps, for a service extension to fetch android.notification.image the notification's image
url the payload's url and data.url, opened on a tap
priority apns-priority 10, or 5 for normal android.priority HIGH or NORMAL Urgency high or normal
expiresAt apns-expiration android.ttl (four weeks at most) TTL
silent content-available, push type background, priority 5 data only: the app's service gets it, nothing shows skipped (silent-not-supported): browsers take no push that shows nothing
apns, fcm, web pushType, topic, aps and headers, merged last; payload, the whole body as it is (a Wallet pass update is {} to the pass type id) android and data, merged last tag, icon, badge, ttl, requireInteraction, actions

A push lives a day unless expiresAt (a Date, or milliseconds) says otherwise; one already past is delivered now or never. On APNs, sound, badge, threadId, category and image go on an alert (the default push type) only, and a silent push carries none of them anywhere. Null values in data are left out everywhere.

A Live Activity is the same send with apns.pushType: the topic gets Apple's .push-type.liveactivity, and dates inside content-state go the way Swift decodes them, which appleReferenceDate writes.

import { appleReferenceDate } from "direct-push";

await push.send({ platform: "apns", token: activityPushToken }, {
  apns: {
    pushType: "liveactivity",
    aps: { event: "update", timestamp: Math.floor(Date.now() / 1000), "content-state": { endsAt: appleReferenceDate(end) } },
  },
});

voip, complication, fileprovider and location get their suffixes the same way; apns.topic and apns.headers override anything.

Results

One per device, in the order given. send never rejects: what went wrong on a device is in its result.

interface Result {
  device: Device;
  ok: boolean;
  status: number;           // HTTP; 0 when nothing came back (network, timeout) or a key wouldn't load; -1 skipped
  reason?: string;          // APNs' reason, FCM's error code and message, the push service's text
  dead: boolean;            // the device is gone: delete it (if it wasn't registered again after invalidSince)
  retryable: boolean;       // try again later, not before retryAfter
  config: boolean;          // our side is wrong: tell someone, and never delete devices for it
  skipped?: boolean;        // not sent: not-configured, unknown-platform, silent-not-supported, unknown-push-service
  env?: "production" | "sandbox";   // APNs: the environment that took the token, when it wasn't the device's: keep it
  invalidSince?: number;    // APNs 410: when the token stopped being valid (ms)
  retryAfter?: number;      // seconds, from Retry-After
  id?: string;              // apns-id, FCM's message name, the push service's Location
}
dead retryable config
APNs 410 Unregistered, ExpiredToken, BadDeviceToken from both environments, DeviceTokenNotForTopic, MissingDeviceToken 429, 5xx, IdleTimeout, the network, a timeout (15 s) the rest: InvalidProviderToken, BadTopic, TopicDisallowed…
FCM UNREGISTERED, a 400 about the registration token, SENDER_ID_MISMATCH 429, 5xx, the network, a timeout; Google's token exchange busy the rest: the token exchange refused, a 404 without UNREGISTERED (a wrong project id)…
Web Push 404, 410, a 403 that says the subscription is another VAPID key's (Apple's VapidPkHashMismatch, FCM's "does not correspond to the sender ID"), a subscription whose keys can't be used 429, 5xx, the network, a timeout the rest: 400, 401, any other 403 (Apple's BadJwtToken, BadVapidPublicKey…)…

Two answers are handled before they reach you: APNs' ExpiredProviderToken and FCM's 401 drop the token held and send once more with a new one.

DeviceTokenNotForTopic, SENDER_ID_MISMATCH and a push service's 403 for another key are what a wrong bundle id, a wrong Firebase project and a changed VAPID key look like from every device at once. So createPush counts them as config instead of dead until the same setting has had a push go through on that platform (on the web, through that push service: Chrome's answers vouch for nothing of Safari's); a server keeps that proof in its tables for the next process, under a hash of the setting, so a changed key or topic starts with none. And it keeps each platform's answers of the last ten minutes: when at least three are of that kind and they are at least half, they come back config even then.

A push service that answers with a redirect isn't followed: the result says Redirect, and none of the three is set.

A browser's endpoint is sent to only when it is on one of the browsers' push services, PUSH_SERVICES: fcm.googleapis.com, *.push.services.mozilla.com, *.push.apple.com and *.notify.windows.com (*. is any name under it). Any other host is skipped with unknown-push-service, whoever registered it; webPush({ vapid, pushServices: [...PUSH_SERVICES, "push.example.com"] }) adds one, and the server's pushServices does the same for what it registers and for the web sender it makes from push's options (a createPush() handed to it ready-made needs them in its own). Of what a push service answers, only the first 4 KB is read.

A message too large for the service (4 KB on APNs and FCM, 5 KB for VoIP, 3993 bytes of JSON for Web Push) is refused before it is sent, with status 413 and PayloadTooLarge and none of the three set: it is the message that has to change.

The server

What the apps each built for themselves, once: who has which devices, and an outbox of pushes a cron empties.

import { createPushServer, defaultRender } from "direct-push/server";

const server = createPushServer({ sql, push, authorize });

await server.enqueue({
  userId: "u_123",
  type: "comment",
  data: { title: "Ana commented", body: "Looks great!", postId: "42" },
  groupKey: "post-42",                  // rows of one user with the same key go out as one push
  dedupeKey: "comment-9001",            // queued once, however many times this runs
});
await server.tick();                    // sends what is due

Pushes are queued with enqueue (one item or a list; it answers how many were new), with POST /push/messages from another backend, or, on Postgres, with an insert from your own SQL (examples/supabase has a trigger). An item is userId, and any of type, data, message (a whole Message, sent as it is), groupKey, dedupeKey, sendAfter and expiresAt (a Date, milliseconds or an ISO string) and platforms (["web"]: only the user's browsers, for a reminder the phone raised by itself). send(userId, message, { platforms }) sends to a user's devices now instead, skipping the outbox, with one message or, like render, a function of a language (called once for each language among the devices); both keep what the services answered about the devices, and keep(userId, results) does the same for pushes an app sends through server.push itself.

The tick

Each tick, from whatever keeps time (every minute is right whatever the pushes are):

  1. Takes the due rows on a lease, once the rows past their expires_at are dropped (last_error expired): whole groups (one user and one groupKey; a row without one goes alone), oldest first, up to batch rows. One statement, so two ticks at once never take the same row, nor part of the same group (Postgres locks each group it takes first, never waiting for one another tick holds; SQLite and D1 run one writer at a time). A tick that dies leaves its rows leased, and another takes them again after ten minutes.
  2. Waits for a burst to end, with debounceMs: a group still getting rows waits until it has had none that long, but never more than maxDebounceMs after its first. A row without a groupKey is alone and never waits.
  3. Waits for the user, with quietUntil: their rows go back until then, and that isn't counted as a try.
  4. Writes one message per group with render, once for each language among the user's devices (group.locale), and sends it to the user's devices that are on, eight groups at a time. A group the tick hasn't started tickBudgetMs (a minute) after it began goes back to the queue instead, not counted as a try, and the next tick takes it first: a slow push service never keeps a tick running past what the platform allows.
  5. Keeps what the answers say: a device that is gone is removed (an APNs one only if it didn't register again after Apple says it went), and an APNs environment learnt is kept. Then the rows are sent when any device took the push, or there was nobody left to take it (last_error says no-devices, devices-gone or nothing-to-send); back in the queue when every failure that isn't our side can work later, after 2, 4, 8… minutes (an hour at most, and never before retryAfter) until maxAttempts or their expiry; failed when our side is wrong and no other device can take it later, or the tries or the time ran out, with the reasons in last_error and an observe event.
  6. Prunes the rows done more than 30 days ago.

It answers what it did, in rows: { claimed, sent, retried, failed, expired, deferred, devicesRemoved } (deferred: back in the queue for quiet hours, or for the next tick).

The default render sends the newest row's message, else its data's title and body with the rest of its data (and its type) as the data a tap is routed by. A burst asks for words of its own:

render: (group) =>
  group.rows.length === 1
    ? defaultRender(group)
    : { title: group.locale?.startsWith("es") ? `${group.rows.length} comentarios nuevos` : `${group.rows.length} new comments`,
        data: { postId: group.rows.at(-1)!.data?.postId } },

The tables

Three, prefixed (push_ by default), made and migrated by the server on its first request or tick:

Table What
devices One row per device: user_id, platform (apns, fcm or web), token (the APNs or FCM token, or a browser's endpoint; unique), p256dh and auth (a browser's keys), apns_env (learnt), locale, enabled, created_at, updated_at.
outbox One row per queued push: user_id, type, data and message (JSON as text), group_key, dedupe_key (unique), send_after, expires_at, claimed_at, attempts, sent_at, last_error, created_at, platforms (JSON, null for all).
meta How far the schema has migrated, and which settings have had a push go through (the breaker's proof, the hundred most recent).

Ids are text, times integer milliseconds and flags integers, so the same tables work on SQLite, D1 and Postgres. A token belongs to one user at a time: registering is one upsert on it, so a phone that signs into another account moves over at once. enabled is the device's own switch: the same user registering again (apps do it on every launch) never touches it, and a token that moves to another user starts on. APNs tokens are kept in lower case, and a browser's endpoint must be an https address on one of the push services (pushServices, the browsers' own unless given): no other host, no other port, no IP address. The sender also never follows a redirect, and a test push to a browser says only what kind of failure it met. A user keeps the 20 devices they registered most recently (maxDevices): registering one more forgets the one registered longest ago.

On Postgres all three have row level security on and no policies: on Supabase the Data API can't reach them, and only the server's own connection (the tables' owner, or service_role) reads and writes them.

The routes

Under basePath (/push), all JSON. A body must be sent as Content-Type: application/json (anything else is 415): a form is what another site can make a browser send without asking first. Errors are { "error": "…" }.

Route Who What
POST /devices the user (authorize) Registers the caller's device: a Device (or a browser's subscription.toJSON()), with locale and enabled if wanted. Answers { ok, device }.
GET /devices the user The caller's devices, switched off ones too, without a browser's keys.
DELETE /devices the user { "token": … } (or endpoint): forgets that device, if it is the caller's. With "onlyEnabled": true (notifications turned off on the phone, not a sign-out), only while it is switched on. Answers { ok, removed }.
POST /devices/test the user { "token": …, "title"?, "body"? }: one push to that device of the caller's, now. Answers { ok, result } (a browser's failure as its kind only: HTTP 500, network, timeout); 404 when it isn't theirs, 409 when it is switched off. What it says is the caller's alone: it raises no observe event.
POST or GET /tick Authorization: Bearer the cron secret or the admin token One tick. Answers { ok, claimed, sent, … }.
POST /messages Authorization: Bearer the admin token Queues an item, a list of them, or { "messages": [...] }. Answers { ok, queued }.

Without authorize the device routes are off, and without adminToken, /messages. The secrets are compared in constant time.

Options

createPushServer({                        // pushWorker({…}) takes the same but sql (env.DB); push is the secrets unless given
  sql,                                    // the database: direct-push/sqlite, /postgres or /d1
  push: pushFromEnv(env),                 // the services' options, or a createPush() (direct-push/node's on Node and Bun)
  tablePrefix: "push_",                   // the tables' prefix
  basePath: "/push",                      // where the routes answer
  authorize: (req) => userId,             // whose request it is, or null; the device routes are off without it
  cronSecret: "…",                        // the bearer a scheduler sends to /tick (Vercel Cron's CRON_SECRET)
  adminToken: "…",                        // the bearer for /messages, and /tick (the Worker reads env.ADMIN_TOKEN)
  render: (group) => message,             // one message from a group's rows, in group.locale; null sends nothing
  quietUntil: (userId, now) => date,      // until when a user isn't to be woken; null for now
  debounceMs: 0,                          // a group still getting rows waits until it has had none this long…
  maxDebounceMs: 600_000,                 // …but no longer than this after its first row
  lifetimeMs: 86_400_000,                 // how long a queued push is worth sending after it is due
  maxAttempts: 5,                         // tries before it is given up on
  batch: 500,                             // rows a tick takes at most (a group is never split)
  tickBudgetMs: 60_000,                   // how long a tick starts groups for; the rest go back, untried, for the next
  pushServices: PUSH_SERVICES,            // the hosts a browser's endpoint may be on (the server's web sender takes them too)
  maxDevices: 20,                         // devices a user keeps; one more forgets the one registered longest ago
  observe: (event) => …,                  // what needs knowing; a send never waits for it
});

observe is told of config (our side is wrong, with the results that say so), failed and retry (rows given up on or back in the queue, and why), removed (a device gone) and tick (its summary and how long it took). Alert on the first: it is a key, the topic or the project, and nothing will reach that platform until someone fixes it. On the web only a push service's own answer can raise it (no other host is sent to), and a test push never does: any signed-in user can ask for one as often as they like. On a Worker it runs after the answer through ctx.waitUntil; elsewhere the call waits for it, so a platform that freezes a function once it has answered doesn't cut an alert off.

The server is also register(userId, device, meta?), unregister(token, userId?, { onlyEnabled }?), devices(userId), enqueue(items), send(userId, message, { platforms }?), keep(userId, results) and push, for an app that registers devices through its own API.

Connect an app

One package, three clients, all in this repository. Each gives this device as the server takes it, POSTs it to {basePath}/devices with whatever headers your authorize reads, and DELETEs it there at sign-out.

npx direct-push app, run in an app's folder (it needs no keys), finds the projects under it (three folders down) and, for each one checked, does what can be done safely and only once, so running it again changes nothing: the web gets a sw.js in its public/ (or static/) folder, direct-push/sw's built code with the listeners, served as it is, unless the site already has a worker of its own there; Android gets JitPack in settings.gradle(.kts) and the dependency in the app module (through gradle/libs.versions.toml when there is one); a Package.swift gets the package. An Xcode project's .pbxproj is left to Xcode. What is left, the code below with your server's URL and VAPID public key in it, is printed. --url and --vapid-public-key answer its questions ahead (the key is also read from .env when it is there).

Platform Install from this repository
The web (a page and its service worker) npm: direct-push/web, direct-push/sw
iOS, macOS (Swift 6, iOS 15, macOS 12) Swift Package Manager: https://github.com/guillecura/direct-push
Android (Kotlin 2.1 or later, Android 7.0, API 24) JitPack: com.github.guillecura:direct-push:<tag>

The web

import { current, register, stale, subscribe, unregister } from "direct-push/web";

const vapidPublicKey = "BN…";                            // VAPID_PUBLIC_KEY
const url = "https://api.example.com/push/devices";
const headers = { Authorization: `Bearer ${session.token}` };

// Every load: the browser may have replaced the subscription, or dropped it.
const gone = await stale();
if (gone) await unregister(url, gone, { headers });
const device = await current({ vapidPublicKey });
if (device) await register(url, device, { headers, locale: navigator.language });

// The switch: subscribe straight from the tap, before anything else is awaited.
button.onclick = async () => {
  const device = await subscribe({ vapidPublicKey, serviceWorker: "/sw.js" });
  await register(url, device, { headers, locale: navigator.language });
};

register(url, device, { enabled }) and setEnabled(url, device, enabled) set the device's switch in the app (off: still registered, sent nothing), devices(url) lists the account's devices (this browser's token is its endpoint), and unregister(url, device, { onlyEnabled: true }) is for notifications turned off in the browser rather than a sign-out.

// sw.js, bundled with the rest of the app
import { onNotificationClick, onPush, onSubscriptionChange } from "direct-push/sw";
import { register } from "direct-push/web";

self.addEventListener("push", (event) => onPush(event, { defaultTitle: "Acme", icon: "/icon-192.png" }));
self.addEventListener("notificationclick", (event) => onNotificationClick(event));   // focuses or opens data.url

// The browser replaced the subscription: the new one goes to the server. A worker has no session of its own, so
// this suits a server on the site's own origin whose authorize reads the site's cookie.
self.addEventListener("pushsubscriptionchange", (event) =>
  onSubscriptionChange(event, { vapidPublicKey: "BN…", save: (device) => register("/push/devices", device) }));

What browsers differ on, and the client handles or says:

  • Safari shows the prompt only for a tap, and a tap stops counting at the first await. subscribe asks before it awaits anything, so call it from the tap itself, first.
  • On an iPhone or iPad, Web Push needs the site added to the Home Screen and opened from there (iOS 16.4 and later). In a Safari tab there is no push at all: permission() answers "home-screen", so the page can say so instead of offering a switch that can't work.
  • Register on every load. A browser replaces a subscription on its own now and then, and drops it when notifications are blocked or reset; current() gives what it has now and stale() the endpoint to drop.
  • Keep the VAPID key. A subscription belongs to the key it was made with: a new one makes the push services refuse every subscription made with the old, and a browser is reachable again only once its page calls subscribe with the new one (no prompt then, if it was allowed).
  • subscribe throws a SubscribeError whose reason is unsupported, home-screen, denied (only the browser's settings undo it), dismissed or no-service-worker; register a RegisterError with the server's status and words.

direct-push/sw imports nothing at runtime, so it bundles into the worker with the rest of the app's code. Its own types are written out, so it compiles both in a project with the WebWorker library and in one with only the DOM's.

Swift (iOS 15, macOS 12; in Xcode, File › Add Package Dependencies… with this repository's URL; the app needs the Push Notifications capability)

import DirectPush

// The app delegate: three calls forwarded.
func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    DirectPush.shared.start()                  // here, or the tap that launched the app is lost
    return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) {
    DirectPush.shared.didRegister(deviceToken: token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    DirectPush.shared.didFailToRegister(error: error)
}

// Signed in.
let push = DirectPush.shared
let devices = URL(string: "https://api.example.com/push/devices")!
push.register(to: devices) { ["Authorization": "Bearer \(try await session.accessToken())"] }
push.onOpen = { opened in if opened.isTap { router.open(opened.data) } }   // the payload's data, as strings
await push.requestAuthorization()              // the prompt the first time; the token goes up while allowed

// Back in the foreground (scenePhase .active): notifications turned off in Settings withdraw it, back on send it.
await push.recheck()

// Signing out, while the session still works.
try await push.unregister(from: devices) { ["Authorization": "Bearer \(try await session.accessToken())"] }

onOpen and Received hand every data value over as a String, as FCM does on Android: a number or a bool in the payload comes as "3" or "true", a nested object or array as its JSON text, so the app parses what it needs.

The device goes up with env left out, so the server learns it from APNs instead of a guess from the build (DirectPush.apnsEnvironment() reads it from the embedded provisioning profile, for an app that wants to say). The token follows the permission: refused at a launch or a sign-in, or turned off by the time recheck() looks, it is withdrawn (DELETE with onlyEnabled, so a device switched off in the app stays off); an app that relies on silent pushes, which need no permission, sets followsPermission = false. A sign-out waits for a registration still on its way, so it can't land after the DELETE and give the device back to the account that left. The delegate methods are the completion-handler ones, finished on the main thread: the async ones crashed apps on taps from the Lock Screen. A tap or a token that comes before its callback is set waits for it. onForeground, onSilent (a content-available push: the remote-notification background mode, and the app delegate forwarding didReceiveRemoteNotification), onWithdraw (with onToken, for a backend of your own), onError, presentInForeground and setBadge are there too, and, with register(to:), devices(), isThisDevice(_:) and setEnabled(_:) for the switch in the app.

Kotlin (the app needs Firebase set up: its google-services.json and plugin, or DirectPush.initialize(…) with the same values)

// settings.gradle.kts: dependencyResolutionManagement { repositories { maven("https://jitpack.io") } }
// build.gradle.kts:    implementation("com.github.guillecura:direct-push:v1.0.3")
import io.directpush.DirectPush
import io.directpush.PermissionRequester

// Application.onCreate, and again at sign-in: the token now, and each renewal after, while notifications are allowed.
DirectPush.ensureChannel(this, "comments", getString(R.string.comments))
DirectPush.register(this, "https://api.example.com/push/devices") { mapOf("Authorization" to "Bearer ${session.token()}") }

// An activity.
private val notifications = PermissionRequester(this)         // a property: Android registers it before onStart
override fun onStart() { super.onStart(); DirectPush.recheck(this) }   // a switch flipped in the settings
notifications.request { allowed -> … }                         // Android 13's prompt, when something asks for it
DirectPush.opened(intent)?.let(router::open)                   // in onCreate and onNewIntent: a tapped push's data

// Signing out (it suspends), while the session still works.
DirectPush.unregister(context)

DirectPush.unregister(context, url, headers) signs out in a process that never registered. With register(context, url, …), DirectPush.devices(context) lists the account's devices (isThisPhone marks this one) and DirectPush.setEnabled(context, enabled) is the switch in the app.

The library's manifest asks for POST_NOTIFICATIONS and declares DirectPushService, which shows the pushes that arrive while the app is open the way the system shows the others (the payload's channel, the manifest's default icon and colour, the data on the tap, which starts the activity as FCM's own taps do, whatever its launch mode); extend it for onSilent and the rest, and declare the subclass. FCM gives a token without the permission, so the client sends it only while notifications are allowed and withdraws it when they stop being (sparing a device switched off in the app). PermissionRequester.status tells a prompt that still shows (never asked, refused once, dismissed) from one refused for good. Without Firebase set up nothing crashes: DirectPush.token() throws a DirectPushException that says what is missing.

Each client sends its device ({"platform":"apns","token":…}, {"platform":"fcm","token":…}, or a browser's endpoint and keys) with a locale: the app's language on iOS (es), the phone's on Android (es-UY), the one given on the web. render gets it as group.locale.

Keys

npx direct-push init goes through all of this step by step and writes the env file; what follows is what it asks for. They belong on the server, never in an app or a repository (the .gitignore here leaves out *.p8 and service accounts). Each variable takes the file's contents, or base64 of them for a secret store that dislikes newlines; the .p8 also with its line breaks written as \n.

  • APNs: in Apple's developer site, Certificates, Identifiers & Profiles › Keys, a new key with Apple Push Notifications service (APNs) on; if asked, for both environments, since a token is tried in either. The .p8 downloads once. APNS_KEY_ID is the key's id, APNS_TEAM_ID the team's (Membership details), APNS_BUNDLE_ID the app's bundle id and APNS_PRIVATE_KEY the file. A key for the whole team serves every one of its apps. APNS_ENV=sandbox only makes a device of unknown environment try the sandbox first.
  • FCM: in the Firebase console, Project settings › Service accounts › Generate new private key: a JSON file, which is FCM_SERVICE_ACCOUNT, whole. It must be the project the Android app's google-services.json is from; a token of another project answers SENDER_ID_MISMATCH.
  • Web Push: npx direct-push vapid-keys prints VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY (>> .env appends just them; a pair in standard base64, padded, is taken too). VAPID_SUBJECT is a mailto: or https: address the push services can reach you at; Apple's refuses any other kind. The public key also goes to the page, as subscribe's vapidPublicKey.

npx direct-push send tries them: one push to one device, with what the service answered (--env .env reads them from a file; --help lists the rest). Do it before pointing the server at real devices: a wrong bundle id, Firebase project or VAPID key answers config there, and nothing will reach that platform until it is fixed.

With an AI agent

The package ships a Claude Code skill: when to use which import, the wizards, and the rules that keep keys out of code. Copy it into the project and Claude reads it when the task calls for it:

mkdir -p .claude/skills && cp -r node_modules/direct-push/skills/direct-push .claude/skills/

Other agents can read the same file, or this README at node_modules/direct-push/README.md.

Develop

npm install
npm test                                # the senders, the server on SQLite, Postgres (PGlite) and a D1 stand-in, HTTP/2, the CLI, web, sw
npm run typecheck
npm run build
npm run test:deno                       # the senders on Deno, and the built package as npm:direct-push serves it
DIRECT_PUSH_NET=1 npm test              # also asks the real APNs sandbox, no keys needed: what each fetch gets back
swift test                              # the Swift client
cd clients/android && ./gradlew testDebugUnitTest   # the Android client (JDK 17 and the Android SDK)

A release is a version in package.json (and in Package.swift's comment and the Kotlin line above) and a vX.Y.Z tag pushed: the release workflow publishes to npm with provenance, and Swift Package Manager and JitPack read the tag. The very first time, npm needs the package to exist before it trusts the workflow, and provenance needs the repository to be public: so the repository goes public, a placeholder version (0.0.0-stage, not the first real one, which the tag would then fail to publish again) goes up by hand, the trusted publisher is set on npmjs.com for release.yml, and only then the tag.

Credits

Made by Guille Cura at Whitebear.

License

MIT

whitebear