• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Apple Push Notification Backend In NodeJS

Apple Push Notification Backend In NodeJS

March 16, 2015 by Rana Ahsan 11 Comments

apn backend

Node.JS is a nice technology for building high-performance and efficient backend applications. Thus it is also a very popular technology to be used as a mobile application’s backend server, where performance impacts user engagement highly. For a mobile application, push notification is a highly important aspect. Implementing push notifications includes both iOS and server-side implementation efforts. Today, in this tutorial, I will try to show how we can have the apple push notification backend server implementation set up and running in a while very easily.

The Workflow Architecture:

To implement the back end, it’s essential that we do understand how the push notification functionality actually works behind the scene. Let’s see the architecture, and I will describe the workflow steps below:

Push Notification Service
  1. iOS App Device Token: each iOS app has a unique device token for the user. If an application needs to implement push notifications, it must have this device token. Thus your iOS app needs to send the token to the server.
  2. Store the device token: After an app sends the token to the server via our backend REST API, we need to store it to use later for sending push notifications to this user specifically
  3. Event Trigger: When some certain interesting event occurs, we need to send a message to our back-end worker(preferably via the message queue system) that contains the main functionality for sending the push notification.
  4. Retrieve Device token: The back-end worker needs to retrieve the device token for the specified user to send the push notification accordingly.
  5. Sending Push Notification: The backend worker will now use the device token and use apple’s push notification API to make an API call to apple’s push notification server.
  6. Bingo!: The push notification will pop up on the corresponding iOS device.

As part of the workflow, step 5 includes the main server-side implementations specific to sending a push notification, and I will discuss that part only. Other parts, like saving/retrieving device tokens etc, I am leaving them up to you.

Implementation With The APN library for NodeJS:

There is a very nice wrapper library for APN in NodeJS named ‘apn’. This will give you a very easy-to-understand API interface to interact with. Here is a simple code snippet that will give you a brief idea of start using this:

<pre>
var apn  = require("apn")

var apnError = function(err){
    console.log("APN Error:", err);
}

var options = {
    "cert": "cert.pem",
    "key":  "key.pem",
    "passphrase": null,
    "gateway": "gateway.sandbox.push.apple.com",
    "port": 2195,
    "enhanced": true,
    "cacheLength": 5
  };
options.errorCallback = apnError;

var feedBackOptions = {
    "batchFeedback": true,
    "interval": 300
};

var apnConnection, feedback;

module.exports = {
    init : function(){
        apnConnection = new apn.Connection(options);

        feedback = new apn.Feedback(feedBackOptions);
        feedback.on("feedback", function(devices) {
            devices.forEach(function(item) {
                //TODO Do something with item.device and item.time;
            });
        });
    },

    send : function (params){
        var myDevice, note;
        
        myDevice = new apn.Device(params.token);
        note = new apn.Notification();

        note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
        note.badge = 1;
        note.sound = "ping.aiff";
        note.alert = params.message;
        note.payload = {'messageFrom': params.from};

        if(apnConnection) {
            apnConnection.pushNotification(note, myDevice);
        }
    }
}

/*usage
pushNotifier = require("./pushNotifier");
pushNotifier.init();
//use valid device token to get it working 
pushNotifier.process({token:'', message:'Test message', from: 'sender'});
*/
</pre>Code language: JavaScript (javascript)

Let’s know about the different components in brief:

  • Certificate Files: We will need a valid certificate pair from apple to get this working properly. If you have a .p12 file, you can convert it to the expected .pem format using these instructions. If you have no idea, start with the official apple site for push certificates
  • Error Handler: You need to pass an error handler if something bad happens. You can use convenient logging of the errors there.
  • Feedback Handler: The feedback handler is attached and used to handle failed notifications. You may want to resend or log/keep track of them for future use.
  • Notification Settings: It includes various settings to configure how apple interprets your notification. To know more details about them, check the tables 3.1 and 3.2 on apple’s official documentation here.

However, there is possibly an issue with this library. The certificate and key files are required to be put in the root directory. If you place them somewhere else and try to add the paths in the ‘options,’ you might get an error. Most probably, the issue is related to this GitHub ticket.

Final Words:

I am not an iOS developer and thus tried to keep the scope of this apple push notification backend tutorial specific to server-side implementation only. If you don’t understand the part described/shown above, feel free to ask me via commenting below. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: javascript, nodejs

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. MESHAL says

    October 1, 2015 at 12:53 am

    thanks for this is tutorial

    i do that on server but i have problem

    node_modules/apns/lib/file-loader.js:43
    if (err) throw err;
    ^
    Error: ENOENT, open ‘./apns/pushcert.pem’
    at Error (native)

    Reply
    • MESHAL says

      October 1, 2015 at 1:25 am

      i just slove it thanks

      Reply
      • Md Ali Ahsan Rana says

        October 8, 2015 at 8:21 pm

        Cool! Happy to hear that you got it solved.

        Reply
      • Edward says

        June 8, 2016 at 10:05 am

        How did you solve this? I’m getting the same error…

        Reply
    • Upendra says

      June 22, 2016 at 7:14 am

      Hi,Could you please tell me How can we confirm,whether the notification sent or not
      after this statement

      apnConnection.pushNotification(note, myDevice);

      Reply
  2. edurivaraEdu says

    October 14, 2015 at 2:21 pm

    Usage is:
    pushNotifier.send instead of pushNotifier.process as it says in the example, right?

    Reply
  3. varun says

    January 11, 2016 at 7:04 am

    I understood how APNS works and i am able to send pushnotification through APNS. I want to create a web app/web site. In that i will type the notification and click send. How to achieve this using node.js

    Reply
  4. Hema Bahirwani says

    August 22, 2016 at 9:18 am

    Hello, I would like to know how do we handle the notifications received. For instance, you click on the push notification received, it will take you to the application that includes the push notification feature. i wanna know how do i fetch the details of the notification received and push into an array.

    Reply
  5. sirajudden says

    March 21, 2017 at 1:49 am

    I got the below error..

    apnConnection = new apn.Connection(options);
    ^

    TypeError: apn.Connection is not a constructor
    at Object.init (/Users/Iexemplar/Documents/nodews/newpush/pushNotifier.js:28:25)
    at Object. (/Users/Iexemplar/Documents/nodews/newpush/server.js:3:14)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.runMain (module.js:607:10)
    at run (bootstrap_node.js:420:7)
    at startup (bootstrap_node.js:139:9)

    Reply
  6. azaz says

    August 4, 2017 at 12:43 am

    Hi,

    i want to send personalized push notification for each user, how can we do that ?

    Reply
  7. Adolfo says

    December 11, 2018 at 4:17 pm

    same error

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023