web-push

Web Push library for Node.js

README

web-push

Build Status

Why


Web push requires that push messages triggered from a backend be done via the
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 and will also handle legacy support
for browsers relying on GCM for message sending / delivery.

Install


Installation is simple, just install via npm.

    npm install web-push --save

Usage


The common use case for this library is an application server using
a GCM API key and VAPID keys.

  1. ``` js
  2. const webpush = require('web-push');

  3. // VAPID keys should be generated only once.
  4. const vapidKeys = webpush.generateVAPIDKeys();

  5. webpush.setGCMAPIKey('<Your GCM API Key Here>');
  6. webpush.setVapidDetails(
  7.   'mailto:example@yourdomain.org',
  8.   vapidKeys.publicKey,
  9.   vapidKeys.privateKey
  10. );

  11. // This is the same output of calling JSON.stringify on a PushSubscription
  12. const pushSubscription = {
  13.   endpoint: '.....',
  14.   keys: {
  15.     auth: '.....',
  16.     p256dh: '.....'
  17.   }
  18. };

  19. webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
  20. ```

Using VAPID Key for applicationServerKey


When subscribing to push messages, you'll need to pass your VAPID key,
which you can do like so:

  1. ``` js
  2. registration.pushManager.subscribe({
  3.   userVisibleOnly: true,
  4.   applicationServerKey: '<Your Public Key from generateVAPIDKeys()>'
  5. });
  6. ```

Command Line


You can install web-push globally and use it for sending notifications
and / or generating VAPID keys.

Install like so:

    npm install web-push -g

Then you can run the following commands:

    Usage:

web-push send-notification --endpoint= [--key=] [--auth=] [--payload=] [--encoding=] [--ttl=] [--vapid-subject=] [--vapid-pubkey=] [--vapid-pvtkey=] [--proxy=] [--gcm-api-key=]

      web-push generate-vapid-keys [--json]

  Example of send notification:
  1. ``` sh
  2.     > web-push generate-vapid-keys --json
  3.     > {"publicKey":"BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE","privateKey":"I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0"}
  4. ```
   The subscription value:
  1. ``` js
  2.     {
  3.       "endpoint": "https://fcm.googleapis.com/fcm/send/d61c5u920dw:APA91bEmnw8utjDYCqSRplFMVCzQMg9e5XxpYajvh37mv2QIlISdasBFLbFca9ZZ4Uqcya0ck-SP84YJUEnWsVr3mwYfaDB7vGtsDQuEpfDdcIqOX_wrCRkBW2NDWRZ9qUz9hSgtI3sY",
  4.       "expirationTime": null,
  5.       "keys": {
  6.         "p256dh": "BL7ELU24fJTAlH5Kyl8N6BDCac8u8li_U5PIwG963MOvdYs9s7LSzj8x_7v7RFdLZ9Eap50PiiyF5K0TDAis7t0",
  7.         "auth": "juarI8x__VnHvsOgfeAPHg"
  8.       }
  9.     }
  10. ```
  The command example:
  1. ``` sh
  2.     web-push send-notification  \
  3.     --endpoint=https://fcm.googleapis.com/fcm/send/d61c5u920dw:APA91bEmnw8utjDYCqSRplFMVCzQMg9e5XxpYajvh37mv2QIlISdasBFLbFca9ZZ4Uqcya0ck-SP84YJUEnWsVr3mwYfaDB7vGtsDQuEpfDdcIqOX_wrCRkBW2NDWRZ9qUz9hSgtI3sY \
  4.     --key=BL7ELU24fJTAlH5Kyl8N6BDCac8u8li_U5PIwG963MOvdYs9s7LSzj8x_7v7RFdLZ9Eap50PiiyF5K0TDAis7t0 \
  5.     --auth=juarI8x__VnHvsOgfeAPHg \
  6.     --vapid-subject=mailto:example@qq.com \
  7.     --vapid-pubkey=BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE \
  8.     --vapid-pvtkey=I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0 \
  9.     --payload=Hello
  10. ```  

API Reference


