Philip Claren
Philip Claren

Reputation: 2896

Problems with axios and Azure Application Insights

The NPM package @microsoft/applicationinsights-we from microsoft when used in the frontend will add headers for tracking calls across different parts of the application (e.g. frontend, backend, services etc.).

I'm using axios in the frontend which out of the box does not work with the package. Neither disableFetchTracking:false nor disableAjaxTracking:false works. I don't want to replace axios with fetch, because axios is more convenient to use and this would be a lot of rewrite too.

What can I do?

Upvotes: 2

Views: 1662

Answers (1)

Łukasz Wiśniewski
Łukasz Wiśniewski

Reputation: 111

The @microsoft/applicationinsights-web package does inject correlation headers into axios calls (by instrumenting XMLHttpRequest). There might be a few causes of the problem in your application:

Another library broke the instrumentation

Something else might be hijacking the XMLHttpRequest object and affecting the AppInsights instrumentation. One such library is pace.js, which overwrites the window.XMLHttpRequest constructor but does not add open, send and abort to it's prototype. AppInsights expects these functions to be present on the XMLHttpRequest's prototype: https://github.com/microsoft/ApplicationInsights-JS/blob/91f08a1171916a1bbf14c03a019ebd26a3a69b86/extensions/applicationinsights-dependencies-js/src/ajax.ts#L330

Here is a working axios + @microsoft/applicationinsights-web example:

Edit axios-appinsights

Here is the same example, but with pace.js loaded - the Request-Id header is not added:

Edit axios-appinsights-pace

Either removing pace.js or placing it's script tag / import after the AppInsights initialization code should fix the problem.

Cross-origin requests

Another explanation might be that the frontend app is making cross-origin requests, which are not processed by AppInsights by default - the enableCorsCorrelation: true config setting is needed.

Upvotes: 5

Related Questions