Client for connecting to Apple's Push Notification Service using the new HTTP/2 protocol with JSON web tokens.
This is a fork of the original apns2 package with support for Cloudflare Workers. The original package has multiple dependencies that are incompatible with the Cloudflare Workers runtime. This fork removes those dependencies and replaces them with native Cloudflare Workers APIs.
This package is not compatible with Node.js, and does not depend on the nodejs_compat
flag.
Create an APNS client using a signing key:
import { ApnsClient } from '@fivesheepco/cloudflare-apns2'
const client = new ApnsClient({
team: 'TFLP87PW54',
keyId: '123ABC456',
signingKey: '-----BEGIN PRIVATE KEY-----\nMIGTAg...\n-----END PRIVATE KEY-----',
defaultTopic: 'com.tablelist.Tablelist',
})
Send a basic notification with message:
import { Notification } from '@fivesheepco/cloudflare-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 '@fivesheepco/cloudflare-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)
}
Send a silent notification using content-available
key:
import { SilentNotification } from '@fivesheepco/cloudflare-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.
Send multiple notifications concurrently:
import { Notification } from '@fivesheepco/cloudflare-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)
}
For complete control over the push notification packet use the base Notification
class:
import { Notification } from '@fivesheepco/cloudflare-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
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'
...
})
@fivesheepco/cloudflare-apns2
requires Node.js v20 or later