Making Application Insights Fast & Secure

What is Application Insights?

It’s an application monitoring tool available on Microsoft’s Azure cloud that you can use to detect errors and usage in your application. For ASP.NET Core apps, it can do this for both your C# and JavaScript code. It’s main competitors are New Relic and RayGun.

Implementing Application Insights

Following the Getting Started guide for ASP.NET Core applications requires you to add the following HTML helper to your _Layout.cshtml file:

This HTML helper adds an inline script containing the minified JavaScript in snippet.js.

This script is responsible for:

  1. Containing the users instrumentation key (The HTML helper adds this for you).
  2. Downloading the full application insights script asynchronously which actually does all the work.
  3. Recording any logs that occur while the full script is downloaded

The Problem

For most websites, this is fine and you can stop here. Here is what can be improved for the rest:

  1. The above adds 1KB to every HTML page. Moving this script into a separate file would mean that this script could be cached in the browser the first time it was downloaded. A separate file could also be dirstributed to a CDN and globally distributed very quickly.
  2. If you are using a Content Security Policy (CSP) to secure your site using inline scripts in your site is a big no no. You could use a nonce (A nonce means you can’t cache the page as each page becomes unique) or even better a hash of the script contents but browser support for CSP 2.0 is not great. Using an external script would be the simplest option.

Making It Slightly Faster and More Secure

So what does it take to move the above snippet.js file into a separate file? Well, it turns out that you can get snippet.js from the applicationinsights-js NPM package which you can add to your package.json like so:

The next step is to inject your instrumentation key into snippet.js and also the URL to the full application insights script which is missing from the snippet.js file in the NPM package. I do this using a gulp task like so:

Finally we can include the script in our HTML. Don’t forget to include the cross0rigin attribute on all your script tags, which allows full stack traces to be reported. You can read more about the crossorigin attribute here.

Conclusion

As usual, all of the above is built in to the ASP.NET MVC Boilerplate project template, available as a Visual Studio extension if you select the optional Application Insights feature.