Send a Web Push notification from Node
Generate a VAPID identity, save a browser subscription, and build an encrypted push request with Node crypto before sending it to the subscription endpoint.
A Web Push send needs two separate keys: your persistent VAPID signing key and a fresh encryption key for each message. The browser subscription supplies the receiver’s public key and authentication secret. The Node 26 example below builds the request without sending it, so you can test encryption before involving a push service.
Create and save a subscription
Serve the page and /sw.js over HTTPS, or localhost for development. Prepare the worker before enabling the button. Insert your VAPID public key, generated by the server code below.
const key = 'YOUR_VAPID_PUBLIC_KEY';
const raw = atob(key.replace(/-/g, '+').replace(/_/g, '/'));
await navigator.serviceWorker.register('/sw.js');
const registration = await navigator.serviceWorker.ready;
const button = document.querySelector('#enable-push');
button.disabled = false;
button.onclick = async () => {
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: Uint8Array.from(raw, c => c.charCodeAt(0)),
});
console.log(JSON.stringify(subscription));
};
Use a button initially marked disabled. Subscribe from that user gesture; handle permission rejection in your UI. Send the subscription JSON to an authenticated, CSRF-protected application endpoint and bind it to the account and device. Treat its endpoint as a capability. The Push API defines this browser contract.
Save this minimal worker as /sw.js; the example sender always uses a JSON object with a title and body:
self.addEventListener('push', event => {
const message = event.data.json();
event.waitUntil(self.registration.showNotification(message.title, {
body: message.body,
}));
});
Build the encrypted request
Save as push.mjs. These built-in Node crypto APIs need no package installation.
import { createECDH, createHmac, createCipheriv, randomBytes,
generateKeyPairSync, sign } from 'node:crypto';
const decode = s => Buffer.from(s, 'base64url');
const cat = (...parts) => Buffer.concat(parts);
const hmac = (key, data) => createHmac('sha256', key).update(data).digest();
const expand = (key, info, n) => hmac(key, cat(info, Buffer.from([1]))).subarray(0, n);
export function generateVapid() {
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const jwk = publicKey.export({ format: 'jwk' });
return { privateKey, publicKey: cat(Buffer.from([4]), decode(jwk.x), decode(jwk.y)).toString('base64url') };
}
export function encrypt(subscription, text, senderPrivate, salt = randomBytes(16)) {
const payload = Buffer.from(text);
if (payload.length > 3993) throw new Error('Payload exceeds 3993 bytes');
const ua = decode(subscription.keys.p256dh);
const sender = createECDH('prime256v1');
if (senderPrivate) sender.setPrivateKey(decode(senderPrivate));
else sender.generateKeys();
const pub = sender.getPublicKey();
const shared = sender.computeSecret(ua);
const prkKey = hmac(decode(subscription.keys.auth), shared);
const ikm = expand(prkKey, cat(Buffer.from('WebPush: info\0'), ua, pub), 32);
const prk = hmac(salt, ikm);
const cek = expand(prk, Buffer.from('Content-Encoding: aes128gcm\0'), 16);
const nonce = expand(prk, Buffer.from('Content-Encoding: nonce\0'), 12);
const cipher = createCipheriv('aes-128-gcm', cek, nonce);
const ciphertext = cat(cipher.update(cat(payload, Buffer.from([2]))),
cipher.final(), cipher.getAuthTag());
const header = Buffer.alloc(21);
salt.copy(header);
header.writeUInt32BE(4096, 16);
header[20] = pub.length;
return cat(header, pub, ciphertext);
}
export function makeRequest(subscription, text, vapid, subject) {
const endpoint = new URL(subscription.endpoint);
if (endpoint.protocol !== 'https:') throw new Error('HTTPS endpoint required');
const b64json = value => Buffer.from(JSON.stringify(value)).toString('base64url');
const input = b64json({ typ: 'JWT', alg: 'ES256' }) + '.' + b64json({
aud: endpoint.origin, exp: Math.floor(Date.now() / 1000) + 3600, sub: subject,
});
const signature = sign('sha256', Buffer.from(input), {
key: vapid.privateKey, dsaEncoding: 'ieee-p1363',
}).toString('base64url');
return { method: 'POST', redirect: 'error', headers: {
Authorization: `vapid t=${input}.${signature}, k=${vapid.publicKey}`,
'Content-Encoding': 'aes128gcm', 'Content-Type': 'application/octet-stream',
TTL: '60', Urgency: 'normal', Topic: 'inbox',
}, body: encrypt(subscription, text) };
}
Generate the VAPID pair once with generateVapid(), publish its publicKey to the page, and securely persist the private key, for example as PKCS#8 PEM. Recreating it on each restart breaks the identity associated with existing subscriptions. Load that same key when sending. The ephemeral ECDH key inside encrypt is deliberately different and changes per message.
After loading your saved subscription and VAPID identity, the actual send is:
const options = makeRequest(subscription,
JSON.stringify({ title: 'Inbox', body: 'You have a new message' }),
vapid, 'mailto:push-admin@example.com');
const response = await fetch(subscription.endpoint, options);
if (response.status === 404 || response.status === 410) {
// Remove this subscription from your database.
} else if (!response.ok) {
throw new Error(`Push service returned ${response.status}`);
}
Validate subscription endpoints against your supported push-service policy before fetching them, including protection against access to internal network destinations. Do not let arbitrary posted URLs turn your server into a request proxy.
Check the bytes and delivery policy
The implementation uses the single-record aes128gcm encoding from RFC 8291. The 4096-byte portable body budget leaves 3993 bytes for UTF-8 payload: subtract an 86-byte header, one delimiter and a 16-byte tag. Count bytes, not JavaScript characters.
VAPID, RFC 8292 signs the push-service origin as audience, with an expiry no more than 24 hours ahead. The example uses one hour. It uses raw 64-byte ES256 signatures, not DER encoding. VAPID identifies the sender; it does not encrypt the message.
TTL: 60 permits storage for 60 seconds, Urgency affects delivery priority, and Topic: inbox can replace a pending message with the same topic for that subscription. Topics are at most 32 URL-safe base64 characters. Acceptance is not proof of display. Delete expired subscriptions on 404/410; treat 429 and transient server failures with bounded retry and Retry-After. See RFC 8030.
For production, the maintained web-push library (registry version 4.0.0 when checked in November 2026) packages this protocol work. The direct implementation makes the boundaries visible; the Web Push encryption dive explains the derivation and its test vector.