I have an Angular project and I want to use Application Insights for logging.
I have tried this tutorial and it works just fine, but not in SSR mode.
When I'm running the application in SSR mode, I get this error:
RerefenceError: XmlHttpRequest is not defined
I've found this SO post, which seems to be the same problem as mine. Following one of its answers, I've installed XMLHttpRequest
library and added this line to server.ts
:
(global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
Not working for me. Angular Universal is not responding to http requests yet. Also, I tried to use the 'xhr2' library instead of 'xmlhttprequest`, it didn't work either.
How can I have application insights to work in Angular SSR mode?
More Detail
This is how I added Application insights to my project.
monitoring.service.ts
: a wrapper for ai
APIs:
import { ApplicationInsights } from "@microsoft/applicationinsights-web";
class MonitoringService {
private appInsights: ApplicationInsights;
constructor(@Inject(PLATFORM_ID) private platformId) {
this.appInsights = new ApplicationInsights({
config: {
instrumentationKey: environment.appInsights.instrumentationKey,
},
});
this.appInsights.loadAppInsights();
// from documentation: https://learn.microsoft.com/en-us/azure/azure- monitor/app/javascript#npm-based-setup:
this.appInsights.trackPageView();
}
logException(exception: Error, severityLevel?: number) {
if (isPlatformBrowser(this.platformId)) {
this.appInsights.trackException({
exception: exception,
severityLevel: severityLevel,
});
}
}
}
And then called the initialization codes of ai
at app.component.ts
like this:
import { MonitoringService } from "@shr/services/monitoring.service";
export class AppComponent {
constructor(
private appInsightsService: MonitoringService,
@Inject(PLATFORM_ID) private platformId
) {
this.appInsightsService.startMonitoring();
}
}
UPDATE:
I made it work by surrounding all the method calls related to application insights api, such as trackException()
and this.appInsights.loadAppInsights()
within an if statememt:
if (isPlatformBrower(platformId)) {
// call an api of application insights...
this.appInights.trackException();
}
Using this workaround, I guess none of the exceptions thrown on the server (Angular Universal Server, which is express
in my case) can be captured by Application Insights. Because the global error handler, calls ai API only if the platform is a browser. What happens if some code being run outside of the browser throws an exception? Is there any way to capture such exception and write it to ai, at some time later when we are back to browser platform?