How to pass history to App Insights with React Router 6

Viewed 624

Azure App Insights recommends using their react plugin for SPAs. https://docs.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?

1 Answers

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.

Related