web-push-neo
v0.1.2
Published
Runtime-agnostic Web Push library using Web Crypto API
Downloads
353
Readme
A modern, runtime-agnostic fork of web-push, rewritten in TypeScript.
Why fork?
- Runtime-agnostic — uses Web Crypto API +
fetchinstead of Node.jscrypto/https. Works in Node.js, Deno, Bun, Cloudflare Workers, and any environment with Web Crypto support. - TypeScript / ESM-only — fully typed, tree-shakeable, no CJS.
- Stateless API — no global
setVapidDetails()/setGCMAPIKey(). VAPID details are passed per-call. - aes128gcm only — dropped the legacy
aesgcmencoding. All modern browsers (including Safari 16+) supportaes128gcm. - No GCM — Google Cloud Messaging was deprecated in 2019. FCM works via VAPID.
- 1 dependency — only jose for JWT signing (also runtime-agnostic).
Why
Web push requires that push messages triggered from a backend be done via the Web Push Protocol and if you want to send data with your push message, you must also encrypt that data according to the Message Encryption for Web Push spec.
This module makes it easy to send messages using the Web Crypto API and fetch, so it works in Node.js, Deno, Bun, Cloudflare Workers, and any runtime with Web Crypto support.
Install
pnpm add web-push-neoUsage
import {
generateVAPIDKeys,
sendNotification,
type PushSubscription,
type VapidDetails,
} from 'web-push-neo';
// VAPID keys should be generated only once.
const vapidKeys = await generateVAPIDKeys();
const vapidDetails = {
subject: 'mailto:[email protected]',
publicKey: vapidKeys.publicKey,
privateKey: vapidKeys.privateKey,
} satisfies VapidDetails;
// This is the same output of calling JSON.stringify on a PushSubscription
const pushSubscription = {
endpoint: '.....',
keys: {
auth: '.....',
p256dh: '.....',
},
} satisfies PushSubscription;
await sendNotification(pushSubscription, 'Your Push Payload Text', {
vapidDetails,
});Using VAPID Key for applicationServerKey
When subscribing to push messages, you'll need to pass your VAPID key, which you can do like so:
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: '<Your Public Key from generateVAPIDKeys()>',
});API Reference
sendNotification(pushSubscription, payload, options)
import {
sendNotification,
type PushSubscription,
type SendNotificationOptions,
type SendResult,
} from 'web-push-neo';
const pushSubscription = {
endpoint: '< Push Subscription URL >',
keys: {
p256dh: '< User Public Encryption Key >',
auth: '< User Auth Secret >',
},
} satisfies PushSubscription;
const payload = '< Push Payload String >';
const options = {
vapidDetails: {
subject: "< 'mailto' Address or URL >",
publicKey: '< URL Safe Base64 Encoded Public Key >',
privateKey: '< URL Safe Base64 Encoded Private Key >',
},
TTL: 60,
headers: {
'< header name >': '< header value >',
},
urgency: 'normal',
topic: '< Use a maximum of 32 characters from the URL or filename-safe Base64 characters sets. >',
signal: AbortSignal.timeout(5000),
} satisfies SendNotificationOptions;
const result: SendResult = await sendNotification(pushSubscription, payload, options);Note:
sendNotification()does not require a payload. You can also omitvapidDetailsif the push service supports unauthenticated requests.
Input
Push Subscription
The first argument must be an object containing the details for a push subscription.
The expected format is the same output as JSON.stringify'ing a PushSubscription in the browser.
Payload
The payload is optional, but if set, will be the data sent with a push message.
This must be either a string or a Uint8Array.
Note: In order to encrypt the payload, the pushSubscription must have a keys object with p256dh and auth values.
Options
Options is an optional argument that if defined should be an object containing any of the following values defined, although none of them are required.
- vapidDetails should be an object with subject, publicKey and privateKey values defined. These values should follow the VAPID Spec. Both PKCS8 and raw 32-byte private keys are supported.
- TTL is a value in seconds that describes how long a push message is retained by the push service (by default, four weeks).
- headers is an object with all the extra headers you want to add to the request.
- urgency is to indicate to the push service whether to send the notification immediately or prioritise the recipient's device power considerations for delivery. Provide one of the following values: very-low, low, normal, or high. To attempt to deliver the notification immediately, specify high.
- topic optionally provide an identifier that the push service uses to coalesce notifications. Use a maximum of 32 characters from the URL or filename-safe Base64 characters sets.
- signal an optional
AbortSignalto cancel the request.
Returns
A promise that resolves if the notification was sent successfully with details of the request, otherwise it rejects.
In both cases, resolving or rejecting, you'll be able to access the following values on the returned object or error.
- statusCode, the status code of the response from the push service;
- headers, the headers of the response from the push service;
- body, the body of the response from the push service.
generateVAPIDKeys()
import { generateVAPIDKeys } from 'web-push-neo';
const vapidKeys = await generateVAPIDKeys();
// Prints 2 URL Safe Base64 Encoded Strings
console.log(vapidKeys.publicKey, vapidKeys.privateKey);Input
None.
Returns
Returns a promise that resolves to an object with publicKey and privateKey values which are URL Safe Base64 encoded strings. The private key is in PKCS8 format.
Note: You should create these keys once, store them and use them for all future messages you send.
generateRequestDetails(pushSubscription, payload, options)
import { generateRequestDetails, type RequestDetails } from 'web-push-neo';
const details: RequestDetails = await generateRequestDetails(pushSubscription, payload, options);
// details contains: endpoint, method, headers, bodyNote: When calling
generateRequestDetails()the payload argument does not need to be defined, passing in null will return no body and exclude any unnecessary headers.
Input
Same as sendNotification().
Returns
A promise that resolves to an object containing all the details needed to make a network request:
- endpoint, the URL to send the request to;
- method, this will be 'POST';
- headers, the headers to add to the request;
- body, the body of the request (as a Uint8Array, or null).
Differences from web-push
| Feature | web-push | web-push-neo |
| --------------- | ------------------------- | ------------------------- |
| Runtime | Node.js only | Any (Web Crypto + fetch) |
| Language | JavaScript | TypeScript |
| Module | CJS | ESM-only |
| API style | Global mutable state | Stateless async functions |
| Encryption | Node.js crypto + http_ece | Web Crypto API |
| HTTP | Node.js https | fetch |
| GCM support | Yes | No (deprecated 2019) |
| aesgcm encoding | Yes | No (aes128gcm only) |
| Proxy support | Yes (https-proxy-agent) | No (use custom fetch) |
| Dependencies | 5 | 1 (jose) |
Browser Support
All modern browsers that support the Push API work with this library. The library itself runs on any server-side JavaScript runtime with Web Crypto API and fetch support.
Running tests
pnpm test