### node-apn v1.7 Notification Setup and Sending Source: https://github.com/parse-community/node-apn/blob/master/doc/whats-new.markdown Demonstrates how to set up a connection and send a notification using the older v1.7 API of node-apn. ```javascript function setup() { var connection = new apn.Connection(configuration); connection.on("transmissionError", notificationFailed); } func sendNotification(user) { var note = new apn.Notification(); note.alert = "Hello " + user.name; connection.pushNotification(note, user.token); } ``` -------------------------------- ### node-apn v2.0 Notification Setup and Sending Source: https://github.com/parse-community/node-apn/blob/master/doc/whats-new.markdown Illustrates the updated method for setting up a provider and sending notifications with the new v2.0 API of node-apn, including promise-based handling of responses. ```javascript function setup() { let connection = new apn.Provider(configuration); } function sendNotification(user) { let note = new apn.Notification(); note.alert = "Hello " + user.name; note.topic = "io.github.node-apn.test" connection.send(note, user.token).then( (response) => { response.sent.forEach( (token) => { notificationSent(user, token); }); response.failed.forEach( (failure) => { if (failure.error) { // A transport-level error occurred (e.g. network problem) notificationError(user, failure.device, failure.error); } else { // `failure.status` is the HTTP status code // `failure.response` is the JSON payload notificationFailed(user, failure.device, failure.status, failure.response); } }); }); } ``` -------------------------------- ### Install Node APN Source: https://github.com/parse-community/node-apn/blob/master/README.md Installs the Node APN module using npm. This is the first step to integrate Apple Push Notifications into your Node.js application. ```bash npm install @parse/node-apn --save ``` -------------------------------- ### APNS Notification Payload Example Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown An example JSON output representing the structure of an APNS notification payload configured using node-apn setters. ```json { "aps":{ "alert":{ "body":"Hello, world!", "title":"node-apn", "action":"npm install" }, "badge":10, "mutable-content": 1, "category":"nodejs" } } ``` -------------------------------- ### Successful Channel Creation Response Source: https://github.com/parse-community/node-apn/blob/master/README.md Example response object upon successful creation of a notification channel. ```javascript { apns-request-id: '0309F412-AA57-46A8-9AC6-B5AECA8C4594', apns-channel-id: 'dHN0LXNyY2gtY2hubA==' // The new channel } ``` -------------------------------- ### ReadAll Channels Response Source: https://github.com/parse-community/node-apn/blob/master/README.md Example response object containing a list of active channel IDs. ```javascript { apns-request-id: 'some id value', channels: ['dHN0LXNyY2gtY2hubA==', 'eCN0LXNyY2gtY2hubA==' ...] // A list of active channels } ``` -------------------------------- ### Standard Notification Payload Source: https://github.com/parse-community/node-apn/blob/master/README.md Example of the JSON payload sent to a device for a standard notification. ```json {"messageFrom":"John Appelseed","aps":{"badge":3,"sound":"ping.aiff","alert":"\uD83D\uDCE7 \u2709 You have a new message"}} ``` -------------------------------- ### Live Activity Notification Payload Source: https://github.com/parse-community/node-apn/blob/master/README.md Example of the JSON payload sent to a device for a Live Activity notification. ```json {"messageFrom":"John Appleseed","aps":{"badge":3,"sound":"ping.aiff","alert":"\uD83D\uDCE7 \u2709 You have a new message", "relevance-score":75,"timestamp":1683129662,"stale-date":1683216062,"event":"update","content-state":{}}} ``` -------------------------------- ### Get Device Token Source: https://github.com/parse-community/node-apn/blob/master/README.md Obtain a device token string from your application. ```javascript let deviceToken = "a9d0ed10e9cfd022a61cb08753f49c5a0b0dfb383697bf9f9d750a1003da19c7" ``` -------------------------------- ### Get Bundle ID Source: https://github.com/parse-community/node-apn/blob/master/README.md Obtain your application's bundle identifier, required for channel management. ```javascript let bundleId = "com.node.apn"; ``` -------------------------------- ### Gracefully Shutdown node-apn Connection Source: https://github.com/parse-community/node-apn/blob/master/doc/provider.markdown Indicates to node-apn to close all open connections once the queue of pending notifications is fully drained. This enables application termination. Pushing notifications after shutdown starts will throw an error. ```javascript connection.shutdown(); ``` -------------------------------- ### Initialize apn.Notification Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown Demonstrates how to initialize a new apn.Notification object, optionally pre-populating properties like alert, sound, mutableContent, and a custom payload. ```javascript let notification = new apn.Notification({ alert: "Hello, world!", sound: "chime.caf", mutableContent: 1, payload: { "sender": "node-apn", }, }); ``` -------------------------------- ### Connect to APN Provider Source: https://github.com/parse-community/node-apn/blob/master/README.md Creates a new APN provider instance using token-based authentication. Requires a path to the authentication key, key ID, and developer team ID. By default, it connects to the sandbox environment. ```javascript var options = { token: { key: "path/to/APNsAuthKey_XXXXXXXXXX.p8", keyId: "key-id", teamId: "developer-team-id" }, production: false }; const apnProvider = new apn.Provider(options); ``` -------------------------------- ### Create Standard Notification Source: https://github.com/parse-community/node-apn/blob/master/README.md Create a notification object with standard parameters like expiry, badge, sound, alert, payload, and topic. ```javascript let note = new apn.Notification(); note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now. note.badge = 3; note.sound = "ping.aiff"; note.alert = "\uD83D\uDCE7 \u2709 You have a new message"; note.payload = {'messageFrom': 'John Appleseed'}; note.topic = ""; ``` -------------------------------- ### APNS Convenience Setters Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown Demonstrates the usage of convenience setters for alert, title, badge, and mutable content, along with chainable setters and direct APS property access in node-apn. ```javascript let notification = new apn.Notification(); /// Convenience setter notification.body = "Hello, world!"; notification.title = "node-apn"; notification.badge = 10; /// Chainable setter notification.setAction("npm install") .setMutableContent(1); /// Direct `aps` property access notification.aps.category = "nodejs"; ``` -------------------------------- ### Mocking apn.Client.write() Response Structures Source: https://github.com/parse-community/node-apn/blob/master/doc/testing.markdown Demonstrates the expected object structures for the Promise returned by apn.Client.write() to simulate different outcomes for notifications. ```javascript { device: device } ``` ```javascript { device: device, status: "410", // For implementation reasons, the status code must be a string, not a number response: { reason: "Unregistered" } } ``` ```javascript { device: device, error: new Error("some fake error") } ``` -------------------------------- ### Create Live Activity Notification Source: https://github.com/parse-community/node-apn/blob/master/README.md Create a notification object for Live Activities, including parameters like pushType, relevanceScore, timestamp, staleDate, event, and contentState. ```javascript let note = new apn.Notification(); note.topic = ".push-type.liveactivity"; note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now. note.pushType = "liveactivity", note.badge = 3; note.sound = "ping.aiff"; note.alert = "\uD83D\uDCE7 \u2709 You have a new message"; note.payload = {'messageFrom': 'John Appleseed'}; note.relevanceScore = 75, note.timestamp = Math.floor(Date.now() / 1000); // Current time note.staleDate = Math.floor(Date.now() / 1000) + (8 * 3600); // Expires 8 hour from now. note.event = "update" note.contentState = {} ``` -------------------------------- ### APN Provider Configuration Source: https://github.com/parse-community/node-apn/blob/master/doc/apn.markdown Creates a connection to APNS using the apn.Provider class, configured with credentials. It's recommended to reuse the Provider instance for optimal performance. ```javascript let provider = new apn.Provider({ token: { key: "path/to/key.pem", keyId: "key-id", teamId: "developer-team-id" }, production: false }); ``` -------------------------------- ### Create Channel Source: https://github.com/parse-community/node-apn/blob/master/README.md Use the manageChannels method with the 'create' action to create a new notification channel. This returns a promise. ```javascript try { const result = await apnProvider.manageChannels(note, bundleId, 'create'); // see the documentation for an explanation of the result } catch (error) { // Handle error... } ``` -------------------------------- ### APN Provider Methods Source: https://github.com/parse-community/node-apn/blob/master/doc/provider.markdown Documentation for the apn.Provider class methods: send, manageChannels, and broadcast. These methods handle sending notifications, managing broadcast channels, and broadcasting Live Activity notifications respectively. All methods return Promises that resolve with the status of each notification. ```APIDOC Provider: send(notification, recipients) - Sends notifications to specified recipients. - notification: A Notification object. - recipients: A String or Array of String containing hex-encoded device tokens. - Returns: A Promise that resolves after each notification reaches a final state. manageChannels(notification, bundleId, action) - Manages broadcast channels (create, read, readAll, delete). - notification: A Notification object or an Array of Notification objects. - bundleId: A String containing the bundle identifier for the application. - action: A String specifying the action ('create', 'read', 'readAll', 'delete'). - Returns: A Promise that resolves after each notification reaches a final state. broadcast(notification, bundleId) - Broadcasts Live Activity notifications. - notification: A Notification object or an Array of Notification objects. - bundleId: A String containing the bundle identifier for the application. - Returns: A Promise that resolves after each notification reaches a final state. ``` -------------------------------- ### Load Node APN Module Source: https://github.com/parse-community/node-apn/blob/master/README.md Loads the Node APN module into your JavaScript project. This makes the APN functionality available for use. ```javascript var apn = require('@parse/node-apn'); ``` -------------------------------- ### Connect using HTTP/2 Connection Pool Source: https://github.com/parse-community/node-apn/blob/master/README.md Creates a multi-provider instance to manage a pool of HTTP/2 connections, allowing for round-robin distribution of notifications. This can improve throughput and handle concurrent request limits. ```javascript var options = { // Round robin pool with 2 clients. More can be used if needed. clientCount: 2, token: { key: "path/to/APNsAuthKey_XXXXXXXXXX.p8", keyId: "key-id", teamId: "developer-team-id" }, proxy: { host: "192.168.10.92", port: 8080 }, production: false }; const apnProvider = new apn.MultiProvider(options); ``` -------------------------------- ### Connect to APN Provider via HTTP Proxy Source: https://github.com/parse-community/node-apn/blob/master/README.md Establishes a connection to the APN provider through an HTTP proxy. This is useful in environments where direct connections are not allowed. It requires the proxy host and port. ```javascript var options = { token: { key: "path/to/APNsAuthKey_XXXXXXXXXX.p8", keyId: "key-id", teamId: "developer-team-id" }, proxy: { host: "192.168.10.92", port: 8080 }, production: false }; const apnProvider = new apn.Provider(options); ``` -------------------------------- ### Constructing a Broadcast Notification Source: https://github.com/parse-community/node-apn/blob/master/README.md This snippet demonstrates how to create a new apn.Notification object and populate its properties for a broadcast push notification. Key properties like `channelId` are highlighted. ```javascript let note = new apn.Notification(); note.channelId = "dHN0LXNyY2gtY2hubA=="; // Required note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now. note.pushType = "liveactivity", note.badge = 3; note.sound = "ping.aiff"; note.alert = "\ud83d\udce7 \u2709 You have a new message"; note.payload = {'messageFrom': 'John Appleseed'}; note.relevanceScore = 75, note.timestamp = Math.floor(Date.now() / 1000); // Current time note.staleDate = Math.floor(Date.now() / 1000) + (8 * 3600); // Expires 8 hour from now. note.event = "update" note.contentState = {} ``` -------------------------------- ### apn.Client.write() Method Signature Source: https://github.com/parse-community/node-apn/blob/master/doc/testing.markdown Shows the signature of the private apn.Client.write method, which is called by apn.Provider.send() for each device token. ```javascript apn.Client.write(notification, device) ``` -------------------------------- ### Read All Channels Source: https://github.com/parse-community/node-apn/blob/master/README.md Use the manageChannels method with the 'readAll' action to retrieve all active channel IDs. This returns a promise. ```javascript try { const result = await apnProvider.manageChannels(note, bundleId, 'readAll'); // see the documentation for an explanation of the result } catch (error) { // Handle error... } ``` -------------------------------- ### APN Notification Fields Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown Documentation for key fields within an APN notification payload, including channelId, expiry, priority, and pushType. ```APIDOC notification.channelId: Description: The channel ID is a base64-encoded string that identifies the channel to publish the payload. The channel ID is generated by sending channel creation request to APNs. notification.expiry: Description: A UNIX timestamp when the notification should expire. If the notification cannot be delivered to the device, APNS will retry until it expires. An expiry of `0` indicates that the notification expires immediately, therefore no retries will be attempted. notification.priority: Description: Provide one of the following values: * `10` - The push notification is sent to the device immediately. (Default) > The push notification must trigger an alert, sound, or badge on the device. It is an error to use this priority for a push notification that contains only the `content-available` key. * `5` - The push message is sent at a time that conserves power on the device receiving it. notification.pushType: Description: (Required when delivering notifications to devices running iOS 13 and later, or watchOS 6 and later. Ignored on earlier system versions.) The type of the notification. The value of this header is `alert`, `background`, `pushtotalk`, or `liveactivity`. Specify `alert` when the delivery of your notification displays an alert, plays a sound, or badges your app's icon. Specify `background` for silent notifications that do not interact with the user. Specify `pushtotalk` for notifications that provide information about updates to your application’s push to talk services. Specify `liveactivity` for live activities. The value of this header must accurately reflect the contents of your notification's payload. If there is a mismatch, or if the header is missing on required systems, APNs may delay the delivery of the notification or drop it altogether. Reference: [pl]:https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html "Local and Push Notification Programming Guide: Apple Push Notification Service" ``` -------------------------------- ### Create Channel Notification Object Source: https://github.com/parse-community/node-apn/blob/master/README.md Create a notification object for channel management, including a requestId and payload with message-storage-policy and push-type. ```javascript let note = new apn.Notification(); note.requestId = "0309F412-AA57-46A8-9AC6-B5AECA8C4594"; // Optional note.payload = {'message-storage-policy': '1', 'push-type': 'liveactivity'}; // Required ``` -------------------------------- ### Sending a Broadcast Notification Source: https://github.com/parse-community/node-apn/blob/master/README.md This snippet shows how to send the constructed broadcast notification using the `broadcast` method of the `apnProvider`. It includes basic error handling. ```javascript try { const result = await apnProvider.broadcast(note, bundleId); // see documentation for an explanation of result } catch (error) { // Handle error... } ``` -------------------------------- ### APNS Notification Properties Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown Details essential properties for configuring APNS notifications, including topic, id, and collapseId, which are sent as configuration and not part of the payload. ```APIDOC notification.topic - Required: The destination topic for the notification. - Special cases: - For `pushtotalk` push type, append `.voip-ptt` to your app’s bundle ID. - For `liveactivity` push type, append `.push-type.liveactivity` to your app’s bundle ID. notification.id - A UUID to identify the notification with APNS. - If not supplied, APNS generates one automatically. - If an error occurs, the response will contain the `id`. - This property populates the `apns-id` header. notification.collapseId - Multiple notifications with the same collapse identifier are displayed as a single notification. - The value should not exceed 64 bytes. notification.requestId - An optional custom request identifier returned in the response. - The request identifier must be encoded as a UUID string. ``` -------------------------------- ### APN Provider Configuration Options Source: https://github.com/parse-community/node-apn/blob/master/doc/provider.markdown Configures the apn.Provider for sending Apple Push Notifications. Supports both certificate-based and token-based authentication with various connection and retry settings. ```APIDOC apn.Provider([options]) Options: token: {Object} Configuration for Provider Authentication Tokens. token.key: {Buffer|String} The filename of the provider token key, or the key data. token.keyId: {String} The ID of the key issued by Apple. token.teamId: {String} ID of the team associated with the provider token key. cert: {Buffer|String} The filename of the connection certificate, or the certificate data. (Defaults to: cert.pem) key: {Buffer|String} The filename of the connection key, or the key data. (Defaults to: key.pem) ca: Array of trusted certificates (filename, Buffer, or String). pfx: {Buffer|String} File path for PFX/PKCS12 data, or the PFX data itself. passphrase: {String} The passphrase for the connection key, if required. production: {Boolean} Connect to Production (true) or Sandbox (false) APNs server. (Defaults to NODE_ENV == "production") rejectUnauthorized: {Boolean} Reject Unauthorized property for tls.connect(). (Defaults to true) address: {String} The address of the APNs server. (Defaults to standard APNs server) port: {Number} The port of the APNs server. (Defaults to 443) manageChannelsAddress: {String} The address of the APNs channel management server. manageChannelsPort: {Number} The port of the APNs channel management server. proxy: {host: String, port: Number|String} HTTP proxy for sending notifications. manageChannelsProxy: {host: String, port: Number|String} HTTP proxy for managing channels. connectionRetryLimit: {Number} Maximum connection failures before giving up. (Defaults to 3) heartBeat: {Number} Delay interval in ms for pinging APNs servers. (Defaults to 60000) requestTimeout: {Number} Maximum time in ms to wait for a response. (Defaults to 5000) ``` -------------------------------- ### Send Live Activity Notification Source: https://github.com/parse-community/node-apn/blob/master/README.md Send a Live Activity notification using the apnProvider's send method. This is an asynchronous operation. ```javascript try { const result = await apnProvider.send(note, deviceToken); // see the documentation for an explanation of the result } catch (error) { // Handle error... } ``` -------------------------------- ### Send Standard Notification Source: https://github.com/parse-community/node-apn/blob/master/README.md Send a notification using the apnProvider's send method, which returns a promise. Handle potential errors. ```javascript try { const result = apnProvider.send(note, deviceToken); // see documentation for an explanation of result } catch(error) { // Handle error... } ``` -------------------------------- ### Handling Unicode in Notifications Source: https://github.com/parse-community/node-apn/blob/master/doc/provider.markdown Guidance on sending notifications with Unicode characters, such as emoji. Ensures correct UTF-8 encoding for transmission to Apple. ```javascript // Ensure strings with multi-byte characters are valid UTF-8. // Example: const notification = { aps: { alert: "Hello 👋 World!" } }; // node-apn will transmit this in UTF-8. ``` -------------------------------- ### APN Provider Results Source: https://github.com/parse-community/node-apn/blob/master/doc/provider.markdown Details on the results returned by apn.Provider methods. Promises resolve to an object with 'sent' and 'failed' arrays, detailing the status of each notification. ```APIDOC Results from APN Provider Methods: - Each notification can be in one of three states: 'sent', 'failed' (rejected), or 'failed' (error). - The resolved Promise value is an Object with two properties: - sent: An array of device tokens or bundle identifiers successfully sent. - failed: An array of objects for each failed token or bundle identifier. - For rejected notifications: { device: "", status: , response: { reason: "" } } - For error notifications: { device: "", error: Error // An Error object containing details about the failure. } ``` -------------------------------- ### APN Notification Payload Source: https://github.com/parse-community/node-apn/blob/master/doc/apn.markdown Constructs a push notification payload using the apn.Notification class, setting properties like alert message, badge count, and topic. ```javascript let notification = new apn.Notification(); notification.alert = "Hello, world!"; notification.badge = 1; notification.topic = "io.github.node-apn.test-app"; ``` -------------------------------- ### Set Raw Notification Payload Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown Illustrates the use of `notification.rawPayload`. When `rawPayload` is set, it is encoded and transmitted directly, overriding any effects from convenience setters. ```javascript let notification = new apn.Notification(); notification.rawPayload = { from: "node-apn", source: "web", aps: { "content-available": 1 } }; notification.body = "Hello, world!"; ``` ```json { "from":"node-apn", "source":"web", "aps":{ "content-available":1 } } ``` -------------------------------- ### Set Notification Payload Source: https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown Shows how to set a custom payload for an apn.Notification. Convenience setters like `notification.body` will merge their content into the `aps` property of the payload. If the payload already has an `aps` property, it will be replaced. ```javascript let notification = new apn.Notification(); notification.payload = { from: "node-apn", source: "web", }; notification.body = "Hello, world!"; ``` ```json { "from":"node-apn", "source":"web", "aps":{ "alert":"Hello, world!" } } ``` -------------------------------- ### Sending APN Notification Source: https://github.com/parse-community/node-apn/blob/master/doc/apn.markdown Sends a notification to a list of device tokens using the provider. The send method returns a Promise that resolves with the transmission results, including successful sends and failures. ```javascript provider.send(notification, deviceTokens).then( (response) => { // response.sent: Array of device tokens to which the notification was sent successfully // response.failed: Array of objects containing the device token (`device`) and either an `error`, or a `status` and `response` from the API }); ``` -------------------------------- ### APN Device Tokens Source: https://github.com/parse-community/node-apn/blob/master/doc/apn.markdown Defines an array of device tokens, which are hex-encoded strings, to which notifications will be sent. ```javascript let deviceTokens = ["834c8b48e6254e47435d74720b1d4a13e3e57d0bf318333c284c1db8ce8ddc58"]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.