applicationinsights-web-ts – Coding skill for AI agents
Instrument browser/web apps with the Application Insights JavaScript SDK (@microsoft/applicationinsights-web).
Install the applicationinsights-web-ts skill with one command
Pick the tool you use, copy the command and paste it in your terminal. The skill lands in that tool's skills folder and is ready in your next session.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/applicationinsights-web-ts-d9b1b.tgz | tar xz -C ~/.claude/skills
Call it in Claude Code: /applicationinsights-web-ts – then describe the task you want done.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/applicationinsights-web-ts-d9b1b.tgz | tar xz -C ~/.codex/skills
Call it in Codex: $applicationinsights-web-ts – then describe the task you want done.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/applicationinsights-web-ts-d9b1b.tgz | tar xz -C ~/.hermes/skills
Call it in Hermes Agent: /applicationinsights-web-ts – then describe the task you want done.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/applicationinsights-web-ts-d9b1b.tgz | tar xz -C ~/.deepcode/skills
Call it in DeepSeek: /applicationinsights-web-ts – then describe the task you want done.
SKILL.md content
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 with explicitly verified backend correlation.
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
| Package | Purpose |
| --- | --- |
| @microsoft/applicationinsights-web | Core RUM SDK (page views, AJAX, exceptions). |
| @microsoft/applicationinsights-clickanalytics-js | Auto-collect click telemetry. |
| @microsoft/applicationinsights-react-js | React plugin (router instrumentation, hooks, HOC, ErrorBoundary). |
| @microsoft/applicationinsights-react-native | React Native plugin (native crashes, sessions). |
| @microsoft/applicationinsights-angularplugin-js | Angular plugin (router events, ErrorHandler). |
| @microsoft/applicationinsights-debugplugin-js | Dev-only telemetry inspector. |
| @microsoft/applicationinsights-perfmarkmeasure-js | 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-jsTypings 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=..."Quick Start (npm)
import { ApplicationInsights, DistributedTracingModes } from "@microsoft/applicationinsights-web";
export const appInsights = new ApplicationInsights({
config: {
connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,
enableAutoRouteTracking: true, // SPA route changes -> page views
enableCorsCorrelation: false, // opt in only for approved backend origins // propagate Request-Id / traceparent to cross-origin AJAX
enableRequestHeaderTracking: false, // avoid collecting credentials/PII
enableResponseHeaderTracking: false,
distributedTracingMode: DistributedTracingModes.W3C, // import the enum; do not infer names from numeric literals
autoTrackPageVisitTime: true,
disableFetchTracking: false, // fetch() is auto-instrumented by default
excludeRequestFromAutoTrackingPatterns: [/livemetrics\.azure\.com/i]
}
});
appInsights.loadAppInsights();
appInsights.trackPageView();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>:
Retrieve and review the complete loader snippet from the official SDK setup page.
The prior queue-shim placeholder was not an implementation and must not be pasted as working code.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
// Page views (SPAs that disable enableAutoRouteTracking)
appInsights.trackPageView({ name: "Checkout", uri: "/checkout", properties: { cartSize: 3 } });
// Custom events (user actions, business events)
appInsights.trackEvent({ name: "PurchaseCompleted" }, { orderId: "ord_123", amountUsd: 49.95 });
// Exceptions (caught errors)
try {
await pay(order);
} catch (err) {
appInsights.trackException({ exception: err as Error, severityLevel: 3, properties: { orderId: order.id } });
}
// Traces (logs, severity 0=Verbose, 1=Info, 2=Warning, 3=Error, 4=Critical)
appInsights.trackTrace({ message: "Cart hydrated from local storage", severityLevel: 1 });
// Custom metrics (numeric)
appInsights.trackMetric({ name: "checkout.duration_ms", average: 1234 });
// Dependencies (manually-tracked outbound calls — fetch/XHR are auto-tracked)
appInsights.trackDependencyData({
id: crypto.randomUUID(),
name: "GET /api/orders",
duration: 87, success: true, responseCode: 200,
data: "https://api.example.com/api/orders", target: "api.example.com", type: "Fetch"
});
// User identity (set ONCE per authenticated session — values are PII; do not pass emails)
appInsights.setAuthenticatedUserContext("user-id-123", "tenant-456", /*storeInCookie*/ false);
appInsights.clearAuthenticatedUserContext(); // on logout
// Force send before unload
appInsights.flush();Telemetry Initializers (enrichment & filtering)
Run for every envelope before send. Return false to drop.
import type { ITelemetryItem } from "@microsoft/applicationinsights-web";
appInsights.addTelemetryInitializer((item: ITelemetryItem) => {
item.tags ??= {};
item.tags["ai.cloud.role"] = "web-shop";
item.tags["ai.cloud.roleInstance"] = window.location.hostname;
item.data ??= {};
item.data["app.version"] = import.meta.env.VITE_APP_VERSION;
item.data["app.build"] = import.meta.env.VITE_BUILD_SHA;
// Drop noisy health-check page views
if (item.baseType === "PageviewData" && item.baseData?.uri?.endsWith("/healthz")) return false;
// Scrub query-string secrets
if (item.baseData?.uri) {
item.baseData.uri = (() => { const u = new URL(item.baseData.uri, location.origin); u.search = ""; u.hash = ""; return u.toString(); })();
}
});Click Analytics
import { ClickAnalyticsPlugin } from "@microsoft/applicationinsights-clickanalytics-js";
const clickPlugin = new ClickAnalyticsPlugin();
const appInsights = new ApplicationInsights({
config: {
connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,
extensions: [clickPlugin],
extensionConfig: {
[clickPlugin.identifier]: {
autoCapture: false, // enable only after approved data-tag allowlisting
dataTags: { useDefaultContentNameOrId: true, customDataPrefix: "data-ai-" },
urlCollectHash: false,
behaviorValidator: (b: string) => /^[a-z0-9_]+$/.test(b) ? b : ""
}
}
}
});
appInsights.loadAppInsights();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](https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-typescript/skills/applicationinsights-web-ts/references/framework-extensions.md)). - Manual: call
appInsights.trackPageView({ name, uri })in your router'suseEffecton route change. DisableenableAutoRouteTrackingto avoid double counting.
Distributed Tracing (correlate to backend)
Set the named DistributedTracingModes.W3C (or deliberately select 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 approved cross-origin
… (full content is in the download package)
Related skills
- architect-review – Master software architect specializing in modern architecture
- architecture – Architectural decision-making framework. Requirements analysis, trade-off evaluation…
- architecture-decision-records – Comprehensive patterns for creating, maintaining, and managing Architecture Decision…
- architecture-patterns – Master proven backend architecture patterns including Clean Architecture, Hexagonal…
- architecture-review – Review repository architecture using Ontoly Software Graph and MCP capabilities. Use…
- fastapi-templates – Create production-ready FastAPI projects with async patterns, dependency injection, and…
- chief-ai-officer-advisor – Chief AI Officer advisory for startups: model build-vs-buy decisions (API vs fine-tune…
- chief-ai-officer-advisor – Chief AI Officer advisory for startups: model build-vs-buy decisions (API vs fine-tune…