Adding App Insights to An Aurelia App

I just finished watching some videos from Build 2015 on Channel 9. One of the topics that intrigued me was App Insights. Here I could easily add telemetry for applications in the wild and have it stored out in the cloud. Splunk Cloud gives you much the same thing without the nice UI that Azure provides, but the ease at which you could instrument an application was notable. Best of all, App Insights is free unless you have a large application or want streaming results.

To start, you need to have an Azure Subscription. You can get those for free as well. I use a Pay-as-you-go subscription so I’m only paying for what I use.

Step 1 – Create an App Insights Resource

Log in to with your Azure credentials and click on the shiny + New button in the top left corner.


Click on Application Insights. Enter a name for your project. I generally use the project name (so in this case, it’s aurelia-2).


Click on Configure required settings. In the Application Type, click on ASP.NET web application.


Finally, click on Create. The Azure backend will go off and create the resource for you. It should open automatically when it’s done. If not, you can always open it yourself (use the Browse All button). This is what the screen looks like:


I haven’t sent any data to it, nor have I configured the aurelia-2 application yet, so this is to be expected. Note the circled cloud type icon. Clicking on that will open up a Quickstart guide. One of those guides is to Add code to monitor web pages.

Unfortunately, because Aurelia is a single page application, this code won’t work for me. However, I can place this code in my router to effect the same information.

Step 2 – Update the Aurelia Router

Handling Aurelia applications is difficult because Aurelia uses the location hash (that is, the bit after # in the URL) as a routing indicator. This bit is ignored by App Insights so I have to code around it. Let’s start in app.ts adding a new class called AppInsights:

class AppInsights {
    private server: any;

    constructor() {
        // Copy lines 9-15 from the App Insights QuickStart to here
        this.server = window.appInsights || function (config) {
            function s(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, r = document, f = window, e = "script", o = r.createElement(e), i, u; for (o.src = config.url || "//", r.getElementsByTagName(e)[0].parentNode.appendChild(o), t.cookie = r.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace"]; i.length;)s("track" + i.pop()); return config.disableExceptionTracking || (i = "onerror", s("_" + i), u = f[i], f[i] = function (config, r, f, e, o) { var s = u && u(config, r, f, e, o); return s !== !0 && t["_" + i](config, r, f, e, o), s }), t
        } ({
            instrumentationKey: "{{INSTRUMENTKEY}}"
        window.appInsights = this.server;

    run(routingContext, next) {
        return next();

This code is cut and paste from the Quickstart guide on the Azure Portal, with one exception. Instead of storing the variable within an appInsights variable, I’ve stored it in a private server variable. I’ve also assigned the same code to the window.appInsights variable just in case, but that strictly isn’t necessary since the pipeline is only created once. Don’t forget to include your instrument key in this code. Mine is checked in without an instrument key.

I also need to add the class to the modelbind pipeline:

    configureRouter(config, router) {
        config.title = 'Aurelia';

        config.addPipelineStep('authorize', AuthorizeStep);
        config.addPipelineStep('modelbind', AppInsights);[

Just like the authorization class, Aurelia calls the run() method with a routing context. I’ve just dumped everything out to the console for now so we can take a look at the objects. Run this project to see what you get.

Click around and watch the console. You will always see something after the #. I can also take a look at the routingContext.nextInstruction.moduleId to see what page is being loaded. The best idea, however, may be just to remove the # (correcting for double-slashes) and then send that to the App Insights Service. My run() method is changed to this:

    run(routingContext, next) {
        var origin = window.location.pathname + window.location.hash;
        var path = origin.replace("/#/", "/").replace("#", "");
        console.log("[AppInsights] Tracking for %s", path);
        return next();

You can find early details of the App Insights Javascript API in the MSDN forums.

If you run the project now and click around, you’ll generate some data. Go over to the Azure Portal and you will see one chart is filled in. The interesting data, however, is in the Users, Sessions and Page views boxes. Note you can check out which pages have been used the most. They will appear without the # in them.

Wrapping Up

There are other things you can do. You could add App Insights Telemetry to your ASP.NET API, time the flickr API response and log that as a metric, or store the user that is actually logging in so that user usage is tracked properly. Really, it depends on what you want to see. However, this is a free method of getting usage statistics for your single-page Aurelia application.

As always, my code is on GitHub.