Instrument browser/web apps with @microsoft/applicationinsights-web for Real User Monitoring (RUM), page views, clicks, AJAX/fetch dependencies, exceptions, custom events, and browser-side GenAI agent traces. Use when adding App Insights to React, Angular, Vite, Next.js, or React Native frontends. Not for Node.js server OpenTelemetry (azure-monitor-opentelemetry-ts).
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
Instrument browser/web apps with @microsoft/applicationinsights-web for Real User Monitoring (RUM), page views, clicks, AJAX/fetch dependencies, exceptions, custom events, and browser-side GenAI agent traces. Use when adding App Insights to React, Angular, Vite, Next.js, or React Native frontends. Not for Node.js server OpenTelemetry (azure-monitor-opentelemetry-ts).
Application Insights JavaScript SDK (Web) for TypeScript
When to Use
Use this skill when you need to 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 spans via W3C Trace Context.
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.
Windows host (PowerShell) is primary. All shell commands below are PowerShell-compatible.
Procedure
1. Install Packages
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.
User Timing (performance.mark/measure) integration.
2. Expose Connection String to Client
# Vite / CRA / Next.js — expose to client via the public env prefix
$env:VITE_APPINSIGHTS_CONNECTION_STRING="InstrumentationKey=YOUR_KEY;IngestionEndpoint=https://...;LiveEndpoint=https://..."
$env:NEXT_PUBLIC_APPINSIGHTS_CONNECTION_STRING="InstrumentationKey=YOUR_KEY"
HARD RULE: 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.
<scripttype="text/javascript"src="https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js"crossorigin="anonymous"></script><scripttype="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>
Mark elements with data-ai-* attributes; clicks are emitted as Custom Events with parent-content metadata.
8. SPA Route Tracking
Built-in: set enableAutoRouteTracking: true. Hooks history.pushState/replaceState and popstate.
React Router: use @microsoft/applicationinsights-react-jswithAITracking HOC. Use the React recipe in this file (step 11) and Microsoft Learn for Angular, Next.js, or Vite plugins.
Manual: call appInsights.trackPageView({ name, uri }) in your router's useEffect on route change. Disable enableAutoRouteTracking to avoid double counting.
9. 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.
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.
Set the opt-in env first so backend instrumentations agree on the same schema version:
HARD RULE — 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.
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)
11. React (TypeScript)
React and React Native recipes follow in this file. For Angular/Next/Vite plugins, use the official packages listed in step 1 and Microsoft Learn.
Per-type sampling via telemetry initializer: drop with return false based on item.baseType.
16. 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).
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.
Verification
Check SDK loaded in browser console:
// Should return the ApplicationInsights instance, not undefinedconsole.log(window.appInsights ?? appInsights);
Verify telemetry is flowing — open the App Insights portal > Transaction Search, or run KQL in Log Analytics:
pageViews
| where timestamp > ago(10m)
| summarize count() by name
Verify GenAI traces:
dependencies
| where type == "GenAI"
| where timestamp > ago(10m)
| project timestamp, name, duration, customDimensions["gen_ai.operation.name"], customDimensions["gen_ai.agent.name"]
Verify distributed tracing correlation — check that backend dependency telemetry shares the same operation_Id as the browser page view:
pageViews
| where timestamp > ago(10m)
| join kind=inner (dependencies | where type == "Fetch") on operation_Id
| project operation_Id, name, type
Bundle size check — the full web SDK is ~110 KB minified (~36 KB gzipped). For aggressive budgets, use the Loader Script path or tree-shake unused plugins.
GenAI attribute tables, React/RN recipes, and IConfiguration knobs used in this file (steps 3, 10–11, 14–15). This folder does not ship a references pack.
Limitations
Use this skill only when the task clearly matches its upstream source and local project context.
Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.