This source did not publish a separate summary. Review SKILL.md before using the skill.
SKILL.md
Application Insights JavaScript SDK (Web) for TypeScript
When to Use
Use this skill when you need instrument browser/web apps with the Application Insights JavaScript SDK (@microsoft/applicationinsights-web). Use for Real User Monitoring (RUM) — page views, clicks, AJAX/fetch dependencies, exceptions, custom events, and browser-side GenAI agent traces correlated to backend...
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:
User Timing (performance.mark/measure) integration.
Installation
npm i --save @microsoft/applicationinsights-web
# Optional plugins (install only what you use):
npm i --save @microsoft/applicationinsights-clickanalytics-js
npm i --save @microsoft/applicationinsights-react-js @microsoft/applicationinsights-react-native @microsoft/applicationinsights-angularplugin-js
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.
# Vite / CRA / Next.js — expose to client via the public env prefix
VITE_APPINSIGHTS_CONNECTION_STRING="InstrumentationKey=...;IngestionEndpoint=https://...;LiveEndpoint=https://..."
NEXT_PUBLIC_APPINSIGHTS_CONNECTION_STRING="InstrumentationKey=..."
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>:
<script type="text/javascript" src="https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js" crossorigin="anonymous"></script>
<script type="text/javascript">
var appInsights = window.appInsights || function (cfg) {
/* See: https://learn.microsoft.com/azure/azure-monitor/app/javascript-sdk
Use the latest snippet from the Microsoft Learn page above — it includes
backup-CDN failover (cr), SDK-load-failure reporting, and the queue shim
so calls before SDK ready are not lost. */
}({ src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
crossOrigin: "anonymous",
cfg: { connectionString: "YOUR_CONNECTION_STRING" } });
</script>
Manual: call appInsights.trackPageView({ name, uri }) in your router's useEffect on route change. Disable enableAutoRouteTracking to 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:
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.result are Opt-In by default. Gate them behind a runtime flag and avoid them in production unless you have approved data handling.
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.
KQL: query GenAI traces in App Insights
dependencies
| where type == "GenAI"
| extend op = tostring(customDimensions["gen_ai.operation.name"]),
agent = tostring(customDimensions["gen_ai.agent.name"]),
model = tostring(customDimensions["gen_ai.request.model"]),
tin = toint(customDimensions["gen_ai.usage.input_tokens"]),
tout = toint(customDimensions["gen_ai.usage.output_tokens"])
| summarize calls=count(), p95_ms=percentile(duration, 95),
avg_in=avg(tin), avg_out=avg(tout) by op, agent, model, bin(timestamp, 5m)
Server-side ingestion sampling (recommended) is configured on the App Insights resource. SDK-side sampling reduces network use:
new ApplicationInsights({ config: { connectionString, samplingPercentage: 50 } });
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.
CORS distributed tracing requires the API to allow Request-Id, Request-Context, traceparent, tracestate request headers and expose Request-Context response header.
GenAI sensitive content (gen_ai.input.messages etc.) is Opt-In — never log without an explicit runtime flag and approved data handling.
Agent token usage is on chat spans, not invoke_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
import {
ApplicationInsights,
SeverityLevel,
DistributedTracingModes,
type IConfiguration,
type IConfig,
type ITelemetryItem,
type ITelemetryPlugin,
type ICustomProperties,
type IPageViewTelemetry,
type IEventTelemetry,
type IExceptionTelemetry,
type ITraceTelemetry,
type IMetricTelemetry,
type IDependencyTelemetry
} from "@microsoft/applicationinsights-web";
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: 2 and 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 — Full OTel GenAI semconv distilled (agent / model / tool spans, attributes, content capture).