แก้ไข

แชร์ผ่าน


Enable a framework extension for Application Insights JavaScript SDK

In addition to the core SDK, there are also plugins available for specific frameworks, such as the React plugin, the React Native plugin, and the Angular plugin.

These plugins provide extra functionality and integration with the specific framework.

Prerequisites

What does the plug-in enable?

The React plug-in for the Application Insights JavaScript SDK enables:

  • Track router history
  • Track exceptions
  • Track components usage
  • Use Application Insights with React Context

Add a plug-in

To add a plug-in, follow the steps in this section.

Install the package


npm install @microsoft/applicationinsights-react-js

Add the extension to your code

Note

On March 31, 2025, support for instrumentation key ingestion will end. Instrumentation key ingestion will continue to work, but we'll no longer provide updates or support for the feature. Transition to connection strings to take advantage of new capabilities.

Initialize a connection to Application Insights:

import React from 'react';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactPlugin } from '@microsoft/applicationinsights-react-js';
import { createBrowserHistory } from "history";
const browserHistory = createBrowserHistory({ basename: '' });
var reactPlugin = new ReactPlugin();
// *** Add the Click Analytics plug-in. ***
/* var clickPluginInstance = new ClickAnalyticsPlugin();
   var clickPluginConfig = {
     autoCapture: true
}; */
var appInsights = new ApplicationInsights({
    config: {
        connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE',
        // *** If you're adding the Click Analytics plug-in, delete the next line. ***
        extensions: [reactPlugin],
     // *** Add the Click Analytics plug-in. ***
     // extensions: [reactPlugin, clickPluginInstance],
        extensionConfig: {
          [reactPlugin.identifier]: { history: browserHistory }
       // *** Add the Click Analytics plug-in. ***
       // [clickPluginInstance.identifier]: clickPluginConfig
        }
    }
});
appInsights.loadAppInsights();

(Optional) Add the Click Analytics plug-in

If you want to add the Click Analytics plug-in:

  1. Uncomment the lines for Click Analytics.

  2. Do one of the following, depending on which plug-in you're adding:

    • For React, delete extensions: [reactPlugin],.
    • For React Native, delete extensions: [RNPlugin].
    • For Angular, delete extensions: [angularPlugin],.
  3. See Use the Click Analytics plug-in to continue with the setup process.

Configuration

This section covers configuration settings for the framework extensions for Application Insights JavaScript SDK.

Track router history

Name Type Required? Default Description
history object Optional null Track router history. For more information, see the React router package documentation.

To track router history, most users can use the enableAutoRouteTracking field in the JavaScript SDK configuration. This field collects the same data for page views as the history object.

Use the history object when you're using a router implementation that doesn't update the browser URL, which is what the configuration listens to. You shouldn't enable both the enableAutoRouteTracking field and history object, because you'll get multiple page view events.

The following code example shows how to enable the enableAutoRouteTracking field.

var reactPlugin = new ReactPlugin();
var appInsights = new ApplicationInsights({
    config: {
        connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE',
        enableAutoRouteTracking: true,
        extensions: [reactPlugin]
    }
});
appInsights.loadAppInsights();

Track exceptions

React error boundaries provide a way to gracefully handle an uncaught exception when it occurs within a React application. When such an exception occurs, it's likely that the exception needs to be logged. The React plug-in for Application Insights provides an error boundary component that automatically logs the exception when it occurs.

import React from "react";
import { reactPlugin } from "./AppInsights";
import { AppInsightsErrorBoundary } from "@microsoft/applicationinsights-react-js";

const App = () => {
    return (
        <AppInsightsErrorBoundary onError={() => <h1>I believe something went wrong</h1>} appInsights={reactPlugin}>
            /* app here */
        </AppInsightsErrorBoundary>
    );
};

The AppInsightsErrorBoundary requires two props to be passed to it. They're the ReactPlugin instance created for the application and a component to be rendered when an exception occurs. When an unhandled exception occurs, trackException is called with the information provided to the error boundary, and the onError component appears.

Collect device information

The device information, which includes Browser, OS, version, and language, is already being collected by the Application Insights web package.

Configuration (other)

Track components usage

A feature that's unique to the React plug-in is that you're able to instrument specific components and track them individually.

To instrument React components with usage tracking, apply the withAITracking higher-order component function. To enable Application Insights for a component, wrap withAITracking around the component:

import React from 'react';
import { withAITracking } from '@microsoft/applicationinsights-react-js';
import { reactPlugin, appInsights } from './AppInsights';

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

class MyComponent extends React.Component {
    ...
}

// withAITracking takes 4 parameters (reactPlugin, Component, ComponentName, className). 
// The first two are required and the other two are optional.

export default withAITracking(reactPlugin, MyComponent);

It measures time from the ComponentDidMount event through the ComponentWillUnmount event. To make the result more accurate, it subtracts the time in which the user was idle by using React Component Engaged Time = ComponentWillUnmount timestamp - ComponentDidMount timestamp - idle time.

Explore your data

Use Azure Monitor metrics explorer to plot a chart for the custom metric name React Component Engaged Time (seconds) and split this custom metric by Component Name.

