Using TypeScript/Node to Send Push Notifications to iOS

by 

| September 13, 2023 | in

Sending push notifications is a common feature to add when building mobile applications. A push notification is a message sent from a backend server to your application running on an iPhone or iPad. One of the cool things about push notifications is that they will be handled by the phone even if your application is not running.

Push notification functionality is one of the common reasons we build native applications instead of web applications. In the future, Apple will allow push notifications to web applications, but as of right now, this is a feature that “pushes” us to build native applications.

Sending a push notification to an iOS device is pretty easy. First, we will install the node module apn.

npm I apn

Then, we need to write some code to send the push notification. The code is below.

Most of the code is pretty straightforward, but I want to point out two things. First is the key. You will need to download the key from your Apple developer account. I recommend the key file instead of the certificate method.

Second, be aware of the mode your application is in. It can be in “sandbox” or “production”. If it is in sandbox mode, only messages listed with production equal to “false” will make it to the device. If the application is in production mode, all push notifications listed as production will make it to the device. This detail is very important, and it’s easy to mess up. An easy way to think about it is this: builds from Xcode are in sandbox mode and builds pushed to the app store are in production mode.

You can see a project with all of this set up here: https://github.com/chadmichel/ApplePush/blob/main/index.ts

author avatar
Chad Michel Senior Software Architect
Chad is a lifelong Nebraskan. He grew up in rural Nebraska and now lives in Lincoln. Chad and his wife have a son and daughter.

Related posts