web-push

repository·master·Indexed 25 days ago

https://github.com/web-push-libs/web-push

A Node.js library for sending Web Push notifications from a backend server. It handles the Web Push Protocol, message encryption, and legacy GCM support. Version 3.6.7 includes a CLI for generating VAPID keys and sending notifications, as well as programmatic APIs for encrypting payloads and generating request details.

Tokens
5K
Snippets
12
Records
33
Agent score
85%

What's inside web-push

  1. Use VAPID public key in browser subscription

    master

    When subscribing to push messages in the browser, you must pass your VAPID public key to the applicationServerKey option of the subscribe method.

    registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: '<Your Public Key from generateVAPIDKeys()>'
    });
  2. Basic usage of web-push

    master

    To send a push notification, you typically need to generate VAPID keys once, set your GCM API key, and configure VAPID details. You then use sendNotification with a subscription object (which matches the JSON structure of a browser's PushSubscription) and your payload.

    const webpush = require('web-push');
    
    // VAPID keys should be generated only once.
    const vapidKeys = webpush.generateVAPIDKeys();
    
    webpush.setGCMAPIKey('<Your GCM API Key Here>');
    webpush.setVapidDetails(
      'mailto:example@yourdomain.org',
      vapidKeys.publicKey,
      vapidKeys.privateKey
    );
    
    // This is the same output of calling JSON.stringify on a PushSubscription
    const pushSubscription = {
      endpoint: '.....',
      keys: {
        auth: '.....',
        p256dh: '.....'
      }
    };
    
    webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
  3. Generate VAPID headers with getVapidHeaders()

    master

    The getVapidHeaders() method generates the Authorization and Crypto-Key headers required for VAPID-authenticated push requests.

    Input

    • audience: The origin of the push service (e.g., https://fcm.googleapis.com).
    • subject: A mailto: address or a 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

    An object containing:

    • localPublicKey: The public key matched to the private key used.
    • salt: A string representing the salt used for encryption.
    • cipherText: The encrypted payload as a Buffer.
    const parsedUrl = url.parse(subscription.endpoint);
    const audience = parsedUrl.protocol + '//' +
      parsedUrl.hostname;
    
    const vapidHeaders = vapidHelper.getVapidHeaders(
      audience,
      'mailto: example@web-push-node.org',
      vapidDetails.publicKey,
      vapidDetails.privateKey,
      'aes128gcm'
    );
  4. sendNotification(pushSubscription, payload, options)

    master

    Sends a push notification to a specific subscription. This method handles encryption automatically if a payload and subscription keys are provided. It returns a Promise that resolves with the response details (statusCode, headers, body) or rejects on error.

    webpush.sendNotification(
      pushSubscription,
      payload,
      options
    );
  5. Generate request details with generateRequestDetails()

    master

    The generateRequestDetails() method prepares all the necessary components (endpoint, method, headers, and body) to perform a network request to a push service.

    Input

    1. pushSubscription

    An object containing the subscription details. It should match the format of a PushSubscription object serialized via JSON.stringify() in a browser.

    2. payload (Optional)

    A string or Node.js Buffer. If provided, it will be encrypted. To encrypt a payload, the pushSubscription must include a keys object with p256dh and auth values. Passing null will return no body and exclude unnecessary headers.

    3. options (Optional)

    An object containing:

    • gcmAPIKey: A GCM API key for this specific request.
    • vapidDetails: An object with subject, publicKey, and privateKey (following the VAPID Spec).
    • TTL: Time-to-live in seconds.
    • headers: An object of extra headers to add.
    • contentEncoding: Encoding type (e.g., 'aesgcm' or 'aes128gcm').
    • urgency: Delivery priority (very-low, low, normal, or high).
    • topic: A unique identifier (max 32 characters) for notification coalescing.
    • proxy: Configuration for an HttpsProxyAgent (string URI or options object).

    Returns

    An object containing:

    • endpoint: The URL to send the request to.
    • method: Always 'POST'.
    • headers: The headers to include in the request.
    • body: The request body as a Node.js Buffer.
    const pushSubscription = {
      endpoint: '< Push Subscription URL >',
      keys: {
        p256dh: '< User Public Encryption Key >',
        auth: '< User Auth Secret >'
      }
    };
    
    const payload = '< Push Payload String >';
    
    const options = {
      gcmAPIKey: '< GCM API Key >',
      vapidDetails: {
        subject: '< \'mailto\' Address or URL >',
        publicKey: '< URL Safe Base64 Encoded Public Key >',
        privateKey: '< URL Safe Base64 Encoded Private Key >',
      },
      TTL: <Number>,
      headers: {
        '< header name >': '< header value >'
      },
      contentEncoding: '< Encoding type, e.g.: aesgcm or aes128gcm >',
      urgency:'< Default is normal "Defult" >',
      topic:'< Use a maximum of 32 characters from the URL or filename-safe Base64 characters sets. >',
      proxy: '< proxy server options >'
    }
    
    try {
      const details = webpush.generateRequestDetails(
        pushSubscription,
        payload,
        options
      );
    } catch (err) {
      console.error(err);
    }
  6. Reference: web-push CLI flags for send-notification

    master

    The following flags are available for the web-push send-notification command:

    FlagDescription
    --endpoint=<url>The push service endpoint URL
    --key=<browser key>The user's p256dh key
    --auth=<auth secret>The user's auth secret
    --payload=<message>The message payload
    --encoding=<aesgcm | aes128gcm>The encoding type
    --ttl=<seconds>Time to live in seconds
    --vapid-subject=<vapid subject>VAPID subject (mailto: or https: URI)
    --vapid-pubkey=<public key>VAPID public key (URL Safe Base64)
    --vapid-pvtkey=<private key>VAPID private key (URL Safe Base64)
    --proxy=<http proxy uri>Proxy server URI
    --gcm-api-key=<api key>GCM API key
    web-push send-notification  \
    --endpoint=https://fcm.googleapis.com/fcm/send/d61c5u920dw:APA91bEmnw8utjDYCqSRplFMVCzQMg9e5XxpYajvh37mv2QIlISdasBFLbFca9ZZ4Uqcya0ck-SP84YJUEnWsVr3mwYfaDB7vGtsDQuEpfDdcIqOX_wrCRkBW2NDWRZ9qUz9hSgtI3sY \
    --key=BL7ELU24fJTAlH5Kyl8N6BDCac8u8li_U5PIwG963MOvdYs9s7LSzj8x_7v7RFdLZ9Eap50PiiyF5K0TDAis7t0 \
    --auth=juarI8x__VnHvsOgfeAPHg \
    --vapid-subject=mailto:example@qq.com \
    --vapid-pubkey=BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE \
    --vapid-pvtkey=I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0 \
    --payload=Hello
  7. Reference: sendNotification options

    master

    The options object for sendNotification accepts the following keys:

    • gcmAPIKey: <String> Overrides the global GCM API key for this request.
    • vapidDetails: <Object> Contains subject, publicKey, and privateKey.
    • timeout: <Number> Socket timeout in milliseconds.
    • TTL: <Number> Time-to-live in seconds.
    • headers: <Object> Additional HTTP headers.
    • contentEncoding: <String> Encoding type (e.g., aesgcm or aes128gcm).
    • urgency: <String> Delivery priority (very-low, low, normal, or high).
    • topic: <String> Identifier for notification coalescing (max 32 chars).
    • proxy: <String|Object> Proxy server configuration (compatible with HttpsProxyAgent).
    • agent: <HttpsAgent> HTTPS Agent instance (ignored if proxy is set).
  8. Browser support for Web Push

    master

    Compatibility matrix for Web Push features across major browsers:

    BrowserPush without PayloadPush with PayloadVAPIDNotes
    Chrome✓ v42+✓ v50+✓ v52+In v51 and less, gcm_sender_id is needed.
    Edge✓ v17+✓ v17+✓ v17+
    Firefox✓ v44+✓ v44+✓ v46+
    Opera✓ v39+*✓ v39+**Supports push on Android but not desktop. gcm_sender_id is needed.
    Safari✓ v16+✓ v16+✓ v16+Safari 16 in macOS 13 or later.
    Samsung Internet✓ v4.0.10-53+✓ v5.0.30-40+gcm_sender_id is needed.
  9. Use web-push CLI

    master

    You can install web-push globally to use it as a command-line tool for generating VAPID keys or sending notifications manually.

    Installation:

    npm install web-push -g

    Commands:

    • web-push generate-vapid-keys [--json]: Generates a new pair of VAPID keys. Use --json to get the output in JSON format.
    • web-push send-notification <flags>: Sends a notification using the provided parameters.
  10. Set GCM API Key in WebPushLib

    master
    When sending messages to a GCM (Google Cloud Messaging) endpoint, you must provide an API key. You can set a global API key for the WebPushLib instance using setGCMAPIKey(), or pass a unique key per notification via the gcmAPIKey option in sendNotification() or generateRequestDetails().
  11. Send a push notification with sendNotification()

    master

    The primary method for sending a push notification. It encrypts the payload and performs an HTTPS POST request to the subscription endpoint.

    Parameters:

    • subscription: The PushSubscription object.
    • payload (optional): The string or Buffer to be sent to the user.
    • options (optional): Configuration overrides (see options).

    Returns: Returns a Promise that resolves with an object containing { statusCode, body, headers } if successful, or rejects with a WebPushError if the server returns a non-2xx status code.