Giter Club home page Giter Club logo

applicationinsights-react-js's Introduction

Microsoft Application Insights JavaScript SDK - React Plugin

npm version

React Plugin for the Application Insights Javascript SDK, enables the following:

  • Tracking of router changes
  • React components usage statistics

Full documentation for the React Plugin for the Application Insights JavaScript SDK can be found on Microsoft Docs.

Getting Started

Install npm package:

npm install @microsoft/applicationinsights-react-js

Basic Usage

import React from 'react';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactPlugin, withAITracking } from '@microsoft/applicationinsights-react-js';
import { createBrowserHistory } from "history";

const browserHistory = createBrowserHistory({ basename: '' });
var reactPlugin = new ReactPlugin();
var appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        extensions: [reactPlugin],
        extensionConfig: {
          [reactPlugin.identifier]: { history: browserHistory }
        }
    }
});
appInsights.loadAppInsights();

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

class MyComponent extends React.Component {
    ...
}

export default withAITracking(reactPlugin, MyComponent);

For react-router v6 or other scenarios where router history is not exposed, appInsights config enableAutoRouteTracking can be used to auto track router changes.

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

Configuration

Name Default Description
history null React router history for more information see the documentation of the react-router package.

React components usage tracking

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

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.

Sample App

Azure-Samples/application-insights-react-demo.

React Router

Compatibility Matrix

As part of updating to support ApplicationInsights 3.x we will be bumping the major version number of this extension to match the major version of the supported React-JS version (which will be v17.x for the first release).

Additionally, as part of this change the existing v3.x extension has been moved into the release3.x branch

Version Application Insights React Branch
17.1.2 ^3.1.2 >= 17.0.2 main
17.1.1 ^3.1.1 >= 17.0.2 main
17.1.0 ^3.1.0 >= 17.0.2 main
17.0.4 ^3.0.8 >= 17.0.2 main
17.0.3 ^3.0.7 >= 17.0.2 main
17.0.2 ^3.0.3 >= 17.0.2 main
17.0.1 ^3.0.3 >= 17.0.2 main
17.0.0 ^3.0.2 >= 17.0.2 main
3.4.3 ^2.8.14 >= 17.0.2 release3.x
3.4.2 ^2.8.12 >= 17.0.1 main
3.4.1 ^2.8.10 >= 17.0.1 main
3.4.0 ^2.8.5 >= 17.0.1 main
3.3.6 ^2.8.5 ^17.0.1 main <-- First release from this repo
3.3.5 2.8.5 ^17.0.1 main and AI master
3.3.4 2.8.4 ^17.0.1 AI master
3.3.3 2.8.3 ^17.0.1 AI master
3.3.2 2.8.2 ^17.0.1 AI master
3.3.1 2.8.1 ^17.0.1 AI master
3.3.0 2.8.0 ^17.0.1 AI master
3.2.4 2.7.4 ^17.0.1 AI master
3.2.3 2.7.3 ^17.0.1 AI master
3.2.2 2.7.2 ^17.0.1 AI master
3.2.1 2.7.1 ^17.0.1 AI master
3.2.0 2.7.0 ^17.0.1 AI master
3.1.5 ^2.6.5 ^17.0.1 AI master
3.1.4 ^2.6.4 ^17.0.1 AI master
3.1.3 ^2.6.3 ^17.0.1 AI master
3.1.2 ^2.6.2 ^17.0.1 AI master
3.1.1 ^2.6.2 ^17.0.1 AI master
3.1.0 ^2.6.0 ^17.0.1 AI master
3.0.5 ^2.5.10 ^16.0.0 AI master
3.0.4 ^2.5.9 ^16.0.0 AI master

Nightly Builds

To aid with testing and validation we also produce and publish nightly builds whenever there is a change from the previous build. These builds are published to the NpmJs registry on a successful build / test pass.

This process also tags the source code so that we can track the specific changes included using a nightly build specific version number which is the format "nightly-yymm-##" eg. nightly-2208-05

These nightly builds will not be retained indefinitely and should only be used for pre-production testing and/or validation of any changes that have not yet been released.

NPM

The NPM builds are tagged as "nightly" and can by downloaded using this as the version number npm install @microsoft/applicationinsights-react-js@nightly or using the nightly specific version number which is "nightly.yyyymm-###" (npm install @microsoft/[email protected]) where ## is the specific build number for the month (Note, slightly different version from the source code tag due to compatibility issues between the different systems).

Deployment process

When a new release is deployed the following occurs as part of the release

  • NPM packages are created and published to NpmJs

Release Notes

Release Notes

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Data Collection

As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement.

The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.

License

MIT

applicationinsights-react-js's People

Contributors

