### Browser Client Push Notification Setup (JavaScript) Source: https://context7.com/web-push-libs/web-push/llms.txt Demonstrates how to set up a web browser client to receive push notifications. This includes registering a service worker, subscribing to push notifications using VAPID keys, and sending the subscription details to a backend server. ```javascript // In your web application's JavaScript (client-side) // Register service worker navigator.serviceWorker.register('/service-worker.js') .then(registration => { console.log('Service Worker registered'); // Subscribe to push notifications return registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array('BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE') }); }) .then(subscription => { console.log('Push subscription:', subscription); // Send subscription to your backend server return fetch('/api/push/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(subscription) }); }) .catch(error => { console.error('Subscription failed:', error); }); // Helper function to convert VAPID public key function urlBase64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding) .replace(/-/g, '+') .replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } ``` -------------------------------- ### Generate VAPID keys using web-push CLI Source: https://github.com/web-push-libs/web-push/blob/master/README.md This command-line example shows how to generate VAPID public and private keys using the globally installed web-push tool. The output is in JSON format, useful for programmatic use. ```shell > web-push generate-vapid-keys --json > {"publicKey":"BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE","privateKey":"I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0"} ``` -------------------------------- ### Initialize web-push with VAPID keys (Node.js) Source: https://github.com/web-push-libs/web-push/blob/master/README.md This snippet shows how to initialize the web-push library using generated VAPID keys and set the GCM API key. It prepares the library for sending push notifications. ```javascript const webpush = require('web-push'); // VAPID keys should be generated only once. const vapidKeys = webpush.generateVAPIDKeys(); webpush.setGCMAPIKey(''); 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'); ``` -------------------------------- ### Subscribe to push messages with applicationServerKey (JavaScript) Source: https://github.com/web-push-libs/web-push/blob/master/README.md This code demonstrates how to subscribe to push notifications in a browser environment, passing the public VAPID key to the push manager. This is essential for the client to register for push updates. ```javascript registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: '' }); ``` -------------------------------- ### Send notification using web-push CLI Source: https://github.com/web-push-libs/web-push/blob/master/README.md This command demonstrates sending a push notification using the web-push CLI. It includes parameters for the endpoint, keys, VAPID details, payload, and proxy settings. ```shell 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 ``` -------------------------------- ### setVapidDetails() - Configure VAPID Authentication Source: https://github.com/web-push-libs/web-push/blob/master/README.md Sets the VAPID (Voluntary Application Server Identification) details for server authentication. Must be called before sending notifications with VAPID authentication. ```APIDOC ## setVapidDetails(subject, publicKey, privateKey) ### Description Configures the VAPID credentials for server authentication. These details are used to sign all subsequent push notifications sent through this instance of the web-push library. ### Method Function (Synchronous) ### Parameters #### subject (string) - Required A mailto: address or URL that identifies the application server. Used by the push service to contact you if issues arise. - Format: 'mailto:your-email@example.com' or 'https://example.com' #### publicKey (string) - Required The URL-safe Base64 encoded public VAPID key generated via `generateVAPIDKeys()` #### privateKey (string) - Required The URL-safe Base64 encoded private VAPID key generated via `generateVAPIDKeys()` ### Request Example ```javascript const webpush = require('web-push'); const vapidKeys = webpush.generateVAPIDKeys(); webpush.setVapidDetails( 'mailto:example@yourdomain.org', vapidKeys.publicKey, vapidKeys.privateKey ); ``` ### Response Returns nothing (void). Configuration is applied to the library instance. ### Usage Notes - **Call once**: Set VAPID details once during application startup - **Subject format**: Use a mailto: address or URL that the push service can contact - **Key format**: Keys must be in URL-safe Base64 format as generated by `generateVAPIDKeys()` - **Global configuration**: After calling this, all subsequent `sendNotification()` calls will use these VAPID details unless overridden in options ### Example Complete Setup ```javascript const webpush = require('web-push'); // Option 1: Generate new keys (first time only) const vapidKeys = webpush.generateVAPIDKeys(); // Option 2: Use existing stored keys // const vapidKeys = { // publicKey: process.env.VAPID_PUBLIC_KEY, // privateKey: process.env.VAPID_PRIVATE_KEY // }; webpush.setVapidDetails( 'mailto:example@yourdomain.org', vapidKeys.publicKey, vapidKeys.privateKey ); // Now sendNotification() will automatically use these VAPID details webpush.sendNotification(pushSubscription, 'Your notification message'); ``` ``` -------------------------------- ### Send Push Notifications via CLI Source: https://context7.com/web-push-libs/web-push/llms.txt Sends push notifications directly from the command line for testing and automation purposes. Supports basic notifications, encrypted payloads, and VAPID authentication. ```bash # Basic notification without payload web-push send-notification \ --endpoint=https://fcm.googleapis.com/fcm/send/d61c5u920dw:APA91bEmnw... \ --vapid-subject=mailto:admin@example.com \ --vapid-pubkey=BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8... \ --vapid-pvtkey=I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0 # Notification with text payload web-push send-notification \ --endpoint=https://fcm.googleapis.com/fcm/send/d61c5u920dw:APA91bEmnw... \ --key=BL7ELU24fJTAlH5Kyl8N6BDCac8u8li_U5PIwG963MOvdYs9s7LSzj8x... \ --auth=juarI8x__VnHvsOgfeAPHg \ --payload="Hello from CLI" \ --vapid-subject=mailto:admin@example.com \ --vapid-pubkey=BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8... \ --vapid-pvtkey=I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0 ``` -------------------------------- ### Generate VAPID Keys using CLI Source: https://context7.com/web-push-libs/web-push/llms.txt Generates VAPID keys (public and private) for application authentication using the web-push command-line interface. Supports both human-readable and JSON output formats. ```bash # Install globally npm install web-push -g # Generate VAPID keys (human-readable format) web-push generate-vapid-keys # Output: # ======================================= # # Public Key: # BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE # # Private Key: # I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0 # # ======================================= # Generate VAPID keys (JSON format for scripting) web-push generate-vapid-keys --json # Output: # {"publicKey":"BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE","privateKey":"I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0"} # Store in environment variables export VAPID_PUBLIC_KEY="BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE" export VAPID_PRIVATE_KEY="I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0" ``` -------------------------------- ### Generate VAPID Authorization and Crypto-Key Headers Source: https://github.com/web-push-libs/web-push/blob/master/README.md Generates the necessary Authorization and Crypto-Key headers for VAPID authentication. It requires the push service audience, application subject (mailto or URL), VAPID public and private keys, and the content encoding type. The method returns details about the encryption process, including the local public key, salt, and ciphertext. ```javascript 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' ); ``` -------------------------------- ### setVapidDetails Method Source: https://github.com/web-push-libs/web-push/blob/master/README.md Configures VAPID authentication details for push notifications. This method sets the server contact information and cryptographic keys required for VAPID authentication according to the VAPID specification. ```APIDOC ## setVapidDetails ### Description Configures VAPID authentication details for push notifications by setting the server contact information and cryptographic keys. ### Method Function/Configuration Method ### Parameters #### Input Parameters - **subject** (string) - Required - VAPID server contact information as either an `https:` or `mailto:` URI (per VAPID specification) - **publicKey** (string) - Required - The VAPID public key - **privateKey** (string) - Required - The VAPID private key ### Returns None (void) ### Notes - Subject must be formatted as either an HTTPS URI or mailto URI - Complies with [VAPID specification](https://datatracker.ietf.org/doc/html/draft-thomson-webpush-vapid#section-2.1) ``` -------------------------------- ### Register Service Worker and Subscribe to Push Notifications Source: https://github.com/web-push-libs/web-push/blob/master/test/data/demo/index.html Registers a service worker, establishes bidirectional communication via MessageChannel, and subscribes to push notifications with optional VAPID key. The code checks for service worker support, registers 'service-worker.js', sets up message channel communication with the active service worker, and optionally applies a VAPID key from URL parameters to the subscription options. ```JavaScript (function() { if (!('serviceWorker' in navigator)) { return; } return navigator.serviceWorker.register('service-worker.js') .then(function(registration) { console.log('service worker registered'); return navigator.serviceWorker.ready; }) .then(function(reg) { var channel = new MessageChannel(); channel.port1.onmessage = function(e) { window.document.title = e.data; } reg.active.postMessage('setup', [channel.port2]); var subscribeOptions = { userVisibleOnly: true }; // Figure out the vapid key var searchParam = window.location.search; vapidRegex = searchParam.match(/vapid=(.[^&]*)/); if (vapidRegex) { // Convert the base 64 encoded string subscribeOptions.applicationServerKey = base64UrlToUint8Array(vapidRegex[1]); } console.log(subscribeOptions); return reg.pushManager.subscribe(subscribeOptions); }) .then(function(subscription) { console.log(JSON.stringify(subscription)); window.subscribeSuccess = true; window.testSubscription = JSON.stringify(subscription); }) .catch(function(err) { window.subscribeSuccess = false; window.subscribeError = err; }); })(); ``` -------------------------------- ### Send notification with options (Node.js) Source: https://github.com/web-push-libs/web-push/blob/master/README.md This snippet illustrates the detailed usage of the `sendNotification` function in Node.js, including various options like GCM API key, VAPID details, timeouts, content encoding, and proxy settings. ```javascript 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 >' }, timeout: TTL: , headers: { '< header name >': '< header value >' }, contentEncoding: '< Encoding type, e.g.: aesgcm or aes128gcm >', urgency:'< Default is "normal" >', topic:'< Use a maximum of 32 characters from the URL or filename-safe Base64 characters sets. >', proxy: '< proxy server options >', agent: '< https.Agent instance >' } webpush.sendNotification( pushSubscription, payload, options ); ``` -------------------------------- ### Generate VAPID Headers for Manual HTTP Requests Source: https://context7.com/web-push-libs/web-push/llms.txt Generates VAPID authentication headers required for manual HTTP request construction to push services. It requires subscription endpoint details and VAPID credentials. ```javascript const webpush = require('web-push'); const url = require('url'); const subscription = { endpoint: 'https://fcm.googleapis.com/fcm/send/someendpoint' }; const vapidDetails = { subject: 'mailto:admin@example.com', publicKey: 'BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE', privateKey: 'I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0' }; // Extract audience (origin) from subscription endpoint const parsedUrl = url.parse(subscription.endpoint); const audience = parsedUrl.protocol + '//' + parsedUrl.hostname; try { const vapidHeaders = webpush.getVapidHeaders( audience, vapidDetails.subject, vapidDetails.publicKey, vapidDetails.privateKey, 'aes128gcm' // contentEncoding: 'aes128gcm' or 'aesgcm' ); console.log('VAPID Headers:'); console.log('Authorization:', vapidHeaders.Authorization); // For aes128gcm: 'vapid t=, k=' // For aesgcm: 'WebPush ' if (vapidHeaders['Crypto-Key']) { console.log('Crypto-Key:', vapidHeaders['Crypto-Key']); // For aesgcm only: 'p256ecdsa=' } // Use these headers in your HTTP request to the push service } catch (error) { console.error('Failed to generate VAPID headers:', error); } ``` -------------------------------- ### Send Push Notification with Advanced Options (CLI) Source: https://context7.com/web-push-libs/web-push/llms.txt Sends a push notification using the web-push CLI with advanced options such as TTL, encoding, VAPID details, and proxy configuration. This command is useful for detailed control over notification delivery and authentication. ```bash web-push send-notification \ --endpoint=https://fcm.googleapis.com/fcm/send/someendpoint \ --key=BL7ELU24fJTAlH5Kyl8N6BDCac8u8li_U5PIwG963MOvdYs9s7LSzj8x... \ --auth=juarI8x__VnHvsOgfeAPHg \ --payload='{"title":"Alert","body":"Important message"}' \ --ttl=3600 \ --encoding=aes128gcm \ --vapid-subject=https://example.com/contact \ --vapid-pubkey=$VAPID_PUBLIC_KEY \ --vapid-pvtkey=$VAPID_PRIVATE_KEY \ --proxy=http://proxy.example.com:8080 ``` -------------------------------- ### setGCMAPIKey() - Configure GCM Legacy Support Source: https://github.com/web-push-libs/web-push/blob/master/README.md Sets the Google Cloud Messaging (GCM) API key for legacy browser support. GCM is used for older browsers that don't support modern push notification standards. ```APIDOC ## setGCMAPIKey(gcmAPIKey) ### Description Configures the GCM API key for sending notifications through Google Cloud Messaging. This is used for legacy browser support and older versions of Chrome that rely on GCM for push message delivery. ### Method Function (Synchronous) ### Parameters #### gcmAPIKey (string) - Required Your Google Cloud Messaging API key obtained from Google Cloud Console ### Request Example ```javascript const webpush = require('web-push'); webpush.setGCMAPIKey(''); ``` ### Response Returns nothing (void). Configuration is applied to the library instance. ### Usage Notes - **Legacy support**: GCM is used primarily for older browser versions; modern browsers use standard Web Push Protocol - **Call once**: Set the GCM API key once during application startup - **Optional**: Not required if you only support modern browsers with VAPID authentication - **Override in options**: Can be overridden per-notification by passing `gcmAPIKey` in the options parameter to `sendNotification()` - **Obtain API key**: Get your GCM API key from [Google Cloud Console](https://console.cloud.google.com/) ### Example Setup ```javascript const webpush = require('web-push'); // Configure both GCM and VAPID for maximum compatibility webpush.setGCMAPIKey(''); const vapidKeys = webpush.generateVAPIDKeys(); webpush.setVapidDetails( 'mailto:example@yourdomain.org', vapidKeys.publicKey, vapidKeys.privateKey ); // Now notifications will work with both legacy and modern browsers webpush.sendNotification(pushSubscription, 'Your notification message'); ``` ``` -------------------------------- ### generateVAPIDKeys() - Generate VAPID Key Pair Source: https://github.com/web-push-libs/web-push/blob/master/README.md Generates a new VAPID (Voluntary Application Server Identification) key pair for server authentication. VAPID keys are required for modern push notifications and should be generated once and stored securely. ```APIDOC ## generateVAPIDKeys() ### Description Generates a new VAPID key pair (public and private keys) for server identification and authentication with push services. Should be called once during setup and the keys stored securely for reuse. ### Method Function (Synchronous) ### Parameters None ### Request Example ```javascript const webpush = require('web-push'); const vapidKeys = webpush.generateVAPIDKeys(); console.log(vapidKeys); ``` ### Response #### Success Response Returns an object containing the public and private VAPID keys. #### Response Fields - **publicKey** (string) - URL-safe Base64 encoded public key for use in client subscription - **privateKey** (string) - URL-safe Base64 encoded private key for server authentication #### Response Example ```javascript { "publicKey": "BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE", "privateKey": "I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0" } ``` ### Usage Notes - **One-time generation**: Generate keys once and store them securely in environment variables or configuration files - **Public key distribution**: Share the public key with clients for push subscription - **Private key security**: Keep the private key secret and never expose it to clients - **Reuse**: Use the same key pair for all notifications from your application server - **Rotation**: Consider rotating keys periodically for security ### Example Setup ```javascript const webpush = require('web-push'); // Generate keys (do this once) const vapidKeys = webpush.generateVAPIDKeys(); // Store these securely: // process.env.VAPID_PUBLIC_KEY = vapidKeys.publicKey; // process.env.VAPID_PRIVATE_KEY = vapidKeys.privateKey; // Set up the library with stored keys webpush.setVapidDetails( 'mailto:example@yourdomain.org', process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY ); ``` ``` -------------------------------- ### Send Push Notification with Payload and Options (JavaScript) Source: https://context7.com/web-push-libs/web-push/llms.txt Sends a push notification to a subscribed client with an optional text payload and advanced configuration options. It requires the 'web-push' library and VAPID keys for authentication. The function returns a Promise that resolves with the response status and headers or rejects with an error. ```javascript const webpush = require('web-push'); // Configure VAPID details webpush.setVapidDetails( 'mailto:admin@example.com', 'BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE', 'I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0' ); // Push subscription object obtained from the browser const pushSubscription = { endpoint: 'https://fcm.googleapis.com/fcm/send/d61c5u920dw:APA91bEmnw8utjDYCqSRplFMVCzQMg9e5XxpYajvh37mv2QIlISdasBFLbFca9ZZ4Uqcya0ck-SP84YJUEnWsVr3mwYfaDB7vGtsDQuEpfDdcIqOX_wrCRkBW2NDWRZ9qUz9hSgtI3sY', expirationTime: null, keys: { p256dh: 'BL7ELU24fJTAlH5Kyl8N6BDCac8u8li_U5PIwG963MOvdYs9s7LSzj8x_7v7RFdLZ9Eap50PiiyF5K0TDAis7t0', auth: 'juarI8x__VnHvsOgfeAPHg' } }; // Simple notification with text payload const payload = JSON.stringify({ title: 'Hello!', body: 'You have a new notification', icon: '/icon.png', badge: '/badge.png', data: { url: 'https://example.com/news/item123' } }); // Send notification with comprehensive error handling webpush.sendNotification(pushSubscription, payload) .then(response => { console.log('Push sent successfully:', response.statusCode); console.log('Response headers:', response.headers); console.log('Response body:', response.body); }) .catch(error => { console.error('Push failed:', error); if (error.statusCode === 410 || error.statusCode === 404) { console.log('Subscription expired or invalid, remove from database'); } else if (error.statusCode === 429) { console.log('Rate limited, retry later'); } }); // Advanced: Send with custom options const options = { TTL: 3600, // Time to live in seconds (1 hour) urgency: 'high', // 'very-low', 'low', 'normal', or 'high' topic: 'news-updates', // Group notifications (max 32 chars) headers: { 'Custom-Header': 'value' }, contentEncoding: 'aes128gcm', // or 'aesgcm' for legacy timeout: 5000, // Socket timeout in milliseconds proxy: 'http://proxy.example.com:8080' // HTTP proxy server }; webpush.sendNotification(pushSubscription, payload, options) .then(response => { console.log('Notification sent with options:', response.statusCode); }) .catch(error => { console.error('Error:', error.message); }); ``` -------------------------------- ### Send Push Notification for Legacy Browsers (CLI) Source: https://context7.com/web-push-libs/web-push/llms.txt Sends a push notification to legacy browsers using the GCM API key. This method is for compatibility with older systems that rely on the Google Cloud Messaging service. ```bash export GCM_API_KEY="AIzaSyD4R_4R_4R_YOUR_KEY_HERE" web-push send-notification \ --endpoint=https://android.googleapis.com/gcm/send/someendpoint \ --gcm-api-key=$GCM_API_KEY \ --payload="Legacy browser notification" ``` -------------------------------- ### getVapidHeaders Method Source: https://github.com/web-push-libs/web-push/blob/master/README.md Generates VAPID authentication headers for push service requests. This method creates the Authorization and Crypto-Key headers required for authenticated push notification delivery. ```APIDOC ## getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) ### Description Generates VAPID authentication headers including Authorization and Crypto-Key headers for push service requests. ### Method Function ### Parameters #### Input Parameters - **audience** (string) - Required - The origin of the push service (protocol + hostname) - **subject** (string) - Required - The mailto or URL for your application - **publicKey** (string) - Required - The VAPID public key - **privateKey** (string) - Required - The VAPID private key - **contentEncoding** (string) - Required - The type of content encoding to use (e.g., aesgcm or aes128gcm) - **expiration** (number) - Optional - The expiration time for the headers ### Request Example ```javascript 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' ); ``` ### Response #### Success Response - **localPublicKey** (string) - The public key matched to the private key used during encryption - **salt** (string) - A string representing the salt used to encrypt the payload - **cipherText** (Buffer) - The encrypted payload as a Buffer object ### Notes - Returns an object containing headers ready for HTTP requests - Audience should be extracted from the push subscription endpoint ``` -------------------------------- ### Set GCM API Key Source: https://context7.com/web-push-libs/web-push/llms.txt Configure a GCM API key for legacy browser support including Chrome version 51 and earlier, Opera, and Samsung Internet Browser that rely on Google Cloud Messaging. ```APIDOC ## Set GCM API Key ### Description Configures a Google Cloud Messaging (GCM) API key for legacy browser support. This is used for older browser versions that do not support the modern Web Push Protocol with VAPID authentication. ### Method Function - Synchronous ### Function Signature ```javascript webpush.setGCMAPIKey(apiKey) -> void ``` ### Parameters - **apiKey** (string) - Required - Google Cloud Messaging API key from Firebase Console ### Supported Legacy Browsers - Chrome version 51 and earlier - Opera (older versions) - Samsung Internet Browser (older versions) ### Usage Examples ```javascript const webpush = require('web-push'); // Set GCM API Key directly webpush.setGCMAPIKey('AIzaSyD4R_4R_4R_YOUR_GCM_API_KEY_HERE'); // Set GCM API Key from environment variable (recommended) if (process.env.GCM_API_KEY) { webpush.setGCMAPIKey(process.env.GCM_API_KEY); } ``` ### Automatic Endpoints The GCM API Key is used automatically for endpoints starting with: - `https://android.googleapis.com/gcm/send` - `https://fcm.googleapis.com/fcm/send` (when VAPID is not available) ### Notes - This is optional and only needed for legacy browser support - Modern browsers use VAPID authentication instead - GCM API key can be obtained from Firebase Console - Store API key securely in environment variables, not in code - VAPID authentication is preferred over GCM for new implementations ``` -------------------------------- ### Set VAPID Details Globally in JavaScript Source: https://github.com/web-push-libs/web-push/blob/master/README.md Globally configures the VAPID subject, public key, and private key for the application. These values are used in subsequent calls to sendNotification() and generateRequestDetails() unless overridden in the options argument. The subject should be a mailto: URI following the VAPID specification. ```javascript webpush.setVapidDetails( 'mailto:user@example.org', process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY ); ``` -------------------------------- ### Generate VAPID Keys Source: https://context7.com/web-push-libs/web-push/llms.txt Generate a pair of VAPID public and private keys for authenticating push notifications. These keys should be generated once and stored securely for all future notifications. ```APIDOC ## Generate VAPID Keys ### Description Generates a pair of VAPID (Voluntary Application Server Identification) public and private keys for authenticating push notifications. Keys should be generated once and stored securely. ### Method Function - Synchronous ### Function Signature ```javascript webpush.generateVAPIDKeys() -> Object ``` ### Returns Object containing VAPID key pair: - **publicKey** (string) - Base64-encoded public key for sharing with browsers - **privateKey** (string) - Base64-encoded private key for server-side authentication (keep secure) ### Usage Example ```javascript const webpush = require('web-push'); // Generate VAPID keys (do this once and store them securely) const vapidKeys = webpush.generateVAPIDKeys(); console.log('Public Key:', vapidKeys.publicKey); console.log('Private Key:', vapidKeys.privateKey); // Store these keys in environment variables or secure configuration // Example output: // { // publicKey: 'BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE', // privateKey: 'I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0' // } ``` ### Response Example ```json { "publicKey": "BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE", "privateKey": "I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0" } ``` ### Notes - Generate keys only once per application - Store private key securely (environment variables or key management service) - Share public key with browsers during push subscription registration ``` -------------------------------- ### Configure VAPID Details Source: https://context7.com/web-push-libs/web-push/llms.txt Set global VAPID details that will be used for all subsequent push notification requests. This includes the subject (contact email or URL) and the VAPID key pair. ```APIDOC ## Configure VAPID Details ### Description Sets global VAPID (Voluntary Application Server Identification) details that will be applied to all subsequent push notification requests unless overridden per-request. This should typically be done once at application startup. ### Method Function - Synchronous ### Function Signature ```javascript webpush.setVapidDetails(subject, publicKey, privateKey) -> void ``` ### Parameters - **subject** (string) - Required - Contact information for the push service. Use 'mailto:admin@example.com' or 'https://example.com/contact' - **publicKey** (string) - Required - Base64-encoded VAPID public key - **privateKey** (string) - Required - Base64-encoded VAPID private key ### Usage Examples ```javascript const webpush = require('web-push'); // Set VAPID details globally using environment variables (recommended) webpush.setVapidDetails( 'mailto:admin@example.com', process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY ); // Alternative: use https URL as subject webpush.setVapidDetails( 'https://example.com/contact', 'BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE', 'I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0' ); ``` ### Important Notes - Call this function once at application startup - Subject must be either 'mailto:' URL or 'https://' URL - Safari's push service rejects localhost URLs - use mailto or public https URLs - Mozilla Firefox requires a mailto: subject - Browser push services use this information to contact the application server if issues occur ``` -------------------------------- ### Set GCM API Key for Legacy Browser Support Source: https://context7.com/web-push-libs/web-push/llms.txt Configures the GCM API key, which is necessary for supporting older browser versions (Chrome 51 and earlier, Opera, Samsung Internet Browser). This key is automatically used for specific endpoint patterns when VAPID authentication is not available. ```javascript const webpush = require('web-push'); // Set GCM API Key for legacy browser support webpush.setGCMAPIKey('AIzaSyD4R_4R_4R_YOUR_GCM_API_KEY_HERE'); // Can also be set via environment variable if (process.env.GCM_API_KEY) { webpush.setGCMAPIKey(process.env.GCM_API_KEY); } // This key is used automatically for endpoints starting with: // - https://android.googleapis.com/gcm/send // - https://fcm.googleapis.com/fcm/send (when VAPID is not available) ``` -------------------------------- ### Generate Request Details for Sending Push Notifications Source: https://github.com/web-push-libs/web-push/blob/master/README.md Constructs a detailed object for sending push notifications, incorporating push subscription details, payload, and various options. It supports GCM API keys, VAPID details, TTL, custom headers, content encoding, urgency, topic, and proxy settings. If the payload is null, no body or unnecessary headers are included. The function includes relevant GCM or VAPID headers if provided and required. ```javascript 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: , 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); } ``` -------------------------------- ### generateRequestDetails Method Source: https://github.com/web-push-libs/web-push/blob/master/README.md Generates complete push notification request details including headers and body. This method prepares all necessary information for sending authenticated push notifications with optional encryption and custom headers. ```APIDOC ## generateRequestDetails(pushSubscription, payload, options) ### Description Generates complete push notification request details including headers, body, and authentication information. Payload argument is optional; passing null returns no body and excludes unnecessary headers. ### Method Function ### Parameters #### Input Parameters - **pushSubscription** (object) - Required - Push subscription object containing endpoint and keys - **payload** (string|null) - Optional - The push payload string (can be null) - **options** (object) - Optional - Configuration options object #### Push Subscription Object - **endpoint** (string) - The push service endpoint URL - **keys.p256dh** (string) - User's public encryption key - **keys.auth** (string) - User's auth secret #### Options Object - **gcmAPIKey** (string) - Optional - GCM API Key for GCM push service - **vapidDetails** (object) - Optional - VAPID authentication details - **subject** (string) - mailto address or URL - **publicKey** (string) - URL safe Base64 encoded public key - **privateKey** (string) - URL safe Base64 encoded private key - **TTL** (number) - Optional - Time to live in seconds - **headers** (object) - Optional - Custom HTTP headers - **contentEncoding** (string) - Optional - Encoding type (aesgcm or aes128gcm) - **urgency** (string) - Optional - Urgency level (default: "normal") - **topic** (string) - Optional - Maximum 32 characters from URL or filename-safe Base64 characters - **proxy** (object) - Optional - Proxy server options ### Request Example ```javascript 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: 24 * 60 * 60, headers: { '< header name >': '< header value >' }, contentEncoding: '< aesgcm or aes128gcm >', urgency: 'normal', topic: '< 32 character max >', proxy: '< proxy server options >' }; try { const details = webpush.generateRequestDetails( pushSubscription, payload, options ); } catch (err) { console.error(err); } ``` ### Response #### Success Response Returns an object containing complete request details for sending push notifications ### Error Handling - Throws an error if invalid parameters are provided - Use try-catch block to handle errors ### Notes - Payload argument does not need to be defined; null returns no body - GCM API Key and VAPID headers are included if supplied and required - Headers related to GCM API Key or VAPID keys are automatically included when applicable ``` -------------------------------- ### Service Worker Push Event Handling (JavaScript) Source: https://context7.com/web-push-libs/web-push/llms.txt Code for a service worker that listens for 'push' events and displays notifications to the user. It also handles 'notificationclick' events to open a specific URL when a notification is clicked. ```javascript // Service worker code (service-worker.js) self.addEventListener('push', event => { const data = event.data ? event.data.json() : {}; const title = data.title || 'Notification'; const options = { body: data.body || 'You have a new notification', icon: data.icon || '/icon.png', badge: data.badge || '/badge.png', data: data.data }; event.waitUntil( self.registration.showNotification(title, options) ); }); self.addEventListener('notificationclick', event => { event.notification.close(); event.waitUntil( clients.openWindow(event.notification.data.url || '/') ); }); ``` -------------------------------- ### Generate VAPID Keys for Web Push Authentication Source: https://context7.com/web-push-libs/web-push/llms.txt Generates a pair of VAPID public and private keys required for authenticating push notifications. These keys should be generated once and stored securely for reuse across multiple notifications. ```javascript const webpush = require('web-push'); // Generate VAPID keys (do this once and store them securely) const vapidKeys = webpush.generateVAPIDKeys(); console.log('Public Key:', vapidKeys.publicKey); console.log('Private Key:', vapidKeys.privateKey); // Store these keys in environment variables or secure configuration // Example output: // { // publicKey: 'BGtkbcjrO12YMoDuq2sCQeHlu47uPx3SHTgFKZFYiBW8Qr0D9vgyZSZPdw6_4ZFEI9Snk1VEAj2qTYI1I1YxBXE', // privateKey: 'I0_d0vnesxbBSUmlDdOKibGo6vEXRO-Vu88QlSlm5j0' // } ```