Application Insights JavaScript SDK (Web) for TypeScript
Real User Monitoring (RUM) for browser apps with @microsoft/applicationinsights-web. Auto-collects page views, AJAX/fetch dependencies, unhandled exceptions, and (with the Click Analytics plugin) clicks. Supports custom events, metrics, and GenAI agent traces that follow OpenTelemetry GenAI semantic conventions and correlate to backend spans via W3C Trace Context.
Distinct from
azure-monitor-opentelemetry-ts, which is for Node.js server apps. This skill is for browser/web code (and React Native).
Before Implementation
Search microsoft-docs MCP for current API patterns:
- Query: "Application Insights JavaScript SDK setup"
- Query: "Application Insights JavaScript SDK configuration"
- Query: "Application Insights JavaScript framework extensions React Angular"
- Verify package version:
npm view @microsoft/applicationinsights-web version
Packages
Installation
Typings ship with the package — no separate @types/... install needed.
Connection String
The browser SDK requires a connection string at init time. It ships in plaintext to clients — Microsoft Entra ID auth is not supported for browser telemetry. Use a separate App Insights resource with local auth enabled for browser RUM if you need to isolate it from backend telemetry.
Quick Start (npm)
Call loadAppInsights() exactly once, as early as possible (before user interactions you want tracked). Then trackPageView() for the initial load — when enableAutoRouteTracking is on, subsequent route changes are automatic.
Quick Start (SDK Loader Script)
Recommended when you want auto-updating SDK and zero build pipeline. Paste this as the first <script> in <head>:
Loader-only API (queued until SDK loads): trackEvent, trackPageView, trackException, trackTrace, trackDependencyData, trackMetric, trackPageViewPerformance, startTrackPage, stopTrackPage, startTrackEvent, stopTrackEvent, addTelemetryInitializer, setAuthenticatedUserContext, clearAuthenticatedUserContext, flush.
Core Tracking APIs
Telemetry Initializers (enrichment & filtering)
Run for every envelope before send. Return false to drop.
Click Analytics
Mark elements with data-ai-* attributes; clicks are emitted as Custom Events with parent-content metadata.
SPA Route Tracking
- Built-in: set
enableAutoRouteTracking: true. Hookshistory.pushState/replaceStateandpopstate. - React Router: use
@microsoft/applicationinsights-react-jswithAITrackingHOC (see references/framework-extensions.md [blocked]). - Manual: call
appInsights.trackPageView({ name, uri })in your router'suseEffecton route change. DisableenableAutoRouteTrackingto avoid double counting.
Distributed Tracing (correlate to backend)
Set distributedTracingMode: 2 (DistributedTracingModes.AI_AND_W3C). The SDK adds traceparent (and legacy Request-Id) to outbound fetch/XHR. Backends instrumented with OpenTelemetry (e.g. @azure/monitor-opentelemetry) auto-link to the browser's operation_Id.
For cross-origin calls, also set enableCorsCorrelation: true and add the calling origin to the CORS exposed headers on the API.
GenAI Agent Traces (OTel semantic conventions)
When the browser invokes an AI agent (function-calling, tool-use, model calls direct from the client), emit App Insights Dependency telemetry whose attributes follow the OpenTelemetry GenAI semantic conventions so they are queryable alongside backend agent spans in App Insights / Log Analytics.
Set the opt-in env first so backend instrumentations agree on the same schema version:
Required attribute keys (use the OTel names verbatim)
gen_ai.provider.name well-known values: openai, azure.ai.openai, azure.ai.inference, anthropic, aws.bedrock, gcp.gemini, gcp.vertex_ai, cohere, mistral_ai, groq, deepseek, perplexity, x_ai, ibm.watsonx.ai.
Sensitive content opt-in.
gen_ai.system_instructions,gen_ai.input.messages,gen_ai.output.messages,gen_ai.tool.call.arguments,gen_ai.tool.call.resultare Opt-In by default. Gate them behind a runtime flag and avoid them in production unless you have approved data handling.
Pattern: invoke_agent + nested tool/model spans
The browser's traceparent is automatically attached to outbound fetch (when distributedTracingMode: 2), so downstream Azure OpenAI / agent backend spans hang under the same operation_Id in App Insights.
For the full attribute reference, well-known values, and content-capture guidance, see references/agent-traces.md [blocked].
KQL: query GenAI traces in App Insights
React (TypeScript)
See references/framework-extensions.md [blocked] for full React, React Native, Angular, Next.js, and Vite recipes.
React Native
Performance — Web Vitals
Auto-collected: page-load timings via PerformanceTiming / PerformanceNavigationTiming. To add Core Web Vitals:
Cookies & Privacy
To honor consent dynamically:
Sampling
Server-side ingestion sampling (recommended) is configured on the App Insights resource. SDK-side sampling reduces network use:
Per-type sampling via telemetry initializer: drop with return false based on item.baseType.
Offline / Send-on-Unload
The SDK uses sendBeacon (default onunloadDisableBeacon: false) to flush on pagehide / unload. For SPAs, also call appInsights.flush() before destructive transitions (logout, hard reload).
Common Pitfalls
- Do not initialize twice. Re-importing the module under different bundles produces duplicate page views. Use a single shared module export.
- Initialize before first user input to avoid losing early clicks/exceptions.
- Connection string is public — never reuse the same App Insights resource for backend secrets.
enableAutoRouteTracking+ manualtrackPageView= duplicates. Pick one.- CORS distributed tracing requires the API to allow
Request-Id,Request-Context,traceparent,tracestaterequest headers and exposeRequest-Contextresponse header. - GenAI sensitive content (
gen_ai.input.messagesetc.) is Opt-In — never log without an explicit runtime flag and approved data handling. - Agent token usage is on
chatspans, notinvoke_agent— copy aggregated usage to the parent agent span only if you know it. - React StrictMode double-invokes effects in dev — guard
loadAppInsights()with a module-level singleton.
Bundle Size
The full web SDK is ~110 KB minified (~36 KB gzipped). For aggressive budgets, use the Loader Script path so the SDK loads asynchronously off the critical path, or tree-shake unused plugins.
Key Types
Best Practices
- One singleton instance exported from a single module.
- Initialize early in the app entrypoint, before router setup.
- Use telemetry initializers to attach
app.version,tenantId, and to scrub PII / query-string secrets. - Set
distributedTracingMode: 2and ensure your APIs accept/expose W3C trace context headers. - For GenAI, follow OTel
gen_ai.*attribute names verbatim — they are queryable across browser and backend telemetry uniformly. - Gate sensitive content capture (
gen_ai.input.messages/gen_ai.output.messages) behind a build-time or runtime opt-in. - Flush on logout / sensitive navigation so in-flight telemetry isn't dropped.
References
- references/agent-traces.md [blocked] — Full OTel GenAI semconv distilled (agent / model / tool spans, attributes, content capture).
- references/framework-extensions.md [blocked] — React, React Native, Angular, Next.js, Vite recipes.
- references/configuration.md [blocked] — Full
IConfigurationreference and tuning guide. - Microsoft Learn: https://learn.microsoft.com/azure/azure-monitor/app/javascript-sdk
- ApplicationInsights-JS source: https://github.com/microsoft/ApplicationInsights-JS
- OTel GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/

