---
title: "Making Application Insights Fast & Secure - Muhammad Rehan Saeed"
description: "Implementing Application Insights into your ASP.NET Core application with performance and security as a top priority in this advanced scenario."
canonical_url: "https://rehansaeed.com/making-application-insights-fast-and-secure/"
last_updated: "2016-12-11T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: ".NET,Application Insights,ASP.NET Core,ASP.NET MVC,ASP.NET Core Boilerplate,C#,Content Security Policy"
  "og:description": "Implementing Application Insights into your ASP.NET Core application with performance and security as a top priority in this advanced scenario."
  "og:image": "https://rehansaeed.com/_og/s/o_a03d0a32357d4db2.png"
  "og:image:alt": "Making Application Insights Fast & Secure - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Making Application Insights Fast & Secure"
  "twitter:image": "https://rehansaeed.com/_og/s/o_a03d0a32357d4db2.png"
  "twitter:image:alt": "Making Application Insights Fast & Secure - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [Making Application Insights Fast & Secure](https://rehansaeed.com/making-application-insights-fast-and-secure/)

Posted 11 December 2016 - **4 min read**

![Application Insights](https://rehansaeed.com/_ipx/f_png&s_2560x1440/images/hero/Application-Insights-1366x768.png)

# What is Application Insights? Link to this section

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](https://newrelic.com/) and [RayGun](https://raygun.com/).

# Implementing Application Insights Link to this section

Following the [Getting Started](https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Getting-Started) guide for ASP.NET Core applications requires you to add the following HTML helper to your `_Layout.cshtml` file:

```html
<head>
    @* ...Omitted *@

    @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) 
</head>
```

This HTML helper adds an inline script containing the minified JavaScript in [snippet.js](https://github.com/Microsoft/ApplicationInsights-JS/blob/master/JavaScript/JavaScriptSDK/snippet.js).

```html
<script type="text/javascript">
    var appInsights=window.appInsights||function(config){{
        function i(config){{t[config]=function(){{var i=arguments;t.queue.push(function(){{t[config].apply(t,i)}})}}}}var t={{config:config}},u=document,e=window,o="script",s="AuthenticatedUserContext",h="start",c="stop",l="Track",a=l+"Event",v=l+"Page",y=u.createElement(o),r,f;y.src=config.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{{t.cookie=u.cookie}}catch(p){{}}for(t.queue=[],t.version="1.0",r=["Event","Exception","Metric","PageView","Trace","Dependency"];r.length;)i("track"+r.pop());return i("set"+s),i("clear"+s),i(h+a),i(c+a),i(h+v),i(c+v),i("flush"),config.disableExceptionTracking||(r="onerror",i("_"+r),f=e[r],e[r]=function(config,i,u,e,o){{var s=f&amp;&amp;f(config,i,u,e,o);return s!==!0&amp;&amp;t["_"+r](config,i,u,e,o),s}}),t
    }}({{
        instrumentationKey: '{0}'
    }});

    window.appInsights=appInsights;
    appInsights.trackPageView();
</script>
```

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 Link to this section

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 distributed to a CDN and globally distributed very quickly.
2. If you are using a [Content Security Policy (CSP)](https://rehansaeed.com/content-security-policy-for-asp-net-mvc/) 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 Link to this section

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](https://www.npmjs.com/package/applicationinsights-js) NPM package which you can add to your `package.json` like so:

```json
{
  "dependencies": {
    "applicationinsights-js": "1.0.5"
    // ...
  }
  // ...
}
```

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:

```js
var gulp = require('gulp'),
    sourcemaps = require('gulp-sourcemaps'),    // Creates source map files (https://www.npmjs.com/package/gulp-sourcemaps/)
    replace = require('gulp-replace-task'),     // String replace (https://www.npmjs.com/package/gulp-replace-task/)
    uglify = require('gulp-uglify');            // Minifies JavaScript (https://www.npmjs.com/package/gulp-uglify/)

gulp.task('build-app-insights-js',
    function() {
        return gulp
            .src('./node_modules/ApplicationInsights-JS/JavaScript/JavaScriptSDK/snippet.js')
            .pipe(sourcemaps.init())               // Set up the generation of .map source files for the JavaScript.
            .pipe(
                replace({                          // Carry out the specified find and replace.
                    patterns: [
                        {
                            // match - The string or regular expression to find.
                            match: 'CDN_PATH',
                            // replacement - The string or function used to make the replacement.
                            replacement: 'https://az416426.vo.msecnd.net/scripts/a/ai.0.js'
                        },
                        {
                           match: 'INSTRUMENTATION_KEY',
                           replacement: '11111111-2222-3333-4444-555555555555'
                        }
                    ],
                    usePrefix: false
                }))
            .pipe(uglify())                        // Minifies the JavaScript.
            .pipe(sourcemaps.write('.'))           // Generates source .map files for the JavaScript.
            .pipe(gulp.dest('./wwwroot/js/'));     // Saves the JavaScript file to the specified destination path.
});
```

Finally we can include the script in our HTML. Don't forget to include the `crossorigin` attribute on all your script tags, which allows full stack traces to be reported. You can read more about the `crossorigin` attribute [here](https://raygun.com/blog/2015/05/fixing-script-errors/).

```html
<script asp-append-version="true"
        crossorigin="anonymous"
        src="~/js/application-insights.js"></script>
```

# Conclusion Link to this section

As usual, all of the above is built in to the [ASP.NET Core Boilerplate](https://github.com/ASP-NET-MVC-Boilerplate/Templates) project template, available as a [Visual Studio extension](https://visualstudiogallery.msdn.microsoft.com/6cf50a48-fc1e-4eaf-9e82-0b2a6705ca7d) if you select the optional Application Insights feature.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## GitHub Comments

### 0 Comments

[Comment on GitHub](https://github.com/RehanSaeed/rehansaeed.github.io/issues/87)

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/making-application-insights-fast-and-secure/#webpage","@type":"WebPage","dateModified":"2016-12-11T00:00:00+00:00","datePublished":"2016-12-11T00:00:00+00:00","description":"Implementing Application Insights into your ASP.NET Core application with performance and security as a top priority in this advanced scenario.","name":"Making Application Insights Fast & Secure","url":"https://rehansaeed.com/making-application-insights-fast-and-secure/","breadcrumb":{"@id":"https://rehansaeed.com/making-application-insights-fast-and-secure/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/making-application-insights-fast-and-secure/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/making-application-insights-fast-and-secure/#article","@type":"Article","dateModified":"2016-12-11T00:00:00+00:00","datePublished":"2016-12-11T00:00:00+00:00","description":"Implementing Application Insights into your ASP.NET Core application with performance and security as a top priority in this advanced scenario.","headline":"Making Application Insights Fast & Secure","inLanguage":"en-GB","url":"https://rehansaeed.com/making-application-insights-fast-and-secure/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Application-Insights-1366x768.png","caption":"Application Insights","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/making-application-insights-fast-and-secure/#webpage"},"keywords":[".NET","Application Insights","ASP.NET Core","ASP.NET MVC","ASP.NET Core Boilerplate","C#","Content Security Policy"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/making-application-insights-fast-and-secure/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/making-application-insights-fast-and-secure/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"Making Application Insights Fast & Secure","item":"https://rehansaeed.com/making-application-insights-fast-and-secure/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