sendNotification(pushSubscription, payload, options)


  1. ``` js
  2. const pushSubscription = {
  3.   endpoint: '< Push Subscription URL >',
  4.   keys: {
  5.     p256dh: '< User Public Encryption Key >',
  6.     auth: '< User Auth Secret >'
  7.   }
  8. };

  9. const payload = '< Push Payload String >';

  10. const options = {
  11.   gcmAPIKey: '< GCM API Key >',
  12.   vapidDetails: {
  13.     subject: '< \'mailto\' Address or URL >',
  14.     publicKey: '< URL Safe Base64 Encoded Public Key >',
  15.     privateKey: '< URL Safe Base64 Encoded Private Key >'
  16.   },
  17.   timeout: <Number>
  18.   TTL: <Number>,
  19.   headers: {
  20.     '< header name >': '< header value >'
  21.   },
  22.   contentEncoding: '< Encoding type, e.g.: aesgcm or aes128gcm >',
  23.   proxy: '< proxy server options >',
  24.   agent: '< https.Agent instance >'
  25. }

  26. webpush.sendNotification(
  27.   pushSubscription,
  28.   payload,
  29.   options
  30. );
  31. ```

Note: sendNotification() you don't need to define a payload, and this

method will work without a GCM API Key and / or VAPID keys if the push service
supports it.

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 node
[Buffer](https://nodejs.org/api/buffer.html).

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.

- gcmAPIKey can be a GCM API key to be used for this request and this
request only. This overrides any API key set via setGCMAPIKey().
- vapidDetails should be an object with subject, publicKey and
privateKey values defined. These values should follow the VAPID Spec.
- timeout is a value in milliseconds that specifies the request's socket timeout. On timeout, the request will be destroyed and the promise will be rejected with a meaningful error. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 TCP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout. Once a socket 'timeout' triggers the request will be aborted by the library (by default undefined).
- 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.
- contentEncoding is the type of push encoding to use (e.g. 'aes128gcm', by default, or 'aesgcm').
that may either be a string URI of the proxy server (eg. http://< hostname >:< port >)
or an "options" object with more specific properties.
- agent is the HTTPS Agent instance which will be used in thehttps.request method. If the proxy options defined, agent will be ignored!

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()


  1. ``` js
  2. const vapidKeys = webpush.generateVAPIDKeys();

  3. // Prints 2 URL Safe Base64 Encoded Strings
  4. console.log(vapidKeys.publicKey, vapidKeys.privateKey);
  5. ```

Input


None.

Returns


Returns an object with publicKey and privateKey values which are
URL Safe Base64 encoded strings.

Note: You should create these keys once, store them and use them for all

future messages you send.




setGCMAPIKey(apiKey)


  1. ``` js
  2. webpush.setGCMAPIKey('Your GCM API Key');
  3. ```

Input


This method expects the GCM API key that is linked to the gcm_sender_id in
your web app manifest.

You can use a GCM API Key from the Google Developer Console or the
Cloud Messaging tab under a Firebase Project.

Returns


None.



encrypt(userPublicKey, userAuth, payload, contentEncoding)


  1. ``` js
  2. const pushSubscription = {
  3.   endpoint: 'https://....',
  4.   keys: {
  5.     p256dh: '.....',
  6.     auth: '.....'
  7.   }
  8. };
  9. webPush.encrypt(
  10.   pushSubscription.keys.p256dh,
  11.   pushSubscription.keys.auth,
  12.   'My Payload',
  13.   'aes128gcm'
  14. )
  15. .then(encryptionDetails => {

  16. });
  17. ```

Encrypts the payload according to the [Message Encryption for Web
Push](https://webpush-wg.github.io/webpush-encryption/) standard.

(sendNotification will automatically encrypt the payload for you, so if

you use sendNotification you don't need to worry about it).


Input


The encrypt() method expects the following input:

- userPublicKey: the public key of the receiver (from the browser).
- userAuth: the auth secret of the receiver (from the browser).
- payload: the message to attach to the notification.
- contentEncoding: the type of content encoding to use (e.g. aesgcm or aes128gcm).

Returns


This method returns an object with the following fields:

- localPublicKey: The public key matched the private key used during
encryption.
- salt: A string representing the salt used to encrypt the payload.
- cipherText: The encrypted payload as a Buffer.



getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration)


  1. ``` js
  2. const parsedUrl = url.parse(subscription.endpoint);
  3. const audience = parsedUrl.protocol + '//' +
  4.   parsedUrl.hostname;

  5. const vapidHeaders = vapidHelper.getVapidHeaders(
  6.   audience,
  7.   'mailto: example@web-push-node.org',
  8.   vapidDetails.publicKey,
  9.   vapidDetails.privateKey,
  10.   'aes128gcm'
  11. );
  12. ```

The getVapidHeaders() method will take in the values needed to create
an Authorization and Crypto-Key header.

Input


The getVapidHeaders() method expects the following input:

- audience: the origin of the push service.
- subject: the mailto or URL for your application.
- publicKey: the VAPID public key.
- privateKey: the VAPID private key.
- contentEncoding: the type of content encoding to use (e.g. aesgcm or aes128gcm).

Returns


This method returns an object with the following fields:

- localPublicKey: The public key matched the private key used during
encryption.
- salt: A string representing the salt used to encrypt the payload.
- cipherText: The encrypted payload as a Buffer.



generateRequestDetails(pushSubscription, payload, options)


  1. ``` js
  2. const pushSubscription = {
  3.   endpoint: '< Push Subscription URL >';
  4.   keys: {
  5.     p256dh: '< User Public Encryption Key >',
  6.     auth: '< User Auth Secret >'
  7.   }
  8. };

  9. const payload = '< Push Payload String >';

  10. const options = {
  11.   gcmAPIKey: '< GCM API Key >',
  12.   vapidDetails: {
  13.     subject: '< \'mailto\' Address or URL >',
  14.     publicKey: '< URL Safe Base64 Encoded Public Key >',
  15.     privateKey: '< URL Safe Base64 Encoded Private Key >',
  16.   }
  17.   TTL: <Number>,
  18.   headers: {
  19.     '< header name >': '< header value >'
  20.   },
  21.   contentEncoding: '< Encoding type, e.g.: aesgcm or aes128gcm >',
  22.   proxy: '< proxy server options >'
  23. }

  24. try {
  25.   const details = webpush.generateRequestDetails(
  26.     pushSubscription,
  27.     payload,
  28.     options
  29.   );
  30. } catch (err) {
  31.   console.error(err);
  32. }
  33. ```

Note: When calling generateRequestDetails() the payload argument

does not need to be defined, passing in null will return no body and

exclude any unnecessary headers.

Headers related to the GCM API Key and / or VAPID keys will be included

if supplied and required.


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 encrypted and a [Buffer](https://nodejs.org/api/buffer.html)
will be returned via the payload parameter.

This argument must be either a string or a node
[Buffer](https://nodejs.org/api/buffer.html).

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.

- gcmAPIKey can be a GCM API key to be used for this request and this
request only. This overrides any API key set via setGCMAPIKey().
- vapidDetails should be an object with subject, publicKey and
privateKey values defined. These values should follow the VAPID Spec.
- 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.
- contentEncoding is the type of push encoding to use (e.g. 'aesgcm', by default, or 'aes128gcm').
that may either be a string URI of the proxy server (eg. http://< hostname >:< port >)
or an "options" object with more specific properties.

Returns


An object containing all the details needed to make a network request, the
object will contain:

- 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 Node Buffer).



Browser Support


BrowserPush without PayloadPush with PayloadVAPIDNotes
Chrome✓ v42+✓ v50+✓ v52+In v51 and less, the `gcm_sender_id` is needed to get a push subscription.
Edge✓ v17+ (April 2018)✓ v17+ (April 2018)✓ v17+ (April 2018)
Firefox✓ v44+✓ v44+✓ v46+
Opera✓ v39+ *✓ v39+ * * Opera supports push on Android but not on desktop.

  The gcm_sender_id is needed to get a push subscription.
Safari
Samsung Internet Browser✓ v4.0.10-53+✓ v5.0.30-40+The `gcm_sender_id` is needed to get a push subscription.

Help


Service Worker Cookbook

The Service Worker Cookbook is full of Web Push
examples using this library.

Running tests


Prerequisites:

Java JDK or JRE (http://www.oracle.com/technetwork/java/javase/downloads/index.html)


To run tests:

    npm test