Push Notifications Tutorial: Node.js and Azure Setup

by | Sep 30, 2015

One major step in the development of our multi-platform Time Entry app was push notifications. We wanted to be notified when an action was taken or needed. This took coordination among those working on the project but in the end we ended up with push notifications on our Android, iOS, and Windows apps with a central Azure Notifications hub. This push notifications tutorial series will walk through each platform as well as the setup of Node.js and Azure.

To follow along with this tutorial, check out this GitHub repository.

What is a push notification?

Push notifications are the standard way in the mobile universe to actively send information to a mobile application. Push notifications on all of the three major platforms work in a similar manner. There are three systems involved in sending a push notification.

  1. The mobile phone maintains an active connection to its vendor’s push servers.
  2. A custom application talks to the vendor’s servers, not directly to the phone.
  3. The vendor server acts as an intermediary for all push notifications and sends them down to the phone via the active connection.

How does Azure help us with this?

Azure Notification Hubs act as a proxy between our application and each vendor’s specific implementation of their notification server. Providing a common interface so our application doesn’t have to think about if the mobile application is running on Android or iOS or Windows Phone.

Azure Setup

Create Notification Hub

The first thing we need to do is create a notification hub. To do that head over to the azure dashboard at https://learn.microsoft.com/en-us/azure/notification-hubs/create-notification-hub-portal and Create a namespace and a notification hub

Head to the NOTIFICATION HUBS tab and create a new notification hub

Next head over to the configuration tab and setup the settings that apply to the platform or platforms to which you wish to send notifications. You can get these settings from each provider.

  1. Get Connection String by clicking on CONNECTION INFORMATION, copy out the Full Shared Access string as we will need it later to connect with our application.
    ConnectionString

Node Application

Now that we have Azure setup and ready to use let’s walk through what it takes to talk to it with a simple node application.

Project Creation

  1. Initialize the node project and create a package.json file.
    $ npm init
  2. Install the single node package we will need for this project called azure and save it to the package.json.
    $ npm i -S azure

Device Registration

As a prerequisite to doing this, you need to have an application installed on your iOS device that has been setup to allow push notifications to be received.  For more information on how to do that with iOS that please stay tuned to this blog series.  For now I will assume that you have an app ready to go.

Every device needs to register itself for one or more notifications out of our system. These notifications are specified by tags. Examples of tags can be either a unique idenifier for the user (username for example). Or they can be something more generic like "MyFavoriteSportsTeam". In this case everyone registered for that tag will get a broadcast when their favorite team wins.

  1. Create a file called register.js and create the basic 2 lines of code we need to connect to our notification hub.
    var azure = require('azure');
    var notificationHubService = azure.createNotificationHubService('demo-hub', 'Endpoint=...');
  2. Now is the important line of code that registers a device with Azure so it knows about the device. In this example we will register an iOS device using Apple Push Notification Service (APNS).
    notificationHubService.apns.createTemplateRegistration(
     'deviceToken',
     'tag', {
         'aps': {
             'alert': '$(message)',
             'badge': '#(count)',
             'sound': 'default'
         }
     },
     function (e, r) {
         if (e) {
             console.log(e);
         } else {
             console.log({
                 id: r.RegistrationId,
                 deviceToken: r.DeviceToken,
                 expires: r.ExpirationTime
             });
         }
     }
    );

    There are 4 parameters taken by apns.createTemplateRegistration.

    1. The first is the device token that will be provided by the iOS application itself when it asks the user permission to send notifications.
    2. The second is the tag to use to identify this registration.  Here we just used the simple string of ‘tag’.  You might use a username for example.
    3. The third is the template for this specific notification type. In this case I have used an APNS notification type with two variables in it, one of the message and another for the iOS badge count, we will use these variables later when we send a notification.  Templates are were the power of Azure’s system come in.  They allow us to send a generic message type and taylor it to the specific format that the platform needs (APNS, GCM, Windows, etc.)
    4. The fourth is the callback to handle success/failure of the registration. Here I am simply logging to the console.

The final file looks like this:

var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('demo-hub', 'Endpoint=...');
 
notificationHubService.apns.createTemplateRegistration(
    'deviceToken',
    'tag', {
        'aps': {
            'alert': '$(message)',
            'badge': '#(count)',
            'sound': 'default'
        }
    },
    function (e, r) {
        if (e) {
            console.log(e);
        } else {
            console.log({
                id: r.RegistrationId,
                deviceToken: r.DeviceToken,
                expires: r.ExpirationTime
            });
        }
    }
);

Replace the hub name, connection string, device token to your values.

Execute this program to register your device

$ node register

Output should look something like this:

{
  id: '3...-1',
  deviceToken: '1CD...',
  expires: '2015-12-22T20:02:09.939Z'
}

That’s it! Your device is registered with Azure and ready to use.

Send a notification

Now that we’ve successfully registered a device let’s send it a push notification.

Create a new file called send.js:

var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('demo-hub', 'Endpoint=...');
 
var notification = {
    'message': 'hello from node!', // message to display in notification 
    'count': 0 // set badge iOS badge to this value 
};
 
var responseHandler = (function (n) {
    return function (e, r) {
        if (e) {
            console.log(e);
            return;
        } else {
            console.log(r.statusCode, n);
        }
    };
})(notification);
 
notificationHubService.send('tag', notification, responseHandler);

Let’s break down this file

  • The top 2 lines should be familiar, same as in register.js, that gives us a connection to azure itself.
  • Next we define a notification object. Notice that this object lines up directly with the template that we defined when we registered. It has a message and a count. These will be replaced in the template before the message is pushed to the device.
  • Now we have a response handler. This simply logs the response to the console. Expect to do something more interesting here in a real application.
  • notificationHubService.send is where things actually happen. Three parameters, the tag (or who to send it to), the notification itself and the response handler.

Save and run the file:

$ node send

That’s it! You should see a notification on your device!

Summary

In this first article in our push notifications tutorial series we went over how to setup an Azure Notification Hub and quickly talk to it from a node application to send a message to an iOS device.