Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

apns2

AndrewBarba26.8kMIT12.1.0TypeScript support: included

Node client for connecting to Apple's Push Notification Service using the new HTTP/2 protocol with JSON web tokens.

apn, apns, apns2, push, notification, http2, jwt, apple, ios, macos, tvos, watchos

readme

apns2

npm version Twitter

Node client for connecting to Apple's Push Notification Service using the new HTTP/2 protocol with JSON web tokens.


Create Client

Create an APNS client using a signing key:

import { ApnsClient } from 'apns2'

const client = new ApnsClient({
  team: `TFLP87PW54`,
  keyId: `123ABC456`,
  signingKey: fs.readFileSync(`${__dirname}/path/to/auth.p8`),
  defaultTopic: `com.tablelist.Tablelist`,
  requestTimeout: 0, // optional, Default: 0 (without timeout)
  keepAlive: true, // optional, Default: 5000
})

Sending Notifications

Basic

Send a basic notification with message:

import { Notification } from 'apns2'

const bn = new Notification(deviceToken, { alert: 'Hello, World' })

try {
  await client.send(bn)
} catch (err) {
  console.error(err.reason)
}

Send a basic notification with message and options:

import { Notification } from 'apns2'

const bn = new Notification(deviceToken, {
  alert: 'Hello, World',
  badge: 4,
  data: {
    userId: user.getUserId
  }
})

try {
  await client.send(bn)
} catch (err) {
  console.error(err.reason)
}

Silent

Send a silent notification using content-available key:

import { SilentNotification } from 'apns2'

const sn = new SilentNotification(deviceToken)

try {
  await client.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.

Many

Send multiple notifications concurrently:

import { Notification } from 'apns2'

const notifications = [
  new Notification(deviceToken1, { alert: 'Hello, World' }),
  new Notification(deviceToken2, { alert: 'Hello, World' })
]

try {
  await client.sendMany(notifications)
} catch (err) {
  console.error(err.reason)
}

Advanced

For complete control over the push notification packet use the base Notification class:

import { Notification } from 'apns2'

const notification = new Notification(deviceToken, {
  aps: { ... }
})

try {
  await client.send(notification)
} catch(err) {
  console.error(err.reason)
}

Available options can be found at APNS Payload Options

Error Handling

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 error
client.on(Errors.badDeviceToken, (err) => {
  // Handle accordingly...
  // Perhaps delete token from your database
  console.error(err.reason, err.statusCode, err.notification.deviceToken)
})

// Listen for any error
client.on(Errors.error, (err) => {
  console.error(err.reason, err.statusCode, err.notification.deviceToken)
})

Environments

By default the APNS client connects to the production push notification server. This is identical to passing in the options:

const client = new ApnsClient({
  host: 'api.push.apple.com'
  ...
})

To connect to the development push notification server, pass the options:

const client = new ApnsClient({
  host: 'api.sandbox.push.apple.com'
  ...
})

Requirements

apns2 requires Node.js v16 or later

changelog

Change Log

apns2 follows Semantic Versioning


12.1.0

  1. Add back commonjs support

12.0.0

  1. Migrate to Undici v7
  2. ESM
  3. Drop support for Node 16 and 18

11.7.1

  1. Fix issue with expiration option #88

11.7.0

  1. Update fast-jwt to v4

11.6.0

  1. Fix issue with contentAvailable
  2. Add support for mutableContent

11.5.0

  1. Add ApnsClient.keepAlive
  2. Deprecate ApnsClient.pingInterval

11.4.0

  1. Add location push type
  2. Add pushtotalk push type

11.3.0

  1. Add Priority.low
  2. Fix options requestTimeout and pingInterval
  3. Convert to Biome

11.2.0

  1. Define new Host enum for specifying APNS host
  2. Add liveactivity push type

Thank you 278204 and icodebuster

11.1.0

  1. Accept all options when sending a silent notification

11.0.1

  1. Add back support for Node.js 16.x

11.0.0

  1. Built for Node.js 18
  2. Drops support for all versions of Node <18

10.1.0

  1. Add support for alert subtitle

10.0.1

  1. Re-written in TypeScript
  2. Adjust distribution files
  3. Only allow data options in SilentNotification constructor

10.0.0

  1. Re-written in TypeScript

9.3.0

  1. Update token refresh logic to avoid TooManyProviderTokenUpdates

9.2.0

  1. Allow disabling pingInterval
  2. Fix issue with missing ping callback

9.1.0

  1. Correctly handle socket error events
  2. Lazily connect on first request
  3. Keeps socket alive with ping request every 60s

9.0.0

  1. Full code cleanup
  2. Removes tarn
  3. Requires Node v12 or newer
  4. Rename destroy() to close()

8.5.0

  1. Fix TypeScript typings
  2. New push types and error constants
  3. Add prettier

8.4.0

  1. Add client.destroy() to kill all outstanding connections to apns servers.
  2. Upgrade tarn to v3

8.3.0

  1. Add voip support

8.2.0

  1. Add correct TypeScript definitions for NotificationOptions

8.1.0

  1. Add missing TypeScript interface for NotificationOptions
  2. Remove lodash dependency

8.0.0

  1. Require Node.js v10 or higher

7.0.0

  1. Support apns-push-type and iOS 13

6.1.0

  1. Support thread-id

6.0.0

  1. Remove Bluebird
  2. Remove concurrency option, instead relies on the connection pool and max connections
  3. Accept a Date for the apns expiration

5.0.0

  1. Update code to use async/await

4.0.4

  1. Fix connection pool not releasing resources

4.0.3

  1. Listen for error event when connecting an http2 session

4.0.2

  1. Reset signing token every 59 minutes to prevent TooManyProviderTokenUpdates error

4.0.1

  1. Updated Typescript definitions for v4.0

4.0.0

  1. Remove support for Node versions less than v8.10
  2. High-performance connection pool using tarn
  3. More friendly require API, see README for updated usage

3.0.1

  1. Fix Typescript definitions

3.0.0

  1. Introduces support for the native http2 module in Node.js v8.4.0 or later with fall back to node-spdy in earlier versions of Node.js.

To use the new http2 library you must start your node process with node --expose-http2 and apns2 will automatically use the native module. Later versions of Node.js may expose the native module without the need for a command line flag. In this case, apns2 will automatically use the native module without any additional steps on your end.