Skip to content

Latest commit

 

History

History
157 lines (111 loc) · 6.36 KB

README.md

File metadata and controls

157 lines (111 loc) · 6.36 KB

⚠️ Deprecation Warning ⚠️

This repository has been archived and the corresponding npm package deprecated. The recommended way of using Application Insights in a React application is through its React plugin @microsoft/applicationinsights-react-js, whose code and documentation reside in the repository of Application Insights SDK for JavaScript. The React plugin is based on version 3.x of react-appinsights.


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

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.