aaronpowell avatar abaranch avatar bittola avatar brainrepo avatar capfei avatar dependabot[bot] avatar hectorhdzg avatar ishraque99 avatar jpiyali avatar karlie-777 avatar kryalama avatar markwolff avatar maxshehovtsov avatar microsoft-github-operations[bot] avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar msnev avatar ramthi avatar remijean avatar simonurmi avatar siyuniu-ms avatar szilagyi-sandor avatar xiao-lix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

applicationinsights-react-js's Issues

[BUG] React - withAITracking wrapper modifies the app's css

Description/Screenshot
By wrapping my React application in the TelemetryProvider, using withAITracking, the css of the app is altered, and there is no indication that withAITracking is actually used.
Original style:
image

Style with an withAITracking wrapper:
image

The sidebar of my app is contracted and no longer fills the side. Classes are mixed up, and I don't know why.

Steps to Reproduce

⚡ Files have been altered to protect sensitive code and to highlight the essential parts

App.tsx:

import React from 'react';
import { createHistory, createMemorySource } from '@reach/router';

function App(): JSX.Element {

  const history = createHistory(createMemorySource('/'));
  return (
    <TelemetryProvider
      history={history}
      instrumentationKey={KEY_HERE}
    >
     { *** APP *** }
    </TelemetryProvider>
  );
}
export default App;

TelemetryProvider.tsx:

import React from 'react';
import {
  withAITracking,
  ReactPlugin,
} from '@microsoft/applicationinsights-react-js';
import { ai } from '../../services/TelemetryService';

/**
 * This Component provides telemetry with Azure App Insights
 *
 * NOTE: the package '@microsoft/applicationinsights-react-js' has a HOC withAITracking that requires this to be a Class Component rather than a Functional Component
 *
 * Voir le projet https://github.com/Azure-Samples/application-insights-react-demo pour l'utilisation
 */

export interface TelemetryProviderProps {
  history: any;
  instrumentationKey: string;
}

type TelemetryProviderState = {
  initialized: boolean;
};
class TelemetryProvider extends React.Component<
  TelemetryProviderProps,
  TelemetryProviderState
> {
  constructor(props: TelemetryProviderProps) {
    super(props);
    this.state = {
      initialized: false,
    };
  }

  componentDidMount() {
    const { history } = this.props;
    const { initialized } = this.state;
    const { instrumentationKey } = this.props;
    if (!initialized && Boolean(instrumentationKey) && Boolean(history)) {
      ai.initialize(instrumentationKey, history);
      this.setState({ initialized: true });
    }
  }

  render() {
    const { children } = this.props;
    return <>{children}</>;
  }
}

export default withAITracking(ai.reactPlugin as ReactPlugin, TelemetryProvider);

TelemetryService.ts:

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactPlugin } from '@microsoft/applicationinsights-react-js';

let reactPlugin: ReactPlugin | null = null;
let appInsights: ApplicationInsights | null = null;

/**
 * Create the App Insights Telemetry Service
 * @return {{reactPlugin: ReactPlugin, appInsights: Object, initialize: Function}} - Object
 */
const createTelemetryService = () => {
  /**
   * Initialize the Application Insights class
   * @param {string} instrumentationKey - Application Insights Instrumentation Key
   * @param {Object} browserHistory - client's browser history, supplied by the withRouter HOC
   * @return {void}
   */
  const initialize = (instrumentationKey: string, browserHistory: Object) => {
    if (!browserHistory) {
      throw new Error('Could not initialize Telemetry Service');
    }
    if (!instrumentationKey) {
      throw new Error('Instrumentation key not provided');
    }

    reactPlugin = new ReactPlugin();

    appInsights = new ApplicationInsights({
      config: {
        instrumentationKey,
        maxBatchInterval: 0,
        disableFetchTracking: false,
        extensions: [reactPlugin],
        extensionConfig: {
          [reactPlugin.identifier]: {
            history: browserHistory,
          },
        },
      },
    });

    appInsights.loadAppInsights();
  };

  return { reactPlugin, appInsights, initialize };
};

export const ai = createTelemetryService();
export const getAppInsights = () => appInsights;
  • OS/Browser: Chrome 89.0.4389.114
  • SDK Version [e.g. 22]: @microsoft/[email protected]
  • How you initialized the SDK:

Expected behavior

When using the wrapper withAITracking, the function should return the component of the app as it is with no modifications. No change should be perceptible in the style, and the application should start tracking the metric React Component Engaged Time (seconds).

Additional context

  • I've narrowed it down to withAITracking simply by removing it from the TelemetryProvider. And it worked. I could still send metrics and exceptions to Azure App Insight
  • The metric React Component Engaged Time (seconds) isn't showing up so far in my ressource on Azure.
  • In VSCode, when I choose Go to Definition on withAITracking, it sends me to withAITracking.d.ts, and not to the actual implementation, leading me to believe that the real function is never even reached. Adding console messages in withAITracking.tsx doesn't make them appear in the browser's console. I can't seem to modify the code and change anything in the application.
  • So far, my only workaround has been to remove the withAITracking wrapper, but it seems like a waste. If there's no added cost, I'd like to be able to use this tool. But we'll be force to remove it for now. I don't like to differ my app compared to the sample react app too much.

[BUG] ReactPlugin becomes undefined after certain amount of time

Description/Screenshot
I wrapped each of my components with withAITracking and confirmed that I am properly passing in the instance of the React Plugin.

However, after frequent navigations the app randomly crashes indicating that the React plugin is undefined.

Looks like there was a thread about this issue in the old repo.

Screen Shot 2022-10-19 at 2 57 19 PM

Steps to Reproduce

Quickly navigate between pages that render components that have been wrapped with withAITracking

  • OS/Browser: MacOS/Chrome & Safari
  • React Version:
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
  • SDK Version [e.g. 22]:
    "@microsoft/applicationinsights-react-js": "^3.4.0",
    "@microsoft/applicationinsights-web": "^2.8.8",
  • How you initialized the SDK:
    (NOTE: Some code has been removed)
export class DocsApplicationInsights {
  private reactPlugin: ReactPlugin;

  private searchListener;

  private appInsights;

  setup() {
    const { createBrowserHistory } = require('history');
    this.reactPlugin = new ReactPlugin();
    this.appInsights = new ApplicationInsights({
      config: {
        connectionString:appInsightsConnectionString,
        extensions: [this.reactPlugin],
        extensionConfig: {
          [this.reactPlugin.identifier]: { history: createBrowserHistory({ basename: '' }) },
        },
      },
    });
    this.appInsights.loadAppInsights();
    this.appInsights.setAuthenticatedUserContext(id, undefined, true);
  }

  getReactPlugin() {
    // console.log(Boolean(this.reactPlugin)); <- BTW this always outputs to true when it crashes.
    return this.reactPlugin;
  }
  }
}

export default new DocsApplicationInsights();

Expected behavior
App & components render

Additional context
Using docusaurus.

ApplicationInsights-JS v3 Compatibility

Thanks for the great work of the JS SDK and React plugin!

Is your feature request related to a problem? Please describe.

ApplicationInsights-JS has been upgraded to v3 which is a major update, but there's no documentation of the React plugin says it is compatible with the latest JS SDK.

Describe the solution you'd like

An official support of ApplicationInsights-JS v3.

Describe alternatives you've considered

I've read the Breaking Changes and found:

If the extension is 100% self contained (all referenced code is included in it’s own bundle), then apart from some TypeScript typing warnings / errors the SDK will load and initialize the plugin.

It looks like the plugin should be OK, but it'll be great if we can have an official support or documentation of the v3 compatibility.

Uncaught TypeError: Cannot redefine property: pathname when calling appInsights.loadAppInsights();

Description/Screenshot
Uncaught TypeError: Cannot redefine property: pathname
when calling appInsights.loadAppInsights();

image

Crashes app before react component is rendered, so web page just shows blank. I reproduced this with a simple Vite app, just adding the two app-insights packages and the initialization code below.

Steps to Reproduce

  • OS/Browser: MacOS latest version
  • SDK Version [e.g. 22]:
   "@microsoft/applicationinsights-react-js": "3.4.2",
   "@microsoft/applicationinsights-web": "3.0.1",
  • Node version: 18.5.0

  • created app with Vite using react-ts template

  • How you initialized the SDK:

const browserHistory = createBrowserHistory();
const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
  config: {
    connectionString,
    distributedTracingMode: DistributedTracingModes.W3C,
    enableAutoRouteTracking: true,
    extensions: [reactPlugin as unknown as ITelemetryPlugin],
    extensionConfig: {
      [reactPlugin.identifier]: { history: browserHistory },
    },
  },
});
appInsights.loadAppInsights();

Expected behavior
no crash, app renders

Additional context
Perhaps this is just incompatible versions of applicationinsights-react-js and applicationinsights-web? If I downgrade applicationinsights-web to 2.8.13, the problem goes away. Still, glad I'm entering this so that the next person who encounters it will see this in a search.

Is any version compatible with react 15?

My application run react 15 and I tried to move it to react 16. Used react-codemod but getting errors related to internal dependencies using React.Proptypes.

Is there any version of application insights that can work with react 15?

I have sucessfully sent logs from a demo application to my app insights account using react 16. But when I downgraded version to react 15, It threw similar errors.

TL;DR: I need applicationinsights-react-js to work with react 15

[BUG] Incompatible with react 18

Description/Screenshot

npm WARN Conflicting peer dependency: [email protected]
npm WARN node_modules/react
npm WARN   peer react@"^17.0.1" from @microsoft/[email protected] 
npm WARN   node_modules/@microsoft/applicationinsights-react-js
npm WARN     @microsoft/applicationinsights-react-js@"^3.2.4" from the root project
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: [email protected]
npm WARN Found: [email protected]
npm WARN node_modules/react
npm WARN   react@"^18.0.0" from the root project
npm WARN   6 more (@testing-library/react, react-dom, @compiled/react, ...)
npm WARN 

Steps to Reproduce

  1. Install latest version of react
  2. Install @microsoft/[email protected]

AppInsightsErrorBoundary: Add custom property

Maybe this is already possible?
I would like to add a custom property when the AppInsightsErrorBoundary logs an error to AppInsights.
For example, I would like to add the software version that the error occurred in.

Is this possible by adding a new property to the AppInsightsErrorBoundary?
or should I try to catch the exception, add my version number to it, rethrow, and let it bubble back up to the AppInsightsErrorBoundary?

Finally, is there just just add default properties to TrackException from the config or something?

useTrackEvents skipFirstRun not working properly in React strict mode

When you run your application in development mode and with the strict mode on the skipFirstRun parameter is not working properly. The reason for this is that when the strict mode tries to identifying unsafe lifecycles it will rerender your component making it call the function twice by default. This is not going to happen in production environment, but can be confusing in dev mode.

Steps to Reproduce

  • OS/Browser: Windows/Chrome
  • React Version: 18.2.0

Use the useTrackEvent hook in dev mode with the strict mode on.

Expected behavior
useTrackEvents skipFirstRun parameter works properly in development with strict mode.

Additional context
To prevent this issue, all you need to do is set the firstRun variable back to true, when the hook unmounts. I can create a PR for this if you want.

Thanks!

trackDependencyData method is not exposed via App Insights React SDK when using with React Hooks

Description/Screenshot
I'm using App Insights React SDK in a TypeScript React app to collect application metrics. We use a web worker to send network requests with axios, therefore those requests are not automatically tracked by App Insights. So we decided to collect network request related metrics via Axios interceptors.

Looking at the API reference, I see that there is already a method to collect dependency data manually, which is trackDependencyData. However, when I'm using the React SDK, I cannot access that method.

Steps to Reproduce

  • Initialize app insights via hooks in a React TypeScript app

  • get app insights object using const ai = useAppInsightsContext()

  • try adding ai.trackDependencyData(). The typescript editor will throw an error saying the method is not found.

  • OS/Browser: Mac OS Monterey / Google Chrome

  • SDK Version [e.g. 22]:

    • "@microsoft/applicationinsights-react-js": "^3.3.3",
    • "@microsoft/applicationinsights-web": "^2.8.3",
  • How you initialized the SDK:
    Using the above mentioned packages, as mentioned here

Expected behavior
React SDK should expose a method to manually track dependency data.

Additional context
N/A

[BUG] useTrackMetric doesn't send any data to Application Insights after the latest Teams update (V2)

After the recent Teams update (V2)
applicationinsights-react-js -> useTrackMetric has stopped sending
any data to Application Insights.

That's how I use it in my App:

  1. Custom hook that wraps it:
import { useAppInsightsContext, useTrackMetric } from '@microsoft/applicationinsights-react-js';
import { ICustomProperties } from '@microsoft/applicationinsights-web';

export interface IUseTeamsTrackMetric {
    componentName: string;
    customProperties?: ICustomProperties;
}

type UseTeamsTrackMetricReturnType = () => void;

const useTeamsTrackMetric = ({ componentName, customProperties }: IUseTeamsTrackMetric): UseTeamsTrackMetricReturnType => {
    const appInsights = useAppInsightsContext();
    const trackMetric = useTrackMetric(appInsights, componentName, { ...customProperties, telemetryType: 'frontend' });
    return trackMetric;
};

export default useTeamsTrackMetric;

Examples of use:

export const EmailModal: FC<IEmailModalProps> = ({ isOpen }) => {
    const teamsTrackMetric = useTeamsTrackMetric({ componentName: EMAIL_DRAFT_MODAL_COMPONENT_NAME, customProperties: { event: TELEMETRY_EVENT.LOAD } });

    useEffect(() => {
        if (isOpen) {
            teamsTrackMetric();
        }
    }, [isOpen]);

    return (
        <EmailDialog open={isOpen}>
           <EmailDialogContent>...</EmailDialogContent>
        </EmailDialog>
    );
};

export default EmailModal;

export const EmailDialogContent: FC<IEmailDialogContentProps> = ({ body, onCancel, isLoading, isError, onRefresh }) => {
    const trackCopyToClipboardClick = useTeamsTrackEvent({ eventName: 'Copy to clipboard button', componentName: EMAIL_CONTAINER_COMPONENT_NAME });
    const teamsTrackMetric = useTeamsTrackMetric({ componentName: EMAIL_CONTAINER_COMPONENT_NAME, customProperties: { event: TELEMETRY_EVENT.LOAD } });

    const bodyContentLoaded = !isLoading && !isError && body;

    useEffect(() => {
        if (bodyContentLoaded) {
            teamsTrackMetric();
        }
    }, [bodyContentLoaded]);

    if (isLoading) {
        return <Skeleton onCancel={onCancel} />;
    }

    if (isError) {
        return <Error onTryAgain={onRefresh} />;
    }

    const handleClick = () => {
         ...
        trackCopyToClipboardClick({ eventData: { action: TELEMETRY_ACTION.CLICK }, methodName: 'handleClick' });
        ...
    };

    return (
            <EmailDialogContent>
                <EmailDialogBtn click={handleClick }>...</EmailDialogBtn>
           </EmailDialogContent>
    );
};

[BUG] Error type in AppInsightsErrorBoundary after upgrading to react 18

Description/Screenshot

After I upgrade to react v18 (lib + type). I got the error when starting a react project. The error is from AppInsightsErrorBoundary component. So, I just investigated it's missing children prop in the interface.

Screen Shot 2022-04-13 at 09 43 27

Steps to Reproduce

  1. Upgrade @types/react to "18.0.3".
  2. Upgrade @types/react-dom to "18.0.0".
  3. The error appears.
  • OS/Browser: Chrome 100.0.4896.75
  • SDK Version [e.g. 22]: 3.2.4
  • How you initialized the SDK:

Expected behavior
The error should disappear.

Additional context
Add any other context about the problem here.

[BUG] Events shown twice in App Insights

Description/Screenshot
I don't know if this is the right place for this issue.
I'm using the package to track events, but they end up twice in App Insights

Steps to Reproduce
I've create a codeSandbox to reproduce the issue: https://codesandbox.io/s/react-typescript-forked-jn5wf4?file=/src/App.tsx.
You'll need to add your connection string to try it.
In the network tab, data events are sent once:
image
But on the App Insights, the event is logged twice, with the exact same timestamp:
image

  • OS/Browser: MacOS/Firefox
  • React Version: 17.0.2
  • SDK Version [e.g. 22]: @microsoft/applicationinsights-react-js: v3.4.0 and @microsoft/applicationinsights-web v2.8.9
  • How you initialized the SDK: See the code sandbox

Expected behavior
Events are logged once in App Insights

[BUG] Page view loading time not correct

Description/Screenshot
We are using trackPageView function to upload the page view data into the application insight. Data has been updates as expected but the page loading time seem to be constant for all the pages. Page loading time is not real. We are using react function to create the components. We are not following the class structure.

  • OS/Browser: ALL
  • React Version: 18.2.0
  • SDK Version [e.g. 22]: 17.0.0
  • How you initialized the SDK:
    var reactPlugin = new ReactPlugin();
    var appInsights = new ApplicationInsights({
    config: {
    instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
    extensions: [reactPlugin]
    }
    }
    });
    appInsights.loadAppInsights();

    Expected behavior
    Page view loading time should be actual time.

[BUG] Test fails with invalid hook call when the useAppInsightsContext() is used. (CRA)

Hello, I just run into an issue, where the useAppInsightsContext() hook from "@microsoft/applicationinsights-react-js" makes my tests fail because of Invalid Hook Call error. The error shows up only in tests and the application works fine when served locally or from the build folder.

It's easy to reproduce it by simply making a new create-react-app and then following the official documentation. I've created a demo app here on github, because I can't reproduce the issue in the codesandbox. The issue may be related to CRA itself.

I expect the test to pass, as it works outside of tests.

I've tried every possible suggestion I found in the issues, that seemed even a little related to failing jest or invalid hook call, but nothing works. Maybe I just missed something basic.

I also run into some typing problems when I tried to make the the demo app in typescript as the guide from the documentation uses methods arguments that doesn't fit to method parameter types like appInsights.trackMetric("Component 'MyComponent' is in use");, but it doesn't seems related to this issue.

Thank you very much.

Custom page view names for SPAs

When I use the plugin as documented for a React SPA with router v6, the name for all page views is the page title ("React App" by default). This makes it difficult to track user progress through the application. I was able to solve this using the following telemetry initializer but this doesn't seem very elegant.

appInsights.addTelemetryInitializer((env) => { if(env.baseType === "PageviewData" || env.baseType === "PageviewPerformanceData") { env.baseData.name = window.location.pathname; } });

It would be great for developers to be able to specify how to obtain the page name rather than having to modify it after the fact with a telemetry initializer. Alternatively, if the above approach is the recommended method, adding it to the official documentation would be helpful.

[BUG] AppInsightsErrorBoundary doesn't handle errors from the children components in React 18

Description/Screenshot
AppInsightsErrorBoundary doesn't handle errors from the children components in React 18.

Steps to Reproduce
Use AppInsightsErrorBoundary:

    <AppInsightsErrorBoundary onError={() => <ErrorPage500 />} appInsights={reactPlugin}>
       <SomeComponent />
    </AppInsightsErrorBoundary>
  • Run application in dev mode

  • Use react Chrome plugin to set component to Error state

  • OS/Browser: Chrome

  • React Version: 18

  • SDK Version [e.g. 22]: 3.4.0

  • How you initialized the SDK:

  appInsights.setup(instrumentationKey).setAutoCollectConsole(true, true).start()

Expected behavior
AppInsightsErrorBoundary should catch error state from child components and display provided onError component (e.g. ErrorPage500)

Solution
According to the React 18 documentation: https://reactjs.org/docs/error-boundaries.html
Error boundaries should have getDerivedStateFromError method to avoid recursion:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

And it might look something like this:

export default class AppInsightsErrorBoundary extends React.Component<IAppInsightsErrorBoundaryProps, IAppInsightsErrorBoundaryState> {
    state = { hasError: false };

    static getDerivedStateFromError(): { hasError: boolean } {
        // Update state so the next render will show the fallback UI.
        return { hasError: true }
      }
    
      componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
        reactPlugin.trackException({
          error: error,
          exception: error,
          severityLevel: SeverityLevel.Error,
          properties: errorInfo,
        })
      }

    render() {
        if (this.state.hasError) {
            const { onError } = this.props;
            return React.createElement(onError);
        }

        return this.props.children;
    }
}

AppInsightsErrorBoundary: option to clear hasError (e.g. when using browser back)

Is your feature request related to a problem? Please describe.
I am using the AppInsightsErrorBoundary in App.tsx to display an error page when an error occurs somewhere in the application. This works well. However, when I click the browser back button to return to the previous page, the error component is rendered again. This can only be resolved with a page reload. It seems like the hasError state within the AppInsightsErrorBoundary can never be false.

Describe the solution you'd like
I would like to have the option to toggle the hasError state from the outside or have the AppInsightsErrorBoundary automatically set it to false after rendering.

Describe alternatives you've considered
I tried setting the key attribute of the AppInsightsErrorBoundary to location.pathname to trigger a re-render when the location changes, but it had no effect.

[BUG] Type 'ReactPlugin' is not assignable to type 'ITelemetryPlugin'

A type error similar to issue microsoft/ApplicationInsights-JS#1324 has appeared in the latest versions:
Type 'ReactPlugin' is not assignable to type 'ITelemetryPlugin'.

Versions:

  • @microsoft/applicationinsights-react-js v3.4.0
  • @microsoft/applicationinsights-web v2.8.9

Here's the simplified example from my next.js app:

import { ReactPlugin } from '@microsoft/applicationinsights-react-js';
import {
  ApplicationInsights,
  ITelemetryPlugin,
} from '@microsoft/applicationinsights-web';

const appInsights = new ApplicationInsights({
  config: {
    connectionString: `InstrumentationKey=${process.env.AZURE_INSTURMENTATION_KEY};IngestionEndpoint=https://switzerlandnorth-0.in.applicationinsights.azure.com/;LiveEndpoint=https://switzerlandnorth.livediagnostics.monitor.azure.com/`,
    enableAutoRouteTracking: true,
    extensions: [new ReactPlugin()], // <- error happens here
  },
});

[BUG] `IAppInsights` is incomplete

Description/Screenshot

App Insights does not expose the full interface--

image

Steps to Reproduce

  • OS/Browser: N/A
  • React Version: N/A
  • SDK Version [e.g. 22]: 2.8.6
  • How you initialized the SDK: N/A

Expected behavior
IAppInsights has parity with the core module's interface, or (preferably) reexports the core type directly.

Additional context
I probably wont be able to leverage this library subsequently.

[BUG] 'AppInsightsErrorBoundary' cannot be used as a JSX component.

Description/Screenshot

I have a SPFx 1.16 solution: https://github.com/kkazala/codespaceSPFx created using yo @microsoft/sharepoint
I want to add ErrorBoundary as described here: https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript-react-plugin#react-error-boundaries

I'm getting the following error:

'AppInsightsErrorBoundary' cannot be used as a JSX component.
  Its instance type 'AppInsightsErrorBoundary' is not a valid JSX element.
    Type 'AppInsightsErrorBoundary' is missing the following properties from type 'ElementClass': context, setState, forceUpdate, props, refs

I understand it may be related to the react version, but SPFx requires React v17.0.1 SPFx development environment compatibility

Steps to Reproduce
Repo contains codespace configuration files, please simply create a new codepsace from the repo

  • OS/Browser:
  • React Version: 17.0.1
  • SDK Version [e.g. 22]: 3.4.0
  • How you initialized the SDK:

Expected behavior
I would expect no errors =)

Additional context
I am aware I didn't instantiate ApplicationInsights ;) This is just an example presenting the issue with AppInsightsErrorBoundary.

Cross-site cookies blocking impact

Description

In my Firefox setup, I intentionally enabled "Block all cross-site cookies" option. A similar option named "Prevent cross-site tracking in Safari" is enabled in Safari by default. Google Chrome is planing to do the same mid-2023.

The warning I'm providing to this issue is displayed as a warning only. How cross-site cookies blocking will impact Azure Application Analytics on the web?

Context

OS/Browser: Firefox 115.0.3

React Version: 18.2.0

SDK Version [e.g. 22]: 3.0.2 (@microsoft/applicationinsights-core-js), 17.0.0 (@microsoft/applicationinsights-react-js)

How you initialized the SDK

import {
  AppInsightsContext,
  ReactPlugin,
} from "@microsoft/applicationinsights-react-js";
import { ApplicationInsights } from "@microsoft/applicationinsights-web";

const appInsights = new ApplicationInsights({
  config: {
    connectionString: import.meta.env.VITE_APP_INSIGHTS_CONNECTION_STR,
    extensions: [reactPlugin],
    enableAutoRouteTracking: true,
  },
});
appInsights.loadAppInsights();

Full error

Cookie “” has been rejected as third-party.

Request to access cookie or storage on “https://westeurope-5.in.applicationinsights.azure.com//v2/track” was blocked because we are blocking all third-party storage access requests and content blocking is enabled.

Doesn't appear to be secure

Hi,

On testing this I noticed the following:

From the Network tab it calls https://dc.services.visualstudio.com/v2/track with the instrumentation key in the payload

Which means I can steal these two bits of information and use Postman to directly insert stuff in our insights database..

Which I did

image

Expected behavior
I'd expect that you could lock this down in DevOps with something like a setting to restrict which domains the info came from?

Otherwise someone could skew your analytics/bombard your analytics DB!?

Can you advise?

React plugin Page View on history replace

The React plugin currently tracks a page view every time the history listener is called, even during a page replace. This may not be desirable to those who replace the current page to update page state, since that currently causes a new page view to be tracked.

Could we consider excluding page replaces or adding an option to exclude page replaces from tracking page views?

Tracking api call

I am using telemetry to auto track events in reactjs v18 app. All the api calls are being tracked under dependency section
How to track axios call in the logs > request query i.e. add request tag to it and view in logs > request instead of logs > dependency?

image

[BUG] v17.0.0 Fails to compile with yarn pnp

Description

Failure to compile with yarn pnp:

Failed to compile.

Module not found: Error: Can't resolve '@nevware21/ts-utils' in 'workspace/.yarn/__virtual__/@microsoft-applicationinsights-react-js-virtual-5e2603ec10/0/cache/@microsoft-applicationinsights-react-js-npm-17.0.0-f9df6f3087-3af1cfa49c.zip/node_modules/@microsoft/applicationinsights-react-js/dist-esm'
ERROR in ./.yarn/__virtual__/@microsoft-applicationinsights-react-js-virtual-5e2603ec10/0/cache/@microsoft-applicationinsights-react-js-npm-17.0.0-f9df6f3087-3af1cfa49c.zip/node_modules/@microsoft/applicationinsights-react-js/dist-esm/ReactPlugin.js 13:0-52
Module not found: Error: Can't resolve '@nevware21/ts-utils' in 'workspace/.yarn/__virtual__/@microsoft-applicationinsights-react-js-virtual-5e2603ec10/0/cache/@microsoft-applicationinsights-react-js-npm-17.0.0-f9df6f3087-3af1cfa49c.zip/node_modules/@microsoft/applicationinsights-react-js/dist-esm'

Steps to Reproduce
Minimal reproduction repo: https://github.com/CEOehis/application-insights-yarn-pnp

  • React Version: 17.0.2
  • SDK Versions:
    • @microsoft/applicationinsights-react-js 17.0.0
    • @microsoft/applicationinsights-web 3.0.2

Additional context
@nevware21/ts-utils is referenced in the code but is not specified as a dependency . As a result, yarn pnp is unable to resolve it correctly.

It works with node-modules because @nevware21/ts-utils is also installed with @microsoft/applicationinsights-web.

[BUG] applicationinsights-web is leaking memory in NextJS SSR

Description/Screenshot

image

image

Steps to Reproduce

  • OS/Browser: AppService Container/ Windows 10 (Browser is N/A since leak happens in NextJS nodeJs server)
  • React Version: 18
  • SDK Version [e.g. 22]:
    @microsoft/applicationinsights-react-js: 17.0.1
    @microsoft/applicationinsights-web: 3.0.3
  • NodeJs Version: 18.17.1
  • NextJs Version: 13.5.2
  • How you initialized the SDK:
