[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69AV8NP7E01WANWMC87SWQV":3,"skill-same:01M69AV8NP7E01WANWMC87SWQV":106},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":34,"publishedAt":60,"linkOnly":61,"markdownContent":62,"markdownBody":63,"frontMatter":64,"refName":68,"commitSha":69,"skillDirectory":70,"forksCount":71,"repositoryHtmlUrl":72,"repositoryHomepageUrl":73,"ownerHtmlUrl":74,"ownerBlogUrl":75,"ownerDescription":76,"updatedAt":77,"install":78,"resources":91},"01M69AV8NP7E01WANWMC87SWQV","applicationinsights-web-ts",null,"Instrument browser\u002Fweb apps with the Application Insights JavaScript SDK (@microsoft\u002Fapplicationinsights-web). Use for Real User Monitoring (RUM) — page views, clicks, AJAX\u002Ffetch dependencies, exceptions, custom events, and browser-side GenAI agent traces correlated to backend OpenTelemetry traces. Covers SDK Loader Script and npm setup, framework extensions (React, React Native, Angular), Click Analytics, telemetry initializers, and OTel GenAI semantic conventions for agent\u002Ftool\u002Fmodel spans emitted from the browser.","microsoft\u002Fskills","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69AJYYW4E1RMSYCQDJ4FJSH",3195,"MIT","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fapplicationinsights-web-ts\u002FSKILL.md",[18,23,26,29],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":30,"categoryName":31,"taxonomyType":32,"taxonomyTypeDesc":33},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,9,58,59],"web","applicationinsights web ts","monitoring","for","insights","javascript sdk","native","events","apps","click","react native","fetch","model","angular","OpenTelemetry","genai","framework","browser","analytics","setup","telemetry","otel","react","javascript","sdk","2026-11-10 10:12:30",false,"---\nname: applicationinsights-web-ts\ndescription: Instrument browser\u002Fweb apps with the Application Insights JavaScript SDK (@microsoft\u002Fapplicationinsights-web). Use for Real User Monitoring (RUM) — page views, clicks, AJAX\u002Ffetch dependencies, exceptions, custom events, and browser-side GenAI agent traces correlated to backend OpenTelemetry traces. Covers SDK Loader Script and npm setup, framework extensions (React, React Native, Angular), Click Analytics, telemetry initializers, and OTel GenAI semantic conventions for agent\u002Ftool\u002Fmodel spans emitted from the browser.\nlicense: MIT\nmetadata:\n  author: Microsoft\n  version: \"1.0.0\"\n  package: \"@microsoft\u002Fapplicationinsights-web\"\n---\n\n# Application Insights JavaScript SDK (Web) for TypeScript\n\nReal User Monitoring (RUM) for browser apps with `@microsoft\u002Fapplicationinsights-web`. Auto-collects page views, AJAX\u002Ffetch 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.\n\n> **Distinct from `azure-monitor-opentelemetry-ts`**, which is for Node.js server apps. This skill is for **browser\u002Fweb** code (and React Native).\n\n## Before Implementation\n\nSearch `microsoft-docs` MCP for current API patterns:\n\n- Query: \"Application Insights JavaScript SDK setup\"\n- Query: \"Application Insights JavaScript SDK configuration\"\n- Query: \"Application Insights JavaScript framework extensions React Angular\"\n- Verify package version: `npm view @microsoft\u002Fapplicationinsights-web version`\n\n## Packages\n\n| Package | Purpose |\n| --- | --- |\n| `@microsoft\u002Fapplicationinsights-web` | Core RUM SDK (page views, AJAX, exceptions). |\n| `@microsoft\u002Fapplicationinsights-clickanalytics-js` | Auto-collect click telemetry. |\n| `@microsoft\u002Fapplicationinsights-react-js` | React plugin (router instrumentation, hooks, HOC, ErrorBoundary). |\n| `@microsoft\u002Fapplicationinsights-react-native` | React Native plugin (native crashes, sessions). |\n| `@microsoft\u002Fapplicationinsights-angularplugin-js` | Angular plugin (router events, ErrorHandler). |\n| `@microsoft\u002Fapplicationinsights-debugplugin-js` | Dev-only telemetry inspector. |\n| `@microsoft\u002Fapplicationinsights-perfmarkmeasure-js` | User Timing (`performance.mark\u002Fmeasure`) integration. |\n\n## Installation\n\n```bash\nnpm i --save @microsoft\u002Fapplicationinsights-web\n# Optional plugins (install only what you use):\nnpm i --save @microsoft\u002Fapplicationinsights-clickanalytics-js\nnpm i --save @microsoft\u002Fapplicationinsights-react-js @microsoft\u002Fapplicationinsights-react-native @microsoft\u002Fapplicationinsights-angularplugin-js\n```\n\nTypings ship with the package — no separate `@types\u002F...` install needed.\n\n## Connection String\n\nThe 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.\n\n```bash\n# Vite \u002F CRA \u002F Next.js — expose to client via the public env prefix\nVITE_APPINSIGHTS_CONNECTION_STRING=\"InstrumentationKey=...;IngestionEndpoint=https:\u002F\u002F...;LiveEndpoint=https:\u002F\u002F...\"\nNEXT_PUBLIC_APPINSIGHTS_CONNECTION_STRING=\"InstrumentationKey=...\"\n```\n\n## Quick Start (npm)\n\n```typescript\nimport { ApplicationInsights } from \"@microsoft\u002Fapplicationinsights-web\";\n\nexport const appInsights = new ApplicationInsights({\n  config: {\n    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,\n    enableAutoRouteTracking: true,        \u002F\u002F SPA route changes -> page views\n    enableCorsCorrelation: true,          \u002F\u002F propagate Request-Id \u002F traceparent to cross-origin AJAX\n    enableRequestHeaderTracking: true,\n    enableResponseHeaderTracking: true,\n    distributedTracingMode: 2,            \u002F\u002F DistributedTracingModes.AI_AND_W3C — emit traceparent for backend correlation\n    autoTrackPageVisitTime: true,\n    disableFetchTracking: false,          \u002F\u002F fetch() is auto-instrumented by default\n    excludeRequestFromAutoTrackingPatterns: [\u002Flivemetrics\\.azure\\.com\u002Fi]\n  }\n});\n\nappInsights.loadAppInsights();\nappInsights.trackPageView();\n```\n\nCall `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.\n\n## Quick Start (SDK Loader Script)\n\nRecommended when you want auto-updating SDK and zero build pipeline. Paste this as the **first** `\u003Cscript>` in `\u003Chead>`:\n\n```html\n\u003Cscript type=\"text\u002Fjavascript\" src=\"https:\u002F\u002Fjs.monitor.azure.com\u002Fscripts\u002Fb\u002Fai.3.gbl.min.js\" crossorigin=\"anonymous\">\u003C\u002Fscript>\n\u003Cscript type=\"text\u002Fjavascript\">\n  var appInsights = window.appInsights || function (cfg) {\n    \u002F* See: https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fazure-monitor\u002Fapp\u002Fjavascript-sdk\n       Use the latest snippet from the Microsoft Learn page above — it includes\n       backup-CDN failover (cr), SDK-load-failure reporting, and the queue shim\n       so calls before SDK ready are not lost. *\u002F\n  }({ src: \"https:\u002F\u002Fjs.monitor.azure.com\u002Fscripts\u002Fb\u002Fai.3.gbl.min.js\",\n      crossOrigin: \"anonymous\",\n      cfg: { connectionString: \"YOUR_CONNECTION_STRING\" } });\n\u003C\u002Fscript>\n```\n\nLoader-only API (queued until SDK loads): `trackEvent`, `trackPageView`, `trackException`, `trackTrace`, `trackDependencyData`, `trackMetric`, `trackPageViewPerformance`, `startTrackPage`, `stopTrackPage`, `startTrackEvent`, `stopTrackEvent`, `addTelemetryInitializer`, `setAuthenticatedUserContext`, `clearAuthenticatedUserContext`, `flush`.\n\n## Core Tracking APIs\n\n```typescript\n\u002F\u002F Page views (SPAs that disable enableAutoRouteTracking)\nappInsights.trackPageView({ name: \"Checkout\", uri: \"\u002Fcheckout\", properties: { cartSize: 3 } });\n\n\u002F\u002F Custom events (user actions, business events)\nappInsights.trackEvent({ name: \"PurchaseCompleted\" }, { orderId: \"ord_123\", amountUsd: 49.95 });\n\n\u002F\u002F Exceptions (caught errors)\ntry {\n  await pay(order);\n} catch (err) {\n  appInsights.trackException({ exception: err as Error, severityLevel: 3, properties: { orderId: order.id } });\n}\n\n\u002F\u002F Traces (logs, severity 0=Verbose, 1=Info, 2=Warning, 3=Error, 4=Critical)\nappInsights.trackTrace({ message: \"Cart hydrated from local storage\", severityLevel: 1 });\n\n\u002F\u002F Custom metrics (numeric)\nappInsights.trackMetric({ name: \"checkout.duration_ms\", average: 1234 });\n\n\u002F\u002F Dependencies (manually-tracked outbound calls — fetch\u002FXHR are auto-tracked)\nappInsights.trackDependencyData({\n  id: crypto.randomUUID(),\n  name: \"GET \u002Fapi\u002Forders\",\n  duration: 87, success: true, responseCode: 200,\n  data: \"https:\u002F\u002Fapi.example.com\u002Fapi\u002Forders\", target: \"api.example.com\", type: \"Fetch\"\n});\n\n\u002F\u002F User identity (set ONCE per authenticated session — values are PII; do not pass emails)\nappInsights.setAuthenticatedUserContext(\"user-id-123\", \"tenant-456\", \u002F*storeInCookie*\u002F true);\nappInsights.clearAuthenticatedUserContext(); \u002F\u002F on logout\n\n\u002F\u002F Force send before unload\nappInsights.flush();\n```\n\n## Telemetry Initializers (enrichment & filtering)\n\nRun for every envelope before send. Return `false` to drop.\n\n```typescript\nimport type { ITelemetryItem } from \"@microsoft\u002Fapplicationinsights-web\";\n\nappInsights.addTelemetryInitializer((item: ITelemetryItem) => {\n  item.tags ??= {};\n  item.tags[\"ai.cloud.role\"] = \"web-shop\";\n  item.tags[\"ai.cloud.roleInstance\"] = window.location.hostname;\n  item.data ??= {};\n  item.data[\"app.version\"] = import.meta.env.VITE_APP_VERSION;\n  item.data[\"app.build\"] = import.meta.env.VITE_BUILD_SHA;\n\n  \u002F\u002F Drop noisy health-check page views\n  if (item.baseType === \"PageviewData\" && item.baseData?.uri?.endsWith(\"\u002Fhealthz\")) return false;\n\n  \u002F\u002F Scrub query-string secrets\n  if (item.baseData?.uri) {\n    item.baseData.uri = item.baseData.uri.replace(\u002F([?&](token|sig|key)=)[^&]+\u002Fgi, \"$1REDACTED\");\n  }\n});\n```\n\n## Click Analytics\n\n```typescript\nimport { ClickAnalyticsPlugin } from \"@microsoft\u002Fapplicationinsights-clickanalytics-js\";\n\nconst clickPlugin = new ClickAnalyticsPlugin();\nconst appInsights = new ApplicationInsights({\n  config: {\n    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,\n    extensions: [clickPlugin],\n    extensionConfig: {\n      [clickPlugin.identifier]: {\n        autoCapture: true,\n        dataTags: { useDefaultContentNameOrId: true, customDataPrefix: \"data-ai-\" },\n        urlCollectHash: false,\n        behaviorValidator: (b: string) => \u002F^[a-z0-9_]+$\u002F.test(b) ? b : \"\"\n      }\n    }\n  }\n});\nappInsights.loadAppInsights();\n```\n\nMark elements with `data-ai-*` attributes; clicks are emitted as Custom Events with parent-content metadata.\n\n## SPA Route Tracking\n\n- **Built-in:** set `enableAutoRouteTracking: true`. Hooks `history.pushState\u002FreplaceState` and `popstate`.\n- **React Router:** use `@microsoft\u002Fapplicationinsights-react-js` `withAITracking` HOC (see [references\u002Fframework-extensions.md](references\u002Fframework-extensions.md)).\n- **Manual:** call `appInsights.trackPageView({ name, uri })` in your router's `useEffect` on route change. Disable `enableAutoRouteTracking` to avoid double counting.\n\n## Distributed Tracing (correlate to backend)\n\nSet `distributedTracingMode: 2` (`DistributedTracingModes.AI_AND_W3C`). The SDK adds `traceparent` (and legacy `Request-Id`) to outbound `fetch`\u002F`XHR`. Backends instrumented with **OpenTelemetry** (e.g. `@azure\u002Fmonitor-opentelemetry`) auto-link to the browser's operation_Id.\n\nFor cross-origin calls, also set `enableCorsCorrelation: true` and add the calling origin to the **CORS exposed headers** on the API.\n\n## GenAI Agent Traces (OTel semantic conventions)\n\nWhen 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 \u002F Log Analytics.\n\n**Set the opt-in env first** so backend instrumentations agree on the same schema version:\n\n```bash\nOTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental\n```\n\n### Required attribute keys (use the OTel names verbatim)\n\n| Span \u002F op | Required attributes |\n| --- | --- |\n| `invoke_agent {agent.name}` | `gen_ai.operation.name=invoke_agent`, `gen_ai.provider.name`, `gen_ai.agent.name`, `gen_ai.agent.id` (when known) |\n| `create_agent {agent.name}` | `gen_ai.operation.name=create_agent`, `gen_ai.provider.name`, `gen_ai.agent.name`, `gen_ai.request.model` |\n| `chat {model}` | `gen_ai.operation.name=chat`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` |\n| `execute_tool {tool.name}` | `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name`, `gen_ai.tool.type` (`function` \\| `extension` \\| `datastore`), `gen_ai.tool.call.id` |\n\n`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`.\n\n> **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.\n\n### Pattern: invoke_agent + nested tool\u002Fmodel spans\n\n```typescript\nimport { ApplicationInsights, SeverityLevel } from \"@microsoft\u002Fapplicationinsights-web\";\n\ntype GenAiAttrs = Record\u003Cstring, string | number | boolean | undefined>;\n\nfunction startGenAiSpan(name: string, attrs: GenAiAttrs) {\n  const id = crypto.randomUUID();\n  const start = performance.now();\n  const baseProps: GenAiAttrs = { \"gen_ai.span.id\": id, ...attrs };\n  return {\n    end(success: boolean, extra: GenAiAttrs = {}, error?: Error) {\n      const duration = Math.round(performance.now() - start);\n      const properties = { ...baseProps, ...extra };\n      appInsights.trackDependencyData({\n        id, name, duration, success,\n        responseCode: error ? 500 : 200,\n        type: \"GenAI\",\n        target: String(attrs[\"gen_ai.provider.name\"] ?? \"genai\"),\n        properties: properties as Record\u003Cstring, string>\n      });\n      if (error) {\n        appInsights.trackException({\n          exception: error,\n          severityLevel: SeverityLevel.Error,\n          properties: { ...properties, \"error.type\": error.name } as Record\u003Cstring, string>\n        });\n      }\n    }\n  };\n}\n\n\u002F\u002F Agent invocation\nconst agentSpan = startGenAiSpan(\"invoke_agent ResearchAssistant\", {\n  \"gen_ai.operation.name\": \"invoke_agent\",\n  \"gen_ai.provider.name\": \"azure.ai.openai\",\n  \"gen_ai.agent.name\": \"ResearchAssistant\",\n  \"gen_ai.agent.id\": \"asst_5j66UpCpwteGg4YSxUnt7lPY\",\n  \"gen_ai.request.model\": \"gpt-4o-mini\",\n  \"server.address\": \"myresource.openai.azure.com\"\n});\n\ntry {\n  \u002F\u002F Nested chat completion span\n  const chat = startGenAiSpan(\"chat gpt-4o-mini\", {\n    \"gen_ai.operation.name\": \"chat\",\n    \"gen_ai.provider.name\": \"azure.ai.openai\",\n    \"gen_ai.request.model\": \"gpt-4o-mini\"\n  });\n  const res = await callAzureOpenAi(\u002F* ... *\u002F);\n  chat.end(true, {\n    \"gen_ai.response.model\": res.model,\n    \"gen_ai.response.id\": res.id,\n    \"gen_ai.response.finish_reasons\": JSON.stringify(res.choices.map(c => c.finish_reason)),\n    \"gen_ai.usage.input_tokens\": res.usage.prompt_tokens,\n    \"gen_ai.usage.output_tokens\": res.usage.completion_tokens,\n    \"gen_ai.output.type\": \"text\"\n  });\n\n  \u002F\u002F Nested tool execution span\n  const tool = startGenAiSpan(\"execute_tool getWeather\", {\n    \"gen_ai.operation.name\": \"execute_tool\",\n    \"gen_ai.tool.name\": \"getWeather\",\n    \"gen_ai.tool.type\": \"function\",\n    \"gen_ai.tool.call.id\": \"call_abc123\"\n  });\n  const toolResult = await runGetWeather({ location: \"SF\" });\n  tool.end(true);\n\n  agentSpan.end(true, {\n    \"gen_ai.usage.input_tokens\": res.usage.prompt_tokens,\n    \"gen_ai.usage.output_tokens\": res.usage.completion_tokens\n  });\n} catch (err) {\n  agentSpan.end(false, { \"error.type\": (err as Error).name }, err as Error);\n}\n```\n\nThe browser's `traceparent` is automatically attached to outbound `fetch` (when `distributedTracingMode: 2`), so downstream Azure OpenAI \u002F agent backend spans hang under the same operation_Id in App Insights.\n\nFor the full attribute reference, well-known values, and content-capture guidance, see [references\u002Fagent-traces.md](references\u002Fagent-traces.md).\n\n### KQL: query GenAI traces in App Insights\n\n```kusto\ndependencies\n| where type == \"GenAI\"\n| extend op   = tostring(customDimensions[\"gen_ai.operation.name\"]),\n         agent = tostring(customDimensions[\"gen_ai.agent.name\"]),\n         model = tostring(customDimensions[\"gen_ai.request.model\"]),\n         tin   = toint(customDimensions[\"gen_ai.usage.input_tokens\"]),\n         tout  = toint(customDimensions[\"gen_ai.usage.output_tokens\"])\n| summarize calls=count(), p95_ms=percentile(duration, 95),\n            avg_in=avg(tin), avg_out=avg(tout) by op, agent, model, bin(timestamp, 5m)\n```\n\n## React (TypeScript)\n\nSee [references\u002Fframework-extensions.md](references\u002Fframework-extensions.md) for full React, React Native, Angular, Next.js, and Vite recipes.\n\n```typescript\nimport { ApplicationInsights } from \"@microsoft\u002Fapplicationinsights-web\";\nimport { ReactPlugin, withAITracking } from \"@microsoft\u002Fapplicationinsights-react-js\";\nimport { createBrowserHistory } from \"history\";\n\nconst reactPlugin = new ReactPlugin();\nconst browserHistory = createBrowserHistory();\n\nexport const appInsights = new ApplicationInsights({\n  config: {\n    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,\n    extensions: [reactPlugin],\n    extensionConfig: { [reactPlugin.identifier]: { history: browserHistory } }\n  }\n});\nappInsights.loadAppInsights();\n\nexport const TrackedCheckout = withAITracking(reactPlugin, Checkout, \"Checkout\");\n```\n\n## React Native\n\n```typescript\nimport { ApplicationInsights } from \"@microsoft\u002Fapplicationinsights-web\";\nimport { ReactNativePlugin } from \"@microsoft\u002Fapplicationinsights-react-native\";\n\nconst rnPlugin = new ReactNativePlugin();\nconst appInsights = new ApplicationInsights({\n  config: {\n    connectionString: process.env.EXPO_PUBLIC_APPINSIGHTS_CONNECTION_STRING,\n    extensions: [rnPlugin],\n    disableFetchTracking: false\n  }\n});\nappInsights.loadAppInsights();\n```\n\n## Performance — Web Vitals\n\nAuto-collected: page-load timings via `PerformanceTiming` \u002F `PerformanceNavigationTiming`. To add Core Web Vitals:\n\n```typescript\nimport { onCLS, onLCP, onINP, type Metric } from \"web-vitals\";\n\nfunction send(m: Metric) {\n  appInsights.trackMetric(\n    { name: `web_vitals.${m.name.toLowerCase()}`, average: m.value },\n    { rating: m.rating, navigationType: m.navigationType, id: m.id }\n  );\n}\nonCLS(send); onLCP(send); onINP(send);\n```\n\n## Cookies & Privacy\n\n```typescript\nnew ApplicationInsights({ config: {\n  connectionString,\n  isCookieUseDisabled: true,         \u002F\u002F hard-disable all cookies\n  cookieCfg: { enabled: true, domain: \".example.com\", path: \"\u002F\", expiry: 365 }\n}});\n```\n\nTo honor consent dynamically:\n\n```typescript\nappInsights.getCookieMgr().setEnabled(userGaveConsent);\nappInsights.config.disableTelemetry = !userGaveConsent;\n```\n\n## Sampling\n\nServer-side ingestion sampling (recommended) is configured on the App Insights resource. SDK-side sampling reduces network use:\n\n```typescript\nnew ApplicationInsights({ config: { connectionString, samplingPercentage: 50 } });\n```\n\nPer-type sampling via telemetry initializer: drop with `return false` based on `item.baseType`.\n\n## Offline \u002F Send-on-Unload\n\nThe SDK uses `sendBeacon` (default `onunloadDisableBeacon: false`) to flush on `pagehide` \u002F `unload`. For SPAs, also call `appInsights.flush()` before destructive transitions (logout, hard reload).\n\n## Common Pitfalls\n\n1. **Do not initialize twice.** Re-importing the module under different bundles produces duplicate page views. Use a single shared module export.\n2. **Initialize before first user input** to avoid losing early clicks\u002Fexceptions.\n3. **Connection string is public** — never reuse the same App Insights resource for backend secrets.\n4. **`enableAutoRouteTracking` + manual `trackPageView`** = duplicates. Pick one.\n5. **CORS distributed tracing** requires the API to allow `Request-Id`, `Request-Context`, `traceparent`, `tracestate` request headers and expose `Request-Context` response header.\n6. **GenAI sensitive content** (`gen_ai.input.messages` etc.) is Opt-In — never log without an explicit runtime flag and approved data handling.\n7. **Agent token usage is on `chat` spans, not `invoke_agent`** — copy aggregated usage to the parent agent span only if you know it.\n8. **React StrictMode** double-invokes effects in dev — guard `loadAppInsights()` with a module-level singleton.\n\n## Bundle Size\n\nThe 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.\n\n## Key Types\n\n```typescript\nimport {\n  ApplicationInsights,\n  SeverityLevel,\n  DistributedTracingModes,\n  type IConfiguration,\n  type IConfig,\n  type ITelemetryItem,\n  type ITelemetryPlugin,\n  type ICustomProperties,\n  type IPageViewTelemetry,\n  type IEventTelemetry,\n  type IExceptionTelemetry,\n  type ITraceTelemetry,\n  type IMetricTelemetry,\n  type IDependencyTelemetry\n} from \"@microsoft\u002Fapplicationinsights-web\";\n```\n\n## Best Practices\n\n1. **One singleton instance** exported from a single module.\n2. **Initialize early** in the app entrypoint, before router setup.\n3. **Use telemetry initializers** to attach `app.version`, `tenantId`, and to scrub PII \u002F query-string secrets.\n4. **Set `distributedTracingMode: 2`** and ensure your APIs accept\u002Fexpose W3C trace context headers.\n5. **For GenAI**, follow OTel `gen_ai.*` attribute names verbatim — they are queryable across browser and backend telemetry uniformly.\n6. **Gate sensitive content capture** (`gen_ai.input.messages` \u002F `gen_ai.output.messages`) behind a build-time or runtime opt-in.\n7. **Flush on logout \u002F sensitive navigation** so in-flight telemetry isn't dropped.\n\n## References\n\n- [references\u002Fagent-traces.md](references\u002Fagent-traces.md) — Full OTel GenAI semconv distilled (agent \u002F model \u002F tool spans, attributes, content capture).\n- [references\u002Fframework-extensions.md](references\u002Fframework-extensions.md) — React, React Native, Angular, Next.js, Vite recipes.\n- [references\u002Fconfiguration.md](references\u002Fconfiguration.md) — Full `IConfiguration` reference and tuning guide.\n- Microsoft Learn: \u003Chttps:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fazure-monitor\u002Fapp\u002Fjavascript-sdk>\n- ApplicationInsights-JS source: \u003Chttps:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FApplicationInsights-JS>\n- OTel GenAI semantic conventions: \u003Chttps:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Fspecs\u002Fsemconv\u002Fgen-ai\u002F>\n","# Application Insights JavaScript SDK (Web) for TypeScript\n\nReal User Monitoring (RUM) for browser apps with `@microsoft\u002Fapplicationinsights-web`. Auto-collects page views, AJAX\u002Ffetch 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.\n\n> **Distinct from `azure-monitor-opentelemetry-ts`**, which is for Node.js server apps. This skill is for **browser\u002Fweb** code (and React Native).\n\n## Before Implementation\n\nSearch `microsoft-docs` MCP for current API patterns:\n\n- Query: \"Application Insights JavaScript SDK setup\"\n- Query: \"Application Insights JavaScript SDK configuration\"\n- Query: \"Application Insights JavaScript framework extensions React Angular\"\n- Verify package version: `npm view @microsoft\u002Fapplicationinsights-web version`\n\n## Packages\n\n| Package | Purpose |\n| --- | --- |\n| `@microsoft\u002Fapplicationinsights-web` | Core RUM SDK (page views, AJAX, exceptions). |\n| `@microsoft\u002Fapplicationinsights-clickanalytics-js` | Auto-collect click telemetry. |\n| `@microsoft\u002Fapplicationinsights-react-js` | React plugin (router instrumentation, hooks, HOC, ErrorBoundary). |\n| `@microsoft\u002Fapplicationinsights-react-native` | React Native plugin (native crashes, sessions). |\n| `@microsoft\u002Fapplicationinsights-angularplugin-js` | Angular plugin (router events, ErrorHandler). |\n| `@microsoft\u002Fapplicationinsights-debugplugin-js` | Dev-only telemetry inspector. |\n| `@microsoft\u002Fapplicationinsights-perfmarkmeasure-js` | User Timing (`performance.mark\u002Fmeasure`) integration. |\n\n## Installation\n\n```bash\nnpm i --save @microsoft\u002Fapplicationinsights-web\n# Optional plugins (install only what you use):\nnpm i --save @microsoft\u002Fapplicationinsights-clickanalytics-js\nnpm i --save @microsoft\u002Fapplicationinsights-react-js @microsoft\u002Fapplicationinsights-react-native @microsoft\u002Fapplicationinsights-angularplugin-js\n```\n\nTypings ship with the package — no separate `@types\u002F...` install needed.\n\n## Connection String\n\nThe 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.\n\n```bash\n# Vite \u002F CRA \u002F Next.js — expose to client via the public env prefix\nVITE_APPINSIGHTS_CONNECTION_STRING=\"InstrumentationKey=...;IngestionEndpoint=https:\u002F\u002F...;LiveEndpoint=https:\u002F\u002F...\"\nNEXT_PUBLIC_APPINSIGHTS_CONNECTION_STRING=\"InstrumentationKey=...\"\n```\n\n## Quick Start (npm)\n\n```typescript\nimport { ApplicationInsights } from \"@microsoft\u002Fapplicationinsights-web\";\n\nexport const appInsights = new ApplicationInsights({\n  config: {\n    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,\n    enableAutoRouteTracking: true,        \u002F\u002F SPA route changes -> page views\n    enableCorsCorrelation: true,          \u002F\u002F propagate Request-Id \u002F traceparent to cross-origin AJAX\n    enableRequestHeaderTracking: true,\n    enableResponseHeaderTracking: true,\n    distributedTracingMode: 2,            \u002F\u002F DistributedTracingModes.AI_AND_W3C — emit traceparent for backend correlation\n    autoTrackPageVisitTime: true,\n    disableFetchTracking: false,          \u002F\u002F fetch() is auto-instrumented by default\n    excludeRequestFromAutoTrackingPatterns: [\u002Flivemetrics\\.azure\\.com\u002Fi]\n  }\n});\n\nappInsights.loadAppInsights();\nappInsights.trackPageView();\n```\n\nCall `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.\n\n## Quick Start (SDK Loader Script)\n\nRecommended when you want auto-updating SDK and zero build pipeline. Paste this as the **first** `\u003Cscript>` in `\u003Chead>`:\n\n```html\n\u003Cscript type=\"text\u002Fjavascript\" src=\"https:\u002F\u002Fjs.monitor.azure.com\u002Fscripts\u002Fb\u002Fai.3.gbl.min.js\" crossorigin=\"anonymous\">\u003C\u002Fscript>\n\u003Cscript type=\"text\u002Fjavascript\">\n  var appInsights = window.appInsights || function (cfg) {\n    \u002F* See: https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fazure-monitor\u002Fapp\u002Fjavascript-sdk\n       Use the latest snippet from the Microsoft Learn page above — it includes\n       backup-CDN failover (cr), SDK-load-failure reporting, and the queue shim\n       so calls before SDK ready are not lost. *\u002F\n  }({ src: \"https:\u002F\u002Fjs.monitor.azure.com\u002Fscripts\u002Fb\u002Fai.3.gbl.min.js\",\n      crossOrigin: \"anonymous\",\n      cfg: { connectionString: \"YOUR_CONNECTION_STRING\" } });\n\u003C\u002Fscript>\n```\n\nLoader-only API (queued until SDK loads): `trackEvent`, `trackPageView`, `trackException`, `trackTrace`, `trackDependencyData`, `trackMetric`, `trackPageViewPerformance`, `startTrackPage`, `stopTrackPage`, `startTrackEvent`, `stopTrackEvent`, `addTelemetryInitializer`, `setAuthenticatedUserContext`, `clearAuthenticatedUserContext`, `flush`.\n\n## Core Tracking APIs\n\n```typescript\n\u002F\u002F Page views (SPAs that disable enableAutoRouteTracking)\nappInsights.trackPageView({ name: \"Checkout\", uri: \"\u002Fcheckout\", properties: { cartSize: 3 } });\n\n\u002F\u002F Custom events (user actions, business events)\nappInsights.trackEvent({ name: \"PurchaseCompleted\" }, { orderId: \"ord_123\", amountUsd: 49.95 });\n\n\u002F\u002F Exceptions (caught errors)\ntry {\n  await pay(order);\n} catch (err) {\n  appInsights.trackException({ exception: err as Error, severityLevel: 3, properties: { orderId: order.id } });\n}\n\n\u002F\u002F Traces (logs, severity 0=Verbose, 1=Info, 2=Warning, 3=Error, 4=Critical)\nappInsights.trackTrace({ message: \"Cart hydrated from local storage\", severityLevel: 1 });\n\n\u002F\u002F Custom metrics (numeric)\nappInsights.trackMetric({ name: \"checkout.duration_ms\", average: 1234 });\n\n\u002F\u002F Dependencies (manually-tracked outbound calls — fetch\u002FXHR are auto-tracked)\nappInsights.trackDependencyData({\n  id: crypto.randomUUID(),\n  name: \"GET \u002Fapi\u002Forders\",\n  duration: 87, success: true, responseCode: 200,\n  data: \"https:\u002F\u002Fapi.example.com\u002Fapi\u002Forders\", target: \"api.example.com\", type: \"Fetch\"\n});\n\n\u002F\u002F User identity (set ONCE per authenticated session — values are PII; do not pass emails)\nappInsights.setAuthenticatedUserContext(\"user-id-123\", \"tenant-456\", \u002F*storeInCookie*\u002F true);\nappInsights.clearAuthenticatedUserContext(); \u002F\u002F on logout\n\n\u002F\u002F Force send before unload\nappInsights.flush();\n```\n\n## Telemetry Initializers (enrichment & filtering)\n\nRun for every envelope before send. Return `false` to drop.\n\n```typescript\nimport type { ITelemetryItem } from \"@microsoft\u002Fapplicationinsights-web\";\n\nappInsights.addTelemetryInitializer((item: ITelemetryItem) => {\n  item.tags ??= {};\n  item.tags[\"ai.cloud.role\"] = \"web-shop\";\n  item.tags[\"ai.cloud.roleInstance\"] = window.location.hostname;\n  item.data ??= {};\n  item.data[\"app.version\"] = import.meta.env.VITE_APP_VERSION;\n  item.data[\"app.build\"] = import.meta.env.VITE_BUILD_SHA;\n\n  \u002F\u002F Drop noisy health-check page views\n  if (item.baseType === \"PageviewData\" && item.baseData?.uri?.endsWith(\"\u002Fhealthz\")) return false;\n\n  \u002F\u002F Scrub query-string secrets\n  if (item.baseData?.uri) {\n    item.baseData.uri = item.baseData.uri.replace(\u002F([?&](token|sig|key)=)[^&]+\u002Fgi, \"$1REDACTED\");\n  }\n});\n```\n\n## Click Analytics\n\n```typescript\nimport { ClickAnalyticsPlugin } from \"@microsoft\u002Fapplicationinsights-clickanalytics-js\";\n\nconst clickPlugin = new ClickAnalyticsPlugin();\nconst appInsights = new ApplicationInsights({\n  config: {\n    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,\n    extensions: [clickPlugin],\n    extensionConfig: {\n      [clickPlugin.identifier]: {\n        autoCapture: true,\n        dataTags: { useDefaultContentNameOrId: true, customDataPrefix: \"data-ai-\" },\n        urlCollectHash: false,\n        behaviorValidator: (b: string) => \u002F^[a-z0-9_]+$\u002F.test(b) ? b : \"\"\n      }\n    }\n  }\n});\nappInsights.loadAppInsights();\n```\n\nMark elements with `data-ai-*` attributes; clicks are emitted as Custom Events with parent-content metadata.\n\n## SPA Route Tracking\n\n- **Built-in:** set `enableAutoRouteTracking: true`. Hooks `history.pushState\u002FreplaceState` and `popstate`.\n- **React Router:** use `@microsoft\u002Fapplicationinsights-react-js` `withAITracking` HOC (see [references\u002Fframework-extensions.md](references\u002Fframework-extensions.md)).\n- **Manual:** call `appInsights.trackPageView({ name, uri })` in your router's `useEffect` on route change. Disable `enableAutoRouteTracking` to avoid double counting.\n\n## Distributed Tracing (correlate to backend)\n\nSet `distributedTracingMode: 2` (`DistributedTracingModes.AI_AND_W3C`). The SDK adds `traceparent` (and legacy `Request-Id`) to outbound `fetch`\u002F`XHR`. Backends instrumented with **OpenTelemetry** (e.g. `@azure\u002Fmonitor-opentelemetry`) auto-link to the browser's operation_Id.\n\nFor cross-origin calls, also set `enableCorsCorrelation: true` and add the calling origin to the **CORS exposed headers** on the API.\n\n## GenAI Agent Traces (OTel semantic conventions)\n\nWhen 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 \u002F Log Analytics.\n\n**Set the opt-in env first** so backend instrumentations agree on the same schema version:\n\n```bash\nOTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental\n```\n\n### Required attribute keys (use the OTel names verbatim)\n\n| Span \u002F op | Required attributes |\n| --- | --- |\n| `invoke_agent {agent.name}` | `gen_ai.operation.name=invoke_agent`, `gen_ai.provider.name`, `gen_ai.agent.name`, `gen_ai.agent.id` (when known) |\n| `create_agent {agent.name}` | `gen_ai.operation.name=create_agent`, `gen_ai.provider.name`, `gen_ai.agent.name`, `gen_ai.request.model` |\n| `chat {model}` | `gen_ai.operation.name=chat`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` |\n| `execute_tool {tool.name}` | `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name`, `gen_ai.tool.type` (`function` \\| `extension` \\| `datastore`), `gen_ai.tool.call.id` |\n\n`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`.\n\n> **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.\n\n### Pattern: invoke_agent + nested tool\u002Fmodel spans\n\n```typescript\nimport { ApplicationInsights, SeverityLevel } from \"@microsoft\u002Fapplicationinsights-web\";\n\ntype GenAiAttrs = Record\u003Cstring, string | number | boolean | undefined>;\n\nfunction startGenAiSpan(name: string, attrs: GenAiAttrs) {\n  const id = crypto.randomUUID();\n  const start = performance.now();\n  const baseProps: GenAiAttrs = { \"gen_ai.span.id\": id, ...attrs };\n  return {\n    end(success: boolean, extra: GenAiAttrs = {}, error?: Error) {\n      const duration = Math.round(performance.now() - start);\n      const properties = { ...baseProps, ...extra };\n      appInsights.trackDependencyData({\n        id, name, duration, success,\n        responseCode: error ? 500 : 200,\n        type: \"GenAI\",\n        target: String(attrs[\"gen_ai.provider.name\"] ?? \"genai\"),\n        properties: properties as Record\u003Cstring, string>\n      });\n      if (error) {\n        appInsights.trackException({\n          exception: error,\n          severityLevel: SeverityLevel.Error,\n          properties: { ...properties, \"error.type\": error.name } as Record\u003Cstring, string>\n        });\n      }\n    }\n  };\n}\n\n\u002F\u002F Agent invocation\nconst agentSpan = startGenAiSpan(\"invoke_agent ResearchAssistant\", {\n  \"gen_ai.operation.name\": \"invoke_agent\",\n  \"gen_ai.provider.name\": \"azure.ai.openai\",\n  \"gen_ai.agent.name\": \"ResearchAssistant\",\n  \"gen_ai.agent.id\": \"asst_5j66UpCpwteGg4YSxUnt7lPY\",\n  \"gen_ai.request.model\": \"gpt-4o-mini\",\n  \"server.address\": \"myresource.openai.azure.com\"\n});\n\ntry {\n  \u002F\u002F Nested chat completion span\n  const chat = startGenAiSpan(\"chat gpt-4o-mini\", {\n    \"gen_ai.operation.name\": \"chat\",\n    \"gen_ai.provider.name\": \"azure.ai.openai\",\n    \"gen_ai.request.model\": \"gpt-4o-mini\"\n  });\n  const res = await callAzureOpenAi(\u002F* ... *\u002F);\n  chat.end(true, {\n    \"gen_ai.response.model\": res.model,\n    \"gen_ai.response.id\": res.id,\n    \"gen_ai.response.finish_reasons\": JSON.stringify(res.choices.map(c => c.finish_reason)),\n    \"gen_ai.usage.input_tokens\": res.usage.prompt_tokens,\n    \"gen_ai.usage.output_tokens\": res.usage.completion_tokens,\n    \"gen_ai.output.type\": \"text\"\n  });\n\n  \u002F\u002F Nested tool execution span\n  const tool = startGenAiSpan(\"execute_tool getWeather\", {\n    \"gen_ai.operation.name\": \"execute_tool\",\n    \"gen_ai.tool.name\": \"getWeather\",\n    \"gen_ai.tool.type\": \"function\",\n    \"gen_ai.tool.call.id\": \"call_abc123\"\n  });\n  const toolResult = await runGetWeather({ location: \"SF\" });\n  tool.end(true);\n\n  agentSpan.end(true, {\n    \"gen_ai.usage.input_tokens\": res.usage.prompt_tokens,\n    \"gen_ai.usage.output_tokens\": res.usage.completion_tokens\n  });\n} catch (err) {\n  agentSpan.end(false, { \"error.type\": (err as Error).name }, err as Error);\n}\n```\n\nThe browser's `traceparent` is automatically attached to outbound `fetch` (when `distributedTracingMode: 2`), so downstream Azure OpenAI \u002F agent backend spans hang under the same operation_Id in App Insights.\n\nFor the full attribute reference, well-known values, and content-capture guidance, see [references\u002Fagent-traces.md](references\u002Fagent-traces.md).\n\n### KQL: query GenAI traces in App Insights\n\n```kusto\ndependencies\n| where type == \"GenAI\"\n| extend op   = tostring(customDimensions[\"gen_ai.operation.name\"]),\n         agent = tostring(customDimensions[\"gen_ai.agent.name\"]),\n         model = tostring(customDimensions[\"gen_ai.request.model\"]),\n         tin   = toint(customDimensions[\"gen_ai.usage.input_tokens\"]),\n         tout  = toint(customDimensions[\"gen_ai.usage.output_tokens\"])\n| summarize calls=count(), p95_ms=percentile(duration, 95),\n            avg_in=avg(tin), avg_out=avg(tout) by op, agent, model, bin(timestamp, 5m)\n```\n\n## React (TypeScript)\n\nSee [references\u002Fframework-extensions.md](references\u002Fframework-extensions.md) for full React, React Native, Angular, Next.js, and Vite recipes.\n\n```typescript\nimport { ApplicationInsights } from \"@microsoft\u002Fapplicationinsights-web\";\nimport { ReactPlugin, withAITracking } from \"@microsoft\u002Fapplicationinsights-react-js\";\nimport { createBrowserHistory } from \"history\";\n\nconst reactPlugin = new ReactPlugin();\nconst browserHistory = createBrowserHistory();\n\nexport const appInsights = new ApplicationInsights({\n  config: {\n    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,\n    extensions: [reactPlugin],\n    extensionConfig: { [reactPlugin.identifier]: { history: browserHistory } }\n  }\n});\nappInsights.loadAppInsights();\n\nexport const TrackedCheckout = withAITracking(reactPlugin, Checkout, \"Checkout\");\n```\n\n## React Native\n\n```typescript\nimport { ApplicationInsights } from \"@microsoft\u002Fapplicationinsights-web\";\nimport { ReactNativePlugin } from \"@microsoft\u002Fapplicationinsights-react-native\";\n\nconst rnPlugin = new ReactNativePlugin();\nconst appInsights = new ApplicationInsights({\n  config: {\n    connectionString: process.env.EXPO_PUBLIC_APPINSIGHTS_CONNECTION_STRING,\n    extensions: [rnPlugin],\n    disableFetchTracking: false\n  }\n});\nappInsights.loadAppInsights();\n```\n\n## Performance — Web Vitals\n\nAuto-collected: page-load timings via `PerformanceTiming` \u002F `PerformanceNavigationTiming`. To add Core Web Vitals:\n\n```typescript\nimport { onCLS, onLCP, onINP, type Metric } from \"web-vitals\";\n\nfunction send(m: Metric) {\n  appInsights.trackMetric(\n    { name: `web_vitals.${m.name.toLowerCase()}`, average: m.value },\n    { rating: m.rating, navigationType: m.navigationType, id: m.id }\n  );\n}\nonCLS(send); onLCP(send); onINP(send);\n```\n\n## Cookies & Privacy\n\n```typescript\nnew ApplicationInsights({ config: {\n  connectionString,\n  isCookieUseDisabled: true,         \u002F\u002F hard-disable all cookies\n  cookieCfg: { enabled: true, domain: \".example.com\", path: \"\u002F\", expiry: 365 }\n}});\n```\n\nTo honor consent dynamically:\n\n```typescript\nappInsights.getCookieMgr().setEnabled(userGaveConsent);\nappInsights.config.disableTelemetry = !userGaveConsent;\n```\n\n## Sampling\n\nServer-side ingestion sampling (recommended) is configured on the App Insights resource. SDK-side sampling reduces network use:\n\n```typescript\nnew ApplicationInsights({ config: { connectionString, samplingPercentage: 50 } });\n```\n\nPer-type sampling via telemetry initializer: drop with `return false` based on `item.baseType`.\n\n## Offline \u002F Send-on-Unload\n\nThe SDK uses `sendBeacon` (default `onunloadDisableBeacon: false`) to flush on `pagehide` \u002F `unload`. For SPAs, also call `appInsights.flush()` before destructive transitions (logout, hard reload).\n\n## Common Pitfalls\n\n1. **Do not initialize twice.** Re-importing the module under different bundles produces duplicate page views. Use a single shared module export.\n2. **Initialize before first user input** to avoid losing early clicks\u002Fexceptions.\n3. **Connection string is public** — never reuse the same App Insights resource for backend secrets.\n4. **`enableAutoRouteTracking` + manual `trackPageView`** = duplicates. Pick one.\n5. **CORS distributed tracing** requires the API to allow `Request-Id`, `Request-Context`, `traceparent`, `tracestate` request headers and expose `Request-Context` response header.\n6. **GenAI sensitive content** (`gen_ai.input.messages` etc.) is Opt-In — never log without an explicit runtime flag and approved data handling.\n7. **Agent token usage is on `chat` spans, not `invoke_agent`** — copy aggregated usage to the parent agent span only if you know it.\n8. **React StrictMode** double-invokes effects in dev — guard `loadAppInsights()` with a module-level singleton.\n\n## Bundle Size\n\nThe 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.\n\n## Key Types\n\n```typescript\nimport {\n  ApplicationInsights,\n  SeverityLevel,\n  DistributedTracingModes,\n  type IConfiguration,\n  type IConfig,\n  type ITelemetryItem,\n  type ITelemetryPlugin,\n  type ICustomProperties,\n  type IPageViewTelemetry,\n  type IEventTelemetry,\n  type IExceptionTelemetry,\n  type ITraceTelemetry,\n  type IMetricTelemetry,\n  type IDependencyTelemetry\n} from \"@microsoft\u002Fapplicationinsights-web\";\n```\n\n## Best Practices\n\n1. **One singleton instance** exported from a single module.\n2. **Initialize early** in the app entrypoint, before router setup.\n3. **Use telemetry initializers** to attach `app.version`, `tenantId`, and to scrub PII \u002F query-string secrets.\n4. **Set `distributedTracingMode: 2`** and ensure your APIs accept\u002Fexpose W3C trace context headers.\n5. **For GenAI**, follow OTel `gen_ai.*` attribute names verbatim — they are queryable across browser and backend telemetry uniformly.\n6. **Gate sensitive content capture** (`gen_ai.input.messages` \u002F `gen_ai.output.messages`) behind a build-time or runtime opt-in.\n7. **Flush on logout \u002F sensitive navigation** so in-flight telemetry isn't dropped.\n\n## References\n\n- [references\u002Fagent-traces.md](references\u002Fagent-traces.md) — Full OTel GenAI semconv distilled (agent \u002F model \u002F tool spans, attributes, content capture).\n- [references\u002Fframework-extensions.md](references\u002Fframework-extensions.md) — React, React Native, Angular, Next.js, Vite recipes.\n- [references\u002Fconfiguration.md](references\u002Fconfiguration.md) — Full `IConfiguration` reference and tuning guide.\n- Microsoft Learn: \u003Chttps:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fazure-monitor\u002Fapp\u002Fjavascript-sdk>\n- ApplicationInsights-JS source: \u003Chttps:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FApplicationInsights-JS>\n- OTel GenAI semantic conventions: \u003Chttps:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Fspecs\u002Fsemconv\u002Fgen-ai\u002F>\n",{"name":5,"license":15,"metadata":65,"description":7},{"author":12,"package":66,"version":67},"@microsoft\u002Fapplicationinsights-web","1.0.0","main","3f5b461b2314e01c400564051e92469114c5b68f",".github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fapplicationinsights-web-ts",365,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills","https:\u002F\u002Fmicrosoft.github.io\u002Fskills\u002F","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-12 02:02:58",{"source":8,"skillName":5,"commands":79,"prompt":89,"zipAvailable":90},[80,83,86],{"tool":81,"command":82},"npx","npx skills add microsoft\u002Fskills --skill applicationinsights-web-ts",{"tool":84,"command":85},"bunx","bunx skills add microsoft\u002Fskills --skill applicationinsights-web-ts",{"tool":87,"command":88},"pnpm","pnpm dlx skills add microsoft\u002Fskills --skill applicationinsights-web-ts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fapplicationinsights-web-ts\u002FSKILL.md",true,[92,98,102],{"path":93,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fagent-traces.md","REFERENCE","参考文档",7770,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fapplicationinsights-web-ts\u002Freferences\u002Fagent-traces.md",{"path":99,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":100,"sourceHtmlUrl":101},"references\u002Fconfiguration.md",6639,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fapplicationinsights-web-ts\u002Freferences\u002Fconfiguration.md",{"path":103,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":104,"sourceHtmlUrl":105},"references\u002Fframework-extensions.md",7860,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fapplicationinsights-web-ts\u002Freferences\u002Fframework-extensions.md",[107,132,164,191,211,244],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":114,"publishedAt":60},"01M69B4JCRQV5SPXAFCKXQRV0H","skill-creator","Guide for creating effective skills for AI coding agents working with Azure SDKs and Microsoft Foundry services. Use when creating new skills or updating existing skills.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fskill-creator\u002FSKILL.md",[113],{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},[115,116,117,9,118,119,120,121,122,123,124,125,126,127,128,38,129,130,131],"skill creator","creator","coding agents","foundry","microsoft foundry","ai coding agents","azure","services","coding","guide","use","ai coding","with","sdks","Existing","when","new",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":144,"publishedAt":60},"01M69B4FD57V1MYKRWAJJECTZ7","podcast-generation","Generate AI-powered podcast-style audio narratives using Azure OpenAI's GPT Realtime Mini model via WebSocket. Use when building text-to-speech features, audio narrative generation, podcast creation from content, or integrating with Azure OpenAI Realtime API for real audio output. Covers full-stack implementation from React frontend to Python FastAPI backend with WebSocket streaming.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fpodcast-generation\u002FSKILL.md",[138,139,140,143],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":141,"categoryName":142,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},[145,146,147,148,149,57,150,121,151,152,153,154,155,156,157,47,158,159,160,161,162,130,163],"podcast generation","podcast","generation","frontend","python","realtime","azure openai","generate","streaming","api","Audio","stack","text","fastapi","creation","python fastapi","narrative","features","fastapi backend",{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":171,"publishedAt":60},"01M69B4CYPM5SESY5ZWEFDXEQZ","microsoft-docs","Understand Microsoft technologies by querying official documentation. Use whenever the user asks how something works, wants tutorials, needs configuration options, limits, quotas, or best practices for any Microsoft technology (Azure, .NET, M365, Windows, Power Platform, etc.)—even if they don't mention \"docs.\" If the question is about understanding a concept rather than writing code, this is the right skill.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fmicrosoft-docs\u002FSKILL.md",[170],{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},[172,9,173,174,175,176,177,178,179,180,181,121,182,183,184,125,185,81,186,187,188,189,190,38],"docs","microsoft docs","MCP","writing","cli","mcp server","windows","power platform","official","documentation","learn","best practices","question","power","back","technology","platform","learn mcp","concept",{"skillNo":192,"name":193,"nameZh":6,"description":194,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":195,"categories":196,"keywords":198,"publishedAt":60},"01M69B49C3YPD1ZJ3NC0HPCY58","mcp-builder","Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP), Node\u002FTypeScript (MCP SDK), or C#\u002F.NET (Microsoft MCP SDK).","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fmcp-builder\u002FSKILL.md",[197],{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},[174,199,200,201,149,202,59,203,9,204,205,47,206,207,124,125,208,209,210,127,38,130],"mcp builder","builder","typescript","llms","model context protocol","fastmcp","Tools","node","context","integrate","mcp sdk","building mcp servers",{"skillNo":212,"name":213,"nameZh":6,"description":214,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":215,"categories":216,"keywords":225,"publishedAt":60},"01M69B467A7CDMFQ0T6Q0ZA12Q","kql","KQL language expertise for writing correct, efficient Kusto Query Language queries. Covers syntax gotchas, join patterns, dynamic types, datetime pitfalls, regex patterns, serialization, memory management, result-size discipline, and advanced functions (geo, vector, graph). USE THIS SKILL whenever writing, debugging, or reviewing KQL queries — even simple ones — because the gotchas section prevents the most common errors that waste tool calls and cause expensive retry cascades. Trigger on: KQL, Kusto, ADX, Azure Data Explorer, Fabric Real-Time Intelligence, EventHouse, Log Analytics, log analysis, data exploration, time series, anomaly detection, summarize, where clause, join, extend, project, let statement, parse operator, extract function, any mention of pipe-forward query syntax.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fkql\u002FSKILL.md",[217,220,221,222],{"categoryNo":218,"categoryName":219,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":30,"categoryName":31,"taxonomyType":32,"taxonomyTypeDesc":33},{"categoryNo":223,"categoryName":224,"taxonomyType":32,"taxonomyTypeDesc":33},"01JBSEEDCAT000000000000036","内容创作者",[213,175,226,227,53,121,228,229,230,231,232,233,234,235,236,237,238,239,240,38,241,242,243],"summarize","memory","vector","time series","tool","discipline","log","geo","exploration","pipe","time","project","regex","join","datetime","section","anomaly","parse",{"skillNo":245,"name":246,"nameZh":6,"description":247,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":248,"categories":249,"keywords":250,"publishedAt":60},"01M69B44HJQ7897EZ7NE7DWQX3","github-issue-creator","Convert raw notes, error logs, voice dictation, or screenshots into crisp GitHub-flavored markdown issue reports. Use when the user pastes bug info, error messages, or informal descriptions and wants a structured GitHub issue. Supports images\u002FGIFs for visual evidence.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgithub-issue-creator\u002FSKILL.md",[],[251,252,253,254,116,255,256,257,258,259,260,261,125,262,263,264,265,266,267,38,130],"github","github issue creator","github issue","issue","issue creator","screenshots","notes","logs","error messages","messages","convert","evidence","reports","images","info","visual","error"]