Skip to content

Typescript library to use Application Insights in React applications

License

Notifications You must be signed in to change notification settings

florianchevallier/react-appinsights

 
 

Repository files navigation

react-appinsights

npm Build Status Greenkeeper badge Downloads per month

Javascript library to integrate Application Insights in applications built with React.
react-appinsights extends Application Insights with additional React-specific features:

  • tracking of router changes
  • React components usage statistics
  • API to extend the standard telemetry with additional dimensions

IMPORTANT - please read!

Please note that the latest stable version of this package is 2.0.2 and the corresponding documentation for this version resides here. However, the package is soon going to be upgraded to its next major version (3.0.0). The release candidate (3.0.0-rc6) for this version is published here. The content of this readme refers to the next major version.

Installation

Using npm:

npm install --save react-appinsights@beta

Usage

To initialize Application Insights, add the following to the entry point file of your application (e.g. index.js):

import { reactAI } from "react-appinsights";
import { ApplicationInsights } from "@microsoft/applicationinsights-web";

let appInsights = new ApplicationInsights({
  config: {
    instrumentationKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx",
    extensions: [reactAI],
    extensionConfig: {
      [reactAI.extensionId]: { debug: false }
    }
  }
});
appInsights.loadAppInsights();

See this Application Insights tutorial for Node.js for more details on how to obtain the instrumentation key.

IReactAISettings has following non-mandatory configuration options to be passed into the extensionConfig object:

interface IReactAISettings {
  initialContext?: { [key: string]: any };  // Initial context to initialize with
  history?: History;                        // React router history - to enable page view tracking
  debug?: boolean;                          // Debug mode: displays debug messages from ReactAI in console
}

Track router changes

To track page views, pass a history object to the init method.
For more information see the documentation of the react-router package.

import { reactAI } from "react-appinsights";
import { ApplicationInsights } from "@microsoft/applicationinsights-web";
import { Router } from "react-router-dom";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

/*
 * In the code sample above, set configuration as follows:
 *   extensionConfig: {
 *     [ReactAI.extensionId]: { history: history }
 *   }
 */

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  document.getElementById("root")
);

Enable React components usage tracking

To instrument various React components usage tracking, apply the withAITracking higher-order component function.

import { withAITracking } from 'react-appinsights';

class MyComponent extends React.Component {
    ...
}

export default withAITracking(MyComponent);

To change the name string of the component that appears in Application Insights, you can pass a custom name as second argument of withAITracking.

export default withAITracking(MyComponent, "CustomMyComponentName");

It will measure time from the ComponentDidMount event through the ComponentWillUnmount event. However, in order to make this more accurate, it will subtract the time in which the user was idle. In other words, React Component Engaged Time = ComponentWillUnmount timestamp - ComponentDidMount timestamp - idle time.

To see this metric in the Azure portal you need to navigate to the Application Insights resource, select "Metrics" tab and configure the empty charts to display Custom metric named "React Component Engaged Time (seconds)", select aggregation (sum, avg, etc.) of your liking and apply split by "Component Name".

image

You can also run custom queries to slice and dice AI data to generate reports and visualizations as per your requirements. In the Azure portal, navigate to the Application Insights resource, select "Analytics" from the top menu of the Overview tab and run your query.

image

Please note that it can take up to 10 minutes for new custom metric to appear in the Azure Portal.

Set application context

To augment all telemetry with additional properties use setContext method. For instance:

reactAI.setContext({ CorrelationId: "some-unique-correlation-id", Referrer: document.referrer });

This will add CorrelationId and Referrer property to all page views, ajax calls, exceptions and other telemetry sent to Application Insights.

Get original AppInsights object

Use the following method to get the original AppInsights object:

var appInsights = reactAI.appInsights;

Refer to this doc for information on the Javascript API of Application Insights.

About

Typescript library to use Application Insights in React applications

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 82.3%
  • JavaScript 17.7%