Application Insights for Single Page Applications

    Application monitoring is a fundamental service that any application should have to understand the performance and health of it. When it comes to Single Page Applications (SPA) written on Angular, React or similar frameworks, monitoring becomes crucial because the application runs on the user’s browser.  Ideally, we want to be able to log errors and track custom events to better understand the application performance without having to code an API which consumes the telemetry information.


Application Insights

    Application Insights (AppInsights) is an Application Performance Management (APM) service part of the Azure Monitor services. It is used to monitor running applications.  It is widely used on different platforms like .Net, Node.js, Python and client-side applications written with JavaScript frameworks like React, Angular and others. It is also used by mobile application to help manage crash reporting from all the devices where the application is running from.

    On the cloud, AppInsights provides data analytics tools that are used to understand user behavior and application performance.  The analysis of the data leads to the continuous improvement of the application usability and quality. In addition, visualization tools like PowerBI can be used to tap into the data and create dashboards that can provide insights to the DevOps and Development teams as well as UX designer for usability cases.

How does it work on a SPA?

    At the application level, there is an NPM package that must be installed in the Single Page application to help use the AppInsights services to track events, errors, and API calls. Those events are sent to the Azure monitor service in the cloud via API calls. The API is provided by the monitor service on Azure, and the location of the endpoint is defined in the NPM package.

Note: AppInsights automatically tracks telemetry data like page views, request performance, user sessions and unhandled exceptions for crash reporting. For custom error and event handling, continue to read this article.  

    For the Azure monitor service to resolve the tenant and AppInsights instance information, we need to get the instrumentation key from the application insights instance. This information can be found on the overview blade of the instance associated to your application. To create the instance, visit the resource that is hosting the SPA, click on the Application Insights link and enable the integration. That should provision the AppInsights instance for the application.

Client configuration

    On the client application, open Visual Studio Code and open a terminal console. On the console, install the AppInsights NPM package by entering this command:


npm i –save @microsoft/applicationinsights-web



    Once the package is installed, we can add the instrumentation key to the application as an environment variable. The application environment file (.env) is the right place to add this key. This file uses a key=value format to set those variables.  Most SPAs have an environment file to host application-level variables which can be accessed by using the process object.  If the project does not have this file, one can be created manually. For the variables to be loaded properly, the application needs to be restarted.  Also depending on the current framework and version, like React or Angular, the NPM package env-cmd maybe installed. This package handles the parsing and loading of the variables from the file when the application first loads.

Note: In newer versions of the JavaScript framework, there is no need to add the NPM package.

Note:  Depending on the framework, the variable names should follow a particular naming convention. For example, React requires that the variables are prefixed with the tag REACT_APP

As an example, the instrumentation key should be set with the following format:




     The variable value can then be accessed from anywhere in the code by using the process object.


const key = process.env.INSIGHTSKEY;


Build the logger

    After setting the configuration, we can now implement a service where we can centralize the logging of errors and events. Usually, the logger or exception manager service on the application is the right place for that. This way anywhere in the app, we can import the logger and use it to log errors and events to the cloud.  Review a simple implementation of how this service could be implemented using TypeScript.

Logger Gist

    After reviewing the code, we can notice all the steps taken to initialize the service and what is exported for other components to call. The code first imports the ApplicationInsights dependency. It then instantiates the service with the instrumentation key, which is read from the environment variables. The service exports three functions, init, error, track.

    The init function initializes or bootstrap the AppInsights service. This allows it to track and send telemetry information like page visits and performance metrics automatically. The error function is used to send exception and custom error messages. The track function sends custom events. It uses generics for the data parameter, so it can support events with primitive and complex types.

How to log events

    We should now be ready to look at our application to figure out what we need to log.  For example, we could log handled errors and some important telemetry about our app. For telemetry, we can log the navigation, click events and other custom events that are important to track.

    Each component and/or service of the application, should be handling errors and custom events. The custom events should use a tag name and some measure or message that you want to track.  It is important to define this information properly, so it can be shown on the analytic tools hosted on Azure.

Custom errors

    Custom errors are handled exceptions or unexpected results by the application. These errors are usually handled on a try/catch block or some business rule validation. To log the error, just use the logger service and call the error function, passing the Error object as parameter.

Custom Errors Gist

Custom events

    Custom events are the business events that track application critical messages that can be measured as goal or conversion on the application. Some examples may include customer registration, profile changes and other measurable events that should be reported on the analytical tools. Use the track function of the logger service to log events. Send a tag, for grouping, and a JSON document with some information about the event.

Custom Events Gist

Verifying the data

    After deploying the application and running some test that can trigger some errors or custom events, verify that the messages are sent correctly.  The first verification is to use the browser console, network tab.  We should see some traffic with the track request and VisualStudio endpoint. We are looking for the status to be 200 which should indicate that the message made it home.

    Next, head over to the Azure Portal and open the Application Insights associated with the application. There are multiple tools to use there, so experiment and learn from them. A tool to use and query data is available from the Logs link. This tool list all the tables that are available. To query the custom events, use the custom events table and query the data with a SQL like script.


    For visual statistical analysis, we can use the Events tool. This presents the data on charts, which enables us to visualize the data from the application.


    It is very valuable for our client-side apps to be able to report telemetry information to the cloud. This can enable teams to learn about the application performance and usability. Azure Application Insights provides a solution that enables all applications, built on different platforms, to easily integrate with the service. It is a complete solution because it provides the pipeline to send telemetry data from the applications as well as the analytical tools to view, monitor and learn from the telemetry data.

Thanks for reading.

Originally published by ozkary.com


Post a Comment

What do you think?