Azure AppInsights integration in Blazor WASM

Integrating Azure Application Insights in a Blazor WebAssembly (WASM) app is possible, though it requires special handling since Blazor WASM runs entirely in the browser, and you can’t use the full .NET SDK for Application Insights like you can in server-side apps.

Here’s how you can set it up using JavaScript SDK (since Blazor WASM ultimately runs in the browser):


✅ Step-by-Step Guide

1. Create Application Insights Resource (if not done)

  • Go to Azure Portal → Create a resource → Application Insights.
  • Choose GeneralApplication Insights, select region, etc.
  • After creation, copy the Instrumentation Key or Connection String.

2. Add the Application Insights JavaScript SDK

In your Blazor WebAssembly project:

Modify wwwroot/index.html (for standalone Blazor WASM)

htmlCopyEdit<!-- Application Insights JavaScript SDK -->
<script type="text/javascript">
  var appInsights = window.appInsights || function (config) {
    function r(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 = u.createElement(o), i, f;
    for (s.src = config.url || "https://az416426.vo.msecnd.net/scripts/a/ai.0.js", u.getElementsByTagName(o)[0].parentNode.appendChild(s), t.cookie = u.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace", "Dependency"]; i.length;)
      r("track" + i.pop());
    return r("setAuthenticatedUserContext"), r("clearAuthenticatedUserContext"), r("flush"), config.disableExceptionTracking || (i = "onerror", r("_" + i), f = e[i], e[i] = function (config, r, u, e, o) {
      var s = f && f(config, r, u, e, o);
      return s !== !0 && t["_" + i](config, r, u, e, o), s
    }), t
  }({
    instrumentationKey: "YOUR_INSTRUMENTATION_KEY"
  });

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

3. Call App Insights from C# Code

You can invoke JavaScript from your Blazor C# code like this:

Create a service to interact with JS (e.g., AppInsightsService.cs):

csharpCopyEditusing Microsoft.JSInterop;
using System.Threading.Tasks;

public class AppInsightsService
{
    private readonly IJSRuntime _jsRuntime;

    public AppInsightsService(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    public async Task TrackEventAsync(string eventName)
    {
        await _jsRuntime.InvokeVoidAsync("appInsights.trackEvent", new { name = eventName });
    }

    public async Task TrackExceptionAsync(string errorMessage)
    {
        await _jsRuntime.InvokeVoidAsync("appInsights.trackException", new
        {
            exception = new { message = errorMessage }
        });
    }

    public async Task TrackPageViewAsync(string pageName)
    {
        await _jsRuntime.InvokeVoidAsync("appInsights.trackPageView", new { name = pageName });
    }
}

4. Register the Service

In Program.cs:

csharpCopyEditbuilder.Services.AddScoped<AppInsightsService>();

5. Use in Your Components

razorCopyEdit@inject AppInsightsService AppInsights

<button @onclick="TrackEvent">Track Event</button>

@code {
    private async Task TrackEvent()
    {
        await AppInsights.TrackEventAsync("ButtonClicked");
    }
}

🧠 Notes

  • Only client-side telemetry will be captured (JS-side) — no automatic dependency tracking, for example.
  • If you need full telemetry, consider combining it with Blazor WASM hosted model and using Application Insights server SDK in the backend.
FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect

Leave a Reply