Screenshot that shows a chart that displays the custom metric React Component Engaged Time (seconds) split by Component Name

You can also run custom queries to divide Application Insights data to generate reports and visualizations as per your requirements. Here’s an example of a custom query. Go ahead and paste it directly into the query editor to test it out.

customMetrics
| where name contains "React Component Engaged Time (seconds)"
| summarize avg(value), count() by tostring(customDimensions["Component Name"])

It can take up to 10 minutes for new custom metrics to appear in the Azure portal.

Use Application Insights with React Context

We provide general hooks to allow you to customize the change tracking for individual components. Alternatively, you can use useTrackMetric or useTrackEvent, which are pre-defined contacts we provide for tracking the changes to components.

The React Hooks for Application Insights are designed to use React Context as a containing aspect for it. To use Context, initialize Application Insights, and then import the Context object:

import React from "react";
import { AppInsightsContext } from "@microsoft/applicationinsights-react-js";
import { reactPlugin } from "./AppInsights";

const App = () => {
    return (
        <AppInsightsContext.Provider value={reactPlugin}>
            /* your application here */
        </AppInsightsContext.Provider>
    );
};

This Context Provider makes Application Insights available as a useContext Hook within all children components of it:

import React from "react";
import { useAppInsightsContext } from "@microsoft/applicationinsights-react-js";

const MyComponent = () => {
    const appInsights = useAppInsightsContext();
    const metricData = {
        average: engagementTime,
        name: "React Component Engaged Time (seconds)",
        sampleCount: 1
      };
    const additionalProperties = { "Component Name": 'MyComponent' };
    appInsights.trackMetric(metricData, additionalProperties);
    
    return (
        <h1>My Component</h1>
    );
}
export default MyComponent;
useTrackMetric

The useTrackMetric Hook replicates the functionality of the withAITracking higher-order component, without adding another component to the component structure. The Hook takes two arguments:

  • The Application Insights instance, which can be obtained from the useAppInsightsContext Hook.
  • An identifier for the component for tracking, such as its name.
import React from "react";
import { useAppInsightsContext, useTrackMetric } from "@microsoft/applicationinsights-react-js";

const MyComponent = () => {
    const appInsights = useAppInsightsContext();
    const trackComponent = useTrackMetric(appInsights, "MyComponent");
    
    return (
        <h1 onHover={trackComponent} onClick={trackComponent}>My Component</h1>
    );
}
export default MyComponent;

It operates like the higher-order component, but it responds to Hooks lifecycle events rather than a component lifecycle. If there's a need to run on particular interactions, the Hook needs to be explicitly provided to user events.

useTrackEvent

Use the useTrackEvent Hook to track any custom event that an application might need to track, such as a button click or other API call. It takes four arguments:

  • Application Insights instance, which can be obtained from the useAppInsightsContext Hook.
  • Name for the event.
  • Event data object that encapsulates the changes that have to be tracked.
  • skipFirstRun (optional) flag to skip calling the trackEvent call on initialization. The default value is set to true to mimic more closely the way the non-Hook version works. With useEffect Hooks, the effect is triggered on each value update including the initial setting of the value. As a result, tracking starts too early, which causes potentially unwanted events to be tracked.
import React, { useState, useEffect } from "react";
import { useAppInsightsContext, useTrackEvent } from "@microsoft/applicationinsights-react-js";

const MyComponent = () => {
    const appInsights = useAppInsightsContext();
    const [cart, setCart] = useState([]);
    const trackCheckout = useTrackEvent(appInsights, "Checkout", cart);
    const trackCartUpdate = useTrackEvent(appInsights, "Cart Updated", cart);
    useEffect(() => {
        trackCartUpdate({ cartCount: cart.length });
    }, [cart]);
    
    const performCheckout = () => {
        trackCheckout();
        // submit data
    };
    
    return (
        <div>
            <ul>
                <li>Product 1 <button onClick={() => setCart([...cart, "Product 1"])}>Add to Cart</button></li>
                <li>Product 2 <button onClick={() => setCart([...cart, "Product 2"])}>Add to Cart</button></li>
                <li>Product 3 <button onClick={() => setCart([...cart, "Product 3"])}>Add to Cart</button></li>
                <li>Product 4 <button onClick={() => setCart([...cart, "Product 4"])}>Add to Cart</button></li>
            </ul>
            <button onClick={performCheckout}>Checkout</button>
        </div>
    );
}

export default MyComponent;

When the Hook is used, a data payload can be provided to it to add more data to the event when it's stored in Application Insights.

Sample app

Check out the Application Insights React demo.

Frequently asked questions

This section provides answers to common questions.

How does Application Insights generate device information like browser, OS, language, and model?

The browser passes the User Agent string in the HTTP header of the request. The Application Insights ingestion service uses UA Parser to generate the fields you see in the data tables and experiences. As a result, Application Insights users are unable to change these fields.

Occasionally, this data might be missing or inaccurate if the user or enterprise disables sending User Agent in browser settings. The UA Parser regexes might not include all device information. Or Application Insights might not have adopted the latest updates.

Next steps