Node client for connecting to Apple's Push Notification Service using the new HTTP/2 protocol with JSON web tokens.
Create an APNS client using a signing key:
import{ApnsClient}from'apns2'constclient=newApnsClient({team: `TFLP87PW54`,keyId: `123ABC456`,signingKey: fs.readFileSync(`${__dirname}/path/to/auth.p8`),defaultTopic: `com.tablelist.Tablelist`,requestTimeout: 0,// optional, Default: 0 (without timeout)pingInterval: 5000,// optional, Default: 5000})Send a basic notification with message:
import{Notification}from'apns2'constbn=newNotification(deviceToken,{alert: 'Hello, World'})try{awaitclient.send(bn)}catch(err){console.error(err.reason)}Send a basic notification with message and options:
import{Notification}from'apns2'constbn=newNotification(deviceToken,{alert: 'Hello, World',badge: 4,data: {userId: user.getUserId}})try{awaitclient.send(bn)}catch(err){console.error(err.reason)}Send a silent notification using content-available key:
import{SilentNotification}from'apns2'constsn=newSilentNotification(deviceToken)try{awaitclient.send(sn)}catch(err){console.error(err.reason)}Note: Apple recommends that no options other than the content-available flag be sent in order for a notification to truly be silent and wake up your app in the background. Therefore this class does not accept any additional options in the constructor.
Send multiple notifications concurrently:
import{Notification}from'apns2'constnotifications=[newNotification(deviceToken1,{alert: 'Hello, World'}),newNotification(deviceToken2,{alert: 'Hello, World'})]try{awaitclient.sendMany(notifications)}catch(err){console.error(err.reason)}For complete control over the push notification packet use the base Notification class:
import{Notification}from'apns2'constnotification=newNotification(deviceToken,{aps: { ... }})try{awaitclient.send(notification)}catch(err){console.error(err.reason)}Available options can be found at APNS Payload Options
All errors are defined in ./lib/errors.js and come directly from APNS Table 4
You can easily listen for these errors by attaching an error handler to the APNS client:
import{Errors}from'apns2'// Listen for a specific errorclient.on(Errors.badDeviceToken,(err)=>{// Handle accordingly...// Perhaps delete token from your databaseconsole.error(err.reason,err.statusCode,err.notification.deviceToken)})// Listen for any errorclient.on(Errors.error,(err)=>{console.error(err.reason,err.statusCode,err.notification.deviceToken)})By default the APNS client connects to the production push notification server. This is identical to passing in the options:
constclient=newApnsClient({host: 'api.push.apple.com'...})To connect to the development push notification server, pass the options:
constclient=newApnsClient({host: 'api.sandbox.push.apple.com'...})apns2 requires Node.js v16 or later