7

Azure App Insights recommends using their react plugin for SPAs. https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript-react-plugin

In the documented example, they manually create a browser history to pass to the extension.

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

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

However, I'm using react router 6, which I assume creates its own browser history. The documentation does make reference to the react router documentation, however, this is for react router 5, which does expose the history directly.

With react router 6, what would be the right way to access to the history created by the router?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
cgat
  • 3,689
  • 4
  • 24
  • 38
  • Does this answer your question? [react router v6 navigate outside of components](https://stackoverflow.com/questions/69871987/react-router-v6-navigate-outside-of-components) – Drew Reese Feb 02 '22 at 03:24

2 Answers2

4

This issue is discussed in great length on the following pull request [v6] Add <HistoryRouter> for standalone history objects. At a high-level, it should allow you to create a Router object with an external history object similar to the v5 documentation.

Currently, you best bet is to import the HistoryRouter component from the pull request into your own project so you can create and use an standalone history object for app insights.

Tim Edgar
  • 2,143
  • 14
  • 11
2

I found the documentation through this question so thought it might be worth mentioning here that it has been updated to specifically address react-router v6:

https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript-react-plugin

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

As per this github issue, page view duration data is lost as a result.

Dave
  • 457
  • 4
  • 15