import {ApplicationInsights, ITelemetryItem} from '@microsoft/applicationinsights-web';
import {ReactPlugin} from '@microsoft/applicationinsights-react-js';

const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
 config: {
   connectionString: "instrumentationKey=test",
   extensions: [reactPlugin],
   enableAutoRouteTracking: true,
   disableAjaxTracking: false,
   autoTrackPageVisitTime: true,
   enableCorsCorrelation: true,
   enableRequestHeaderTracking: true,
   enableResponseHeaderTracking: true,
 }
});
appInsights.loadAppInsights();

appInsights.addTelemetryInitializer((env:ITelemetryItem) => {
   env.tags = env.tags || [];
   env.tags["ai.cloud.role"] = "testTag";
});

export { reactPlugin, appInsights };

Heap Snapshots for analysis in Chrome:
heapsnaps.zip

Min repo:

https://github.com/mauron85/react-appinsights

Install clinic.js and autocannon for testing:

npm install -g autocannon
npm install -g clinic

Build example app:

npm run build
cd .next/
cd .\.next\standalone\
clinic doctor -- node server.js

test load:

autocannon -c 100 -d 600 http://127.0.0.1:3000/

Autocannon will run 100 concurrent connections for 10 min.
After 10min CTRL+C to to stop server and clinicjs will generate mem usage report.

Expected behavior

Memory is not leaking

Additional context

App is constantly leaking memory on server side NextJS server. After removal of appinsights, memory consumption is flat.

image

In real world app, effect is applified greatly.

MicrosoftTeams-image

Tasks

No tasks being tracked yet.

[BUG] Typing issue with @microsoft/applicationinsights-web v2.7.0

Description/Screenshot

It seems that after the release of the @microsoft/applicationinsights-web v2.7.1 - apps with version v2.7.0 and TypeScript not working correctly anymore.

TS2322: Type 'ReactPlugin' is not assignable to type 'ITelemetryPlugin'.

Steps to Reproduce

Simple library with following deps:

"dependencies": {
    "@microsoft/applicationinsights-react-js": "3.0.5",
    "@microsoft/applicationinsights-web": "2.7.0",
    "axios": "0.21.1",
    "qs": "6.9.1",
    "reflect-metadata": "0.1.13"
  },

Initialize app:

this.pluginInstance = new ReactPlugin();
this.insightsInstance = new ApplicationInsights({
      config: {
        instrumentationKey,
        disableFetchTracking: false,
        enableRequestHeaderTracking: true,
        enableResponseHeaderTracking: true,
        extensions: [this.pluginInstance],
      },
    });

this.insightsInstance.loadAppInsights();
  • OS/Browser: Windows
  • SDK Version [e.g. 22]:
  • How you initialized the SDK: NPM

Expected behavior

No breaking changes in typing between patches of the library.

Additional context
Add any other context about the problem here.

[Documentation] Include common react usecases.

I have cruised the documentation, but I still feel like I haven't get the full picture of the use cases and ways to integrate the plugin besides the default initialization.

Specifically, I'm interested in recommendations and common use cases for any additional methods calls beyond the default initialization.

  • For example, is it sufficient to enable enableAutoRouteTracking, or should withAITracking still be implemented for each high level page?
  • what events are send when enableAutoRouteTracking is enabled compared to when withAITracking is enabled?
  • What autoTrackPageVisitTime offers in comparison to withAITracking and which of the two is preferable?
  • Can you list a common usecases when it would be interesting to call other methods explicitly provided by the library (also avoiding sending telemetry that already collected by enableAutoRouteTracking, autoTrackPageVisitTime and withAITracking :
appInsights.trackEvent({name: 'some event'});
appInsights.trackPageView({name: 'some page'});
appInsights.trackPageViewPerformance({name : 'some page', url: 'some url'});
appInsights.trackException({exception: new Error('some error')});
appInsights.trackTrace({message: 'some trace'});
appInsights.trackMetric({name: 'some metric', average: 42});
appInsights.trackDependencyData({absoluteUrl: 'some url', responseCode: 200, method: 'GET', id: 'some id'});
appInsights.startTrackPage("pageName");
appInsights.stopTrackPage("pageName", null, {customProp1: "some value"});
appInsights.startTrackEvent("event");
appInsights.stopTrackEvent("event", null, {customProp1: "some value"});

Thank you in advance!

[BUG] Sample App - link update

Description/Screenshot

Hello team 👋,

Regarding the Sample App section:

image

❓ I am just wondering if the link should point to the same repo

Instead of referencing the 5+ years old repo:

https://github.com/Azure-Samples/application-insights-react-demo

image

Thx!

Steps to Reproduce

  • OS/Browser:
  • React Version:
  • SDK Version [e.g. 22]:
  • How you initialized the SDK:

Expected behavior

Additional context
Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.