Edit

Microsoft Azure Monitor Application Insights JavaScript SDK configuration

The Azure Application Insights JavaScript SDK provides configuration for tracking, monitoring, and debugging your web applications.

SDK configuration

These configuration fields are optional and default to false unless otherwise stated. The following sections group the fields by purpose.

For instructions on how to add SDK configuration, see Add SDK configuration.

Cookies and session storage

Use disableCookiesUsage to disable cookies entirely, cookieCfg for full instance-based cookie configuration, cookieDomain and cookiePath to scope cookies across subdomains or application gateways, and namePrefix, sessionCookiePostfix, and userCookiePostfix to customize cookie and localStorage names.

Configuration field Value type Default value
cookieCfg

Defaults to cookie usage enabled see ICookieCfgConfig settings for full defaults.
ICookieCfgConfig
[Optional]
(Since 2.6.0)
undefined
cookieDomain

Custom cookie domain. It's helpful if you want to share Application Insights cookies across subdomains.
(Since v2.6.0) If cookieCfg.domain is defined it takes precedence over this value.
alias for cookieCfg.domain
[Optional]
null
cookiePath

Custom cookie path. It's helpful if you want to share Application Insights cookies behind an application gateway.
If cookieCfg.path is defined, it takes precedence.
alias for cookieCfg.path
[Optional]
(Since 2.6.0)
null
disableCookiesUsage

Default false. A boolean that indicates whether to disable the use of cookies by the SDK. If true, the SDK doesn't store or read any data from cookies.
(Since v2.6.0) If cookieCfg.enabled is defined it takes precedence. Cookie usage can be re-enabled after initialization via the core.getCookieMgr().setEnabled(true).
alias for cookieCfg.enabled
[Optional]
false
namePrefix

An optional value that's used as name postfix for localStorage and session cookie name.
string undefined
sessionCookiePostfix

An optional value that's used as name postfix for session cookie name. If undefined, namePrefix is used as name postfix for session cookie name.
string undefined
userCookiePostfix

An optional value that's used as name postfix for user cookie name. If undefined, no postfix is added on user cookie name.
string undefined

Ajax and Fetch tracking

Ajax and Fetch auto-collection is grouped into five capability areas: on/off toggles (disableAjaxTracking, disableFetchTracking, disableXhr), request and response header capture (enableRequestHeaderTracking, enableResponseHeaderTracking, ignoreHeaders, customHeaders), URL-based filtering (excludeRequestFromAutoTrackingPatterns), extra window.performance lookups (enableAjaxPerfTracking, ajaxPerfLookupDelay, maxAjaxPerfLookupAttempts, enableAjaxErrorStatusText), and per-page volume control and per-call enrichment (maxAjaxCallsPerView, addRequestContext).

Auto-collection toggles

Use these fields to enable or disable automatic collection of Ajax and Fetch requests and to choose the transport (XHR, Fetch, or Beacon).

Configuration field Value type Default value
disableAjaxTracking

If true, Ajax calls aren't autocollected. Default is false.
boolean false
disableFetchTracking

The default setting for disableFetchTracking is false, meaning it's enabled. However, in versions prior to 2.8.10, it was disabled by default. When set to true, Fetch requests aren't automatically collected. The default setting changed from true to false in version 2.8.0.
boolean false
disableXhr

Don't use XMLHttpRequest or XDomainRequest (for Internet Explorer < version 9) by default instead attempt to use fetch() or sendBeacon. If no other transport is available, it uses XMLHttpRequest
boolean false
isBeaconApiDisabled

If false, the SDK sends all telemetry using the Beacon API
boolean true
onunloadDisableBeacon

Default false. when tab is closed, the SDK sends all remaining telemetry using the Beacon API
boolean false
onunloadDisableFetch

If fetch keepalive is supported don't use it for sending events during unload, it may still fall back to fetch() without keepalive
boolean false

Header tracking

Use these fields to include AJAX and Fetch request or response headers in dependency telemetry, provide extra headers on custom endpoints, or filter sensitive headers out of the log.

Configuration field Value type Default value
enableRequestHeaderTracking

If true, AJAX & Fetch request headers is tracked, default is false. If ignoreHeaders isn't configured, Authorization and X-API-Key headers aren't logged.
boolean false
enableResponseHeaderTracking

If true, AJAX & Fetch request's response headers is tracked, default is false. If ignoreHeaders isn't configured, WWW-Authenticate header isn't logged.
boolean false
ignoreHeaders

AJAX & Fetch request and response headers to be ignored in log data. To override or discard the default, add an array with all headers to be excluded or an empty array to the configuration.
string[] ["Authorization", "X-API-Key", "WWW-Authenticate"]
customHeaders

The ability for the user to provide extra headers when using a custom endpoint. customHeaders aren't added on browser shutdown moment when beacon sender is used. And adding custom headers isn't supported on IE9 or earlier.
[{header: string, value: string}] undefined

URL filtering

Use this field to exclude specific request URLs from automatic Ajax and Fetch tracking.

Configuration field Value type Default value
excludeRequestFromAutoTrackingPatterns

Provide a way to exclude specific route from automatic tracking for XMLHttpRequest or Fetch request. If defined, for an Ajax / fetch request that the request url matches with the regex patterns, auto tracking is turned off. Default is undefined.
string[] | RegExp[] undefined

Performance lookups

Use these fields to include extra window.performance timings on Ajax dependency telemetry, tune the lookup delay and retry count, and include response error text on failed AJAX requests.

Configuration field Value type Default value
enableAjaxPerfTracking

Default false. Flag to enable looking up and including extra browser window.performance timings in the reported Ajax (XHR and fetch) reported metrics.
boolean false
ajaxPerfLookupDelay

Defaults to 25 ms. The amount of time to wait before reattempting to find the windows.performance timings for an Ajax request, time is in milliseconds and is passed directly to setTimeout().
numeric 25
maxAjaxPerfLookupAttempts

Defaults to 3. The maximum number of times to look for the window.performance timings (if available) is required. Not all browsers populate the window.performance before reporting the end of the XHR request. For fetch requests, it's added after it's complete.
numeric 3
enableAjaxErrorStatusText

Default false. If true, include response error data text boolean in dependency event on failed AJAX requests.
boolean false

Volume control and enrichment

Use maxAjaxCallsPerView to cap per-page-view Ajax collection, and addRequestContext to enrich dependency telemetry with a callback at the start of each API call.

Configuration field Value type Default value
maxAjaxCallsPerView

Default 500 - controls how many Ajax calls are monitored per page view. Set to -1 to monitor all (unlimited) Ajax calls on the page.
numeric 500
addRequestContext

Provide a way to enrich dependencies logs with context at the beginning of an API call. Default is undefined. You need to check if xhr exists if you configure xhr related context. You need to check if fetch request and fetch response exist if you configure fetch related context. Otherwise you may not get the data you need.
(requestContext: IRequestionContext) => {[key: string]: any} undefined

Distributed tracing and correlation

Use distributedTracingMode to select W3C, AI, or AI_AND_W3C header format. Use disableCorrelationHeaders to turn correlation off entirely. Use enableCorsCorrelation to inject correlation headers on cross-origin requests. Use appId to set a fixed correlation identity. Use correlationHeaderDomains, correlationHeaderExcludedDomains, and correlationHeaderExcludePatterns to allow-list or block-list specific target domains or URL patterns.

Configuration field Value type Default value
appId

AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests. When Beacon API is enabled, it can't be used automatically, but can be set manually in the configuration. Default is null
string null
correlationHeaderDomains

Enable correlation headers for specific domains
string[] undefined
correlationHeaderExcludedDomains

Disable correlation headers for specific domains
string[] undefined
correlationHeaderExcludePatterns

Disable correlation headers using regular expressions
regex[] undefined
disableCorrelationHeaders

If false, the SDK adds two headers ('Request-Id' and 'Request-Context') to all dependency requests to correlate them with corresponding requests on the server side. Default is false.
boolean false
distributedTracingMode

Sets the distributed tracing mode. If AI_AND_W3C mode or W3C mode is set, W3C trace context headers (traceparent/tracestate) are generated and included in all outgoing requests. AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services.
numeric or DistributedTracingModes DistributedTracing Modes.AI_AND_W3C
enableCorsCorrelation

If true, the SDK adds two headers ('Request-Id' and 'Request-Context') to all CORS requests to correlate outgoing AJAX dependencies with corresponding requests on the server side. Default is false
boolean false

Page views and route tracking

Use enableAutoRouteTracking to track SPA route changes. Use autoTrackPageVisitTime to record time-on-page for the previous view. Use isBrowserLinkTrackingEnabled to track Browser Link requests. Use overridePageViewDuration to compute page view duration from trackPageView calls instead of the navigation timing API.

Configuration field Value type Default value
autoTrackPageVisitTime

If true, on a pageview, the previous instrumented page's view time is tracked and sent as telemetry and a new timer is started for the current pageview. It's sent as a custom metric named PageVisitTime in milliseconds and is calculated via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less). Default is false.
boolean false
enableAutoRouteTracking

Automatically track route changes in Single Page Applications (SPA). If true, each route change sends a new Pageview to Application Insights. Hash route changes (example.com/foo#bar) are also recorded as new page views.
Note: If you enable this field, don't enable the history object for React router configuration because you get multiple page view events.
boolean false
isBrowserLinkTrackingEnabled

Default is false. If true, the SDK tracks all Browser Link requests.
boolean false
overridePageViewDuration

If true, default behavior of trackPageView is changed to record end of page view duration interval when trackPageView is called. If false and no custom duration is provided to trackPageView, the page view performance is calculated using the navigation timing API. Default is false.
boolean false

Exception tracking

Use disableExceptionTracking to opt out of automatic exception collection, and enableUnhandledPromiseRejectionTracking to include unhandled promise rejections as JavaScript errors.

Configuration field Value type Default value
disableExceptionTracking

If true, the SDK doesn't autocollect exceptions. Default is false.
boolean false
enableUnhandledPromiseRejectionTracking

If true, the SDK autocollects unhandled promise rejections as a JavaScript error. When disableExceptionTracking is true (don't track exceptions), the config value is ignored and unhandled promise rejections aren't reported.
boolean false

Sampling, batching, and storage

Use samplingPercentage to set the fixed sampling rate, maxBatchInterval and maxBatchSizeInBytes to tune batch send behavior, enableSessionStorageBuffer and isStorageUseDisabled to control whether the SDK persists unsent telemetry in session or local storage, eventsLimitInMem to cap the in-memory buffer, isRetryDisabled to disable retries on transient failures, disableFlushOnBeforeUnload to skip the flush on page unload, and disableTelemetry as a global off switch.

Configuration field Value type Default value
disableFlushOnBeforeUnload

Default false. If true, the flush method isn't called when the onBeforeUnload event triggers.
boolean false
disableTelemetry

If true, the SDK doesn't collect or send telemetry. Default is false.
boolean false
enableSessionStorageBuffer

Default true. If true, the buffer with all unsent telemetry is stored in session storage. The buffer is restored on page load.
boolean true
eventsLimitInMem

The number of events that can be kept in memory before the SDK starts to drop events when not using Session Storage (the default).
number 10000
isRetryDisabled

Default false. If false, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error), 503 (service unavailable), and 0 (offline, only if detected).
boolean false
isStorageUseDisabled

If true, the SDK doesn't store or read any data from local and session storage. Default is false.
boolean false
maxBatchInterval

How long to batch telemetry for before sending (milliseconds).
numeric 15000
maxBatchSizeInBytes

Max size of telemetry batch. If a batch exceeds this limit, it's immediately sent and a new batch is started.
numeric 10000
samplingPercentage

Percentage of events that's sent. Default is 100, meaning all events are sent. Set it if you wish to preserve your data cap for large-scale applications.
numeric 100

Logging and debugging

Use loggingLevelConsole and loggingLevelTelemetry to route internal SDK errors to the console or to telemetry. Use enableDebug to throw internal errors as exceptions during development. Use diagnosticLogInterval to tune the internal log poller. Use disableDataLossAnalysis to skip startup buffer checks. Use disableIkeyDeprecationMessage to suppress the instrumentation key deprecation notice.

Configuration field Value type Default value
diagnosticLogInterval

(internal) Polling interval (in ms) for internal logging queue
numeric 10000
disableDataLossAnalysis

If false, internal telemetry sender buffers are checked at startup for items not yet sent.
boolean true
disableIkeyDeprecationMessage

Disable instrumentation Key deprecation error message. If true, error messages are NOT sent.
boolean true
enableDebug

If true, internal debugging data is thrown as an exception instead of being logged, regardless of SDK logging settings. Default is false.
Note: Enabling this setting results in dropped telemetry whenever an internal error occurs. It can be useful for quickly identifying issues with your configuration or usage of the SDK. If you don't want to lose telemetry while debugging, consider using loggingLevelConsole or loggingLevelTelemetry instead of enableDebug.
boolean false
loggingLevelConsole

Logs internal Application Insights errors to console.
0: off,
1: Critical errors only,
2: Everything (errors & warnings)
numeric 0
loggingLevelTelemetry

Sends internal Application Insights errors as telemetry.
0: off,
1: Critical errors only,
2: Everything (errors & warnings)
numeric 1

Performance manager

Use enablePerfMgr to emit local perfEvents from instrumented code paths. Use createPerfMgr to supply a custom IPerfManager factory. Use perfEvtsSendAll to control whether every perfEvent fires or only parent events.

Configuration field Value type Default value
createPerfMgr

Callback function that's called to create an IPerfManager instance when required and enablePerfMgr is enabled, it enables you to override the default creation of a PerfManager() without needing to setPerfMgr() after initialization.
(core: IAppInsightsCore, notificationManager: INotificationManager) => IPerfManager undefined
enablePerfMgr

When enabled (true) it creates local perfEvents for code that has been instrumented to emit perfEvents (via the doPerf() helper). It can be used to identify performance issues within the SDK based on your usage or optionally within your own instrumented code.
boolean false
perfEvtsSendAll

When enablePerfMgr is enabled and the IPerfManager fires a INotificationManager.perfEvent() this flag determines whether an event is fired (and sent to all listeners) for all events (true) or only for 'parent' events (false <default>).
A parent IPerfEvent is an event where no other IPerfEvent is still running at the point of the event being created and its parent property isn't null or undefined. Since v2.5.7
boolean false

Identifiers and session lifetime

Use accountId to group users into accounts, idLength to set the generated random ID length, sessionExpirationMs for maximum session duration, and sessionRenewalMs for the inactivity timeout that ends a session.

Configuration field Value type Default value
accountId

An optional account ID, if your app groups users into accounts. No spaces, commas, semicolons, equals, or vertical bars
string null
idLength

Identifies the default length used to generate new random session and user IDs. Defaults to 22, previous default value was 5 (v2.5.8 or less), if you need to keep the previous maximum length set the value to 5.
numeric 22
sessionExpirationMs

A session is logged if it continues for this amount of time in milliseconds. Default is 24 hours
numeric 86400000
sessionRenewalMs

A session is logged if the user is inactive for this amount of time in milliseconds. Default is 30 minutes
numeric 1800000

Other settings

Use featureOptIn to opt into preview features, throttleMgrCfg to configure throttling, disableInstrumentationKeyValidation to bypass ingestion key checks, convertUndefined to substitute a default value for undefined fields, and sdkExtension to prefix the ai.internal.sdkVersion tag for downstream SDK extensions.

Configuration field Value type Default value
convertUndefined

Provide user an option to convert undefined field to user defined value.
any undefined
disableInstrumentationKeyValidation

If true, instrumentation key validation check is bypassed. Default value is false.
boolean false
featureOptIn

Set Feature opt in details.

This configuration field is only available in version 3.0.3 and later.
IFeatureOptIn undefined
sdkExtension

Sets the SDK extension name. Only alphabetic characters are allowed. The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (for example, 'ext_javascript:2.0.0'). Default is null.
string null
throttleMgrCfg

Set throttle mgr configuration by key.

This configuration field is only available in version 3.0.3 and later.
{[key: number]: IThrottleMgrConfig} undefined

Distributed tracing

Modern cloud and microservices architectures have enabled simple, independently deployable services that reduce costs while increasing availability and throughput. However, it has made overall systems more difficult to reason about and debug. Distributed tracing solves this problem by providing a performance profiler that works like call stacks for cloud and microservices architectures.

Azure Monitor provides two experiences for consuming distributed trace data: the transaction diagnostics view for a single transaction/request and the application map view to show how systems interact.

Application Insights can monitor each component separately and detect which component is responsible for failures or performance degradation by using distributed telemetry correlation. This article explains the data model, context-propagation techniques, protocols, and implementation of correlation tactics on different languages and platforms used by Application Insights.

Enable distributed tracing via Application Insights through autoinstrumentation or SDKs

Supported Azure Monitor OpenTelemetry instrumentation and the JavaScript SDK emit distributed tracing data for common frameworks and libraries.

With supported instrumentation configured, tracing information is automatically collected for common frameworks, libraries, and technologies.

Any technology can also be tracked manually by creating custom spans.

Data model for telemetry correlation

Application Insights defines a data model for distributed telemetry correlation. To associate telemetry with a logical operation, every telemetry item has a context field called operation_Id. Every telemetry item in the distributed trace shares this identifier. So even if you lose telemetry from a single layer, you can still associate telemetry reported by other components.

A distributed logical operation typically consists of a set of smaller operations that are requests processed by one of the components. Request telemetry defines these operations. Every request telemetry item has its own id that identifies it uniquely and globally. And all telemetry items (such as traces and exceptions) that are associated with the request should set the operation_parentId to the value of the request id.

Dependency telemetry represents every outgoing operation, such as an HTTP call to another component. It also defines its own id that's globally unique. Request telemetry, initiated by this dependency call, uses this id as its operation_parentId.

You can build a view of the distributed logical operation by using operation_Id, operation_parentId, and request.id with dependency.id. These fields also define the causality order of telemetry calls.

In a microservices environment, traces from components can go to different storage items. Every component can have its own connection string in Application Insights. To get telemetry for the logical operation, Application Insights queries data from every storage item.

When the number of storage items is large, you need a hint about where to look next. The Application Insights data model defines two fields to solve this problem: request.source and dependency.target. The first field identifies the component that initiated the dependency request. The second field identifies which component returned the response of the dependency call.

For information on querying from multiple disparate instances, see Query data across Log Analytics workspaces, applications, and resources in Azure Monitor.

Example

Let's look at an example. An application called Stock Prices shows the current market price of a stock by using an external API called Stock. The Stock Prices application has a page called Stock page that the client web browser opens by using GET /Home/Stock. The application queries the Stock API by using the HTTP call GET /api/stock/value.

You can analyze the resulting telemetry by running a query:

(requests | union dependencies | union pageViews)
| where operation_Id == "STYz"
| project timestamp, itemType, name, id, operation_ParentId, operation_Id

In the results, all telemetry items share the root operation_Id. When an Ajax call is made from the page, a new unique ID (qJSXU) is assigned to the dependency telemetry, and the ID of the pageView is used as operation_ParentId. The server request then uses the Ajax ID as operation_ParentId.

itemType name ID operation_ParentId operation_Id
pageView Stock page STYz STYz
dependency GET /Home/Stock qJSXU STYz STYz
request GET Home/Stock KqKwlrSt9PA= qJSXU STYz
dependency GET /api/stock/value bBrf2L7mm2g= KqKwlrSt9PA= STYz

When the call GET /api/stock/value is made to an external service, you need to know the identity of that server so you can set the dependency.target field appropriately. When the external service doesn't support monitoring, target is set to the host name of the service. An example is stock-prices-api.com. But if the service identifies itself by returning a predefined HTTP header, target contains the service identity that allows Application Insights to build a distributed trace by querying telemetry from that service.

Correlation headers using W3C TraceContext

Application Insights is transitioning to W3C Trace-Context, which defines:

  • traceparent: Carries the globally unique operation ID and unique identifier of the call.
  • tracestate: Carries system-specific tracing context.

Supported instrumentation uses the W3C Trace Context protocol for distributed tracing.

The correlation HTTP protocol, also called Request-Id, is being deprecated. This protocol defines two headers:

  • Request-Id: Carries the globally unique ID of the call.
  • Correlation-Context: Carries the name-value pairs collection of the distributed trace properties.

Application Insights also uses correlation context to populate fields such as dependency.target and request.source when that context is available.

The W3C Trace-Context and Application Insights data models map in the following way:

Application Insights W3C TraceContext
Id of Request and Dependency parent-id
Operation_Id trace-id
Operation_ParentId parent-id of this span's parent span. This field must be empty if it's a root span.

For more information, see Application Insights telemetry data model.

Enable W3C distributed tracing support

This feature is enabled by default for JavaScript, and the headers are automatically included when the hosting page domain is the same as the domain the requests are sent to (for example, the hosting page is example.com and the Ajax requests are sent to example.com). To change the distributed tracing mode, use the distributedTracingMode configuration field. The default value, AI_AND_W3C, provides backward compatibility with any legacy services instrumented by Application Insights.

If the XMLHttpRequest or Fetch Ajax requests go to a different domain host, including subdomains, the correlation headers aren't included by default. To enable this feature, set the enableCorsCorrelation configuration field to true. If you set enableCorsCorrelation to true, all XMLHttpRequest and Fetch Ajax requests include the correlation headers. As a result, if the application on the server that the request calls doesn't support the traceparent header, the request might fail. This failure depends on whether the browser and version can validate the request based on which headers the server accepts. You can use the correlationHeaderExcludedDomains configuration field to exclude the server's domain from cross-component correlation header injection. For example, you can use correlationHeaderExcludedDomains: ['*.auth0.com'] to exclude correlation headers from requests sent to the Auth0 identity provider.

Important

To see all configurations required to enable correlation, see the JavaScript correlation documentation.

Filter and preprocess telemetry

For JavaScript web applications, use telemetry initializers to filter, modify, or enrich telemetry before it's sent.

  • Return false from an initializer to drop a telemetry item before it is sent.
  • Add or modify fields on the telemetry item to enrich telemetry with values that are useful for filtering and analysis.
  • Use SDK sampling configuration to reduce telemetry volume when you need statistical sampling instead of explicit filtering.

Warning

Filtering telemetry can skew portal statistics and can make it harder to follow related items. Prefer sampling when you need volume reduction without explicitly excluding specific telemetry.

JavaScript web applications

To filter telemetry from JavaScript web applications, use ITelemetryInitializer.

  1. Create a telemetry initializer callback function. The callback function takes ITelemetryItem as a parameter, which is the event that's being processed. If the callback returns false, the telemetry item is filtered out.

    var filteringFunction = (envelope) => {
      if (envelope.data.someField === 'tobefilteredout') {
        return false;
      }
      return true;
    };
    
  2. Add your telemetry initializer callback:

    appInsights.addTelemetryInitializer(filteringFunction);
    

JavaScript telemetry initializers

Telemetry initializers run before a JavaScript telemetry item is sent. Use them to add, modify, or drop browser telemetry. Returning false from an initializer drops the item.

Use telemetry initializers for targeted enrichment or filtering. Use sampling when you need volume reduction without explicitly excluding specific telemetry.

JavaScript telemetry initializers

Insert a JavaScript telemetry initializer, if needed. For more information on the telemetry initializers for the Application Insights JavaScript SDK, see Telemetry initializers.

Insert a telemetry initializer by adding the onInit callback function in the JavaScript (Web) SDK Loader Script configuration:

<script type="text/javascript">
!(function (cfg){function e(){cfg.onInit&&cfg.onInit(n)}var x,w,D,t,E,n,C=window,O=document,b=C.location,q="script",I="ingestionendpoint",L="disableExceptionTracking",j="ai.device.";"instrumentationKey"[x="toLowerCase"](),w="crossOrigin",D="POST",t="appInsightsSDK",E=cfg.name||"appInsights",(cfg.name||C[t])&&(C[t]=E),n=C[E]||function(g){var f=!1,m=!1,h={initialize:!0,queue:[],sv:"8",version:2,config:g};function v(e,t){var n={},i="Browser";function a(e){e=""+e;return 1===e.length?"0"+e:e}return n[j+"id"]=i[x](),n[j+"type"]=i,n["ai.operation.name"]=b&&b.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(h.sv||h.version),{time:(i=new Date).getUTCFullYear()+"-"+a(1+i.getUTCMonth())+"-"+a(i.getUTCDate())+"T"+a(i.getUTCHours())+":"+a(i.getUTCMinutes())+":"+a(i.getUTCSeconds())+"."+(i.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z",iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}},ver:undefined,seq:"1",aiDataContract:undefined}}var n,i,t,a,y=-1,T=0,S=["js.monitor.azure.com","js.cdn.applicationinsights.io","js.cdn.monitor.azure.com","js0.cdn.applicationinsights.io","js0.cdn.monitor.azure.com","js2.cdn.applicationinsights.io","js2.cdn.monitor.azure.com","az416426.vo.msecnd.net"],o=g.url||cfg.src,r=function(){return s(o,null)};function s(d,t){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~d.indexOf("ai.3")&&(d=d.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<S.length;e++)if(0<d.indexOf(S[e])){y=e;break}var n,i=function(e){var a,t,n,i,o,r,s,c,u,l;h.queue=[],m||(0<=y&&T+1<S.length?(a=(y+T+1)%S.length,p(d.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+S[a]+i})),T+=1):(f=m=!0,s=d,!0!==cfg.dle&&(c=(t=function(){var e,t={},n=g.connectionString;if(n)for(var i=n.split(";"),a=0;a<i.length;a++){var o=i[a].split("=");2===o.length&&(t[o[0][x]()]=o[1])}return t[I]||(e=(n=t.endpointsuffix)?t.location:null,t[I]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||g.instrumentationKey||"",t=(t=(t=t[I])&&"/"===t.slice(-1)?t.slice(0,-1):t)?t+"/v2/track":g.endpointUrl,t=g.userOverrideEndpointUrl||t,(n=[]).push((i="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",o=s,u=t,(l=(r=v(c,"Exception")).data).baseType="ExceptionData",l.baseData.exceptions=[{typeName:"SDKLoadFailed",message:i.replace(/\./g,"-"),hasFullStack:!1,stack:i+"\nSnippet failed to load ["+o+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(b&&b.pathname||"_unknown_")+"\nEndpoint: "+u,parsedStack:[]}],r)),n.push((l=s,i=t,(u=(o=v(c,"Message")).data).baseType="MessageData",(r=u.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+l+")").replace(/\"/g,"")+'"',r.properties={endpoint:i},o)),s=n,c=t,JSON&&((u=C.fetch)&&!cfg.useXhr?u(c,{method:D,body:JSON.stringify(s),mode:"cors"}):XMLHttpRequest&&((l=new XMLHttpRequest).open(D,c),l.setRequestHeader("Content-type","application/json"),l.send(JSON.stringify(s)))))))},a=function(e,t){m||setTimeout(function(){!t&&h.core||i()},500),f=!1},p=function(e){var n=O.createElement(q),e=(n.src=e,t&&(n.integrity=t),n.setAttribute("data-ai-name",E),cfg[w]);return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=a,n.onerror=i,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||a(0,t)},cfg.ld&&cfg.ld<0?O.getElementsByTagName("head")[0].appendChild(n):setTimeout(function(){O.getElementsByTagName(q)[0].parentNode.appendChild(n)},cfg.ld||0),n};p(d)}cfg.sri&&(n=o.match(/^((http[s]?:\/\/.*\/)\w+(\.\d+){1,5})\.(([\w]+\.){0,2}js)$/))&&6===n.length?(d="".concat(n[1],".integrity.json"),i="@".concat(n[4]),l=window.fetch,t=function(e){if(!e.ext||!e.ext[i]||!e.ext[i].file)throw Error("Error Loading JSON response");var t=e.ext[i].integrity||null;s(o=n[2]+e.ext[i].file,t)},l&&!cfg.useXhr?l(d,{method:"GET",mode:"cors"}).then(function(e){return e.json()["catch"](function(){return{}})}).then(t)["catch"](r):XMLHttpRequest&&((a=new XMLHttpRequest).open("GET",d),a.onreadystatechange=function(){if(a.readyState===XMLHttpRequest.DONE)if(200===a.status)try{t(JSON.parse(a.responseText))}catch(e){r()}else r()},a.send())):o&&r();try{h.cookie=O.cookie}catch(k){}function e(e){for(;e.length;)!function(t){h[t]=function(){var e=arguments;f||h.queue.push(function(){h[t].apply(h,e)})}}(e.pop())}var c,u,l="track",d="TrackPage",p="TrackEvent",l=(e([l+"Event",l+"PageView",l+"Exception",l+"Trace",l+"DependencyData",l+"Metric",l+"PageViewPerformance","start"+d,"stop"+d,"start"+p,"stop"+p,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),h.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},(g.extensionConfig||{}).ApplicationInsightsAnalytics||{});return!0!==g[L]&&!0!==l[L]&&(e(["_"+(c="onerror")]),u=C[c],C[c]=function(e,t,n,i,a){var o=u&&u(e,t,n,i,a);return!0!==o&&h["_"+c]({message:e,url:t,lineNumber:n,columnNumber:i,error:a,evt:C.event}),o},g.autoExceptionInstrumented=!0),h}(cfg.cfg),(C[E]=n).queue&&0===n.queue.length?(n.queue.push(e),n.trackPageView({})):e();})({
src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
onInit: function (sdk) {
    sdk.addTelemetryInitializer(function (envelope) {
    envelope.data = envelope.data || {};
    envelope.data.someField = 'This item passed through my telemetry initializer';
    });
}, // Once the application insights instance has loaded and initialized this method will be called
// sri: false, // Custom optional value to specify whether fetching the snippet from integrity file and do integrity check
cfg: { // Application Insights Configuration
    connectionString: "YOUR_CONNECTION_STRING"
}});
</script>

For a summary of the noncustom properties available on the telemetry item, see Application Insights Export Data Model.

You can add as many initializers as you like. They're called in the order that you add them.

Add a cloud role name and cloud role instance

Use a telemetry initializer to set the ai.cloud.role and ai.cloud.roleInstance tags. These tags define how your component appears in the Application Map in Azure Monitor.

appInsights.queue.push(() => {
appInsights.addTelemetryInitializer((envelope) => {
  envelope.tags["ai.cloud.role"] = "your role name";
  envelope.tags["ai.cloud.roleInstance"] = "your role instance";
});
});

Starting from version 2.6.0, the Azure Application Insights JavaScript SDK provides instance-based cookie management that you can disable and re-enable after initialization.

If you disable cookies during initialization by using the disableCookiesUsage or cookieCfg.enabled configurations, you can re-enable them by using the setEnabled function of the ICookieMgr object.

The instance-based cookie management replaces the previous CoreUtils global functions of disableCookies(), setCookie(), getCookie(), and deleteCookie().

To take advantage of the tree-shaking enhancements introduced in version 2.6.0, stop using the global functions.

ICookieMgrConfig is a cookie configuration for instance-based cookie management added in version 2.6.0. The options it provides allow you to enable or disable the use of cookies by the SDK. You can also set custom cookie domains and paths, and customize the functions for fetching, setting, and deleting cookies.

The following table defines the ICookieMgrConfig options.

Name Type Default Description
enabled boolean true The current instance of the SDK uses this boolean to indicate whether the use of cookies is enabled. If false, the instance of the SDK initialized by this configuration doesn't store or read any data from cookies.
domain string null Custom cookie domain. It's helpful if you want to share Application Insights cookies across subdomains. If not provided, uses the value from root cookieDomain value.
path string / Specifies the path to use for the cookie. If not provided, uses any value from the root cookiePath value.
ignoreCookies string[] undefined Specify the cookie names to ignore. It causes any matching cookie name to never be read or written. They can still be explicitly purged or deleted. You don't need to repeat the name in the blockedCookies configuration. (since v2.8.8)
blockedCookies string[] undefined Specify the cookie names to never write. It prevents creating or updating any cookie name, but they can still be read unless also included in the ignoreCookies. They can still be purged or deleted explicitly. If not provided, it defaults to the same list in ignoreCookies. (Since v2.8.8)
getCookie (name: string) => string null Function to fetch the named cookie value. If not provided, the SDK uses the internal cookie parsing and caching.
setCookie (name: string, value: string) => void null Function to set the named cookie with the specified value. Only called when adding or updating a cookie.
delCookie (name: string, value: string) => void null Function to delete the named cookie with the specified value. This function is separated from setCookie to avoid the need to parse the value to determine whether the cookie is being added or removed. If not provided, the SDK uses the internal cookie parsing and caching.

Source map

Source map support helps you debug minified JavaScript code by unminifying the minified call stack of your exception telemetry.

  • Compatible with all current integrations on the Exception Details panel
  • Supports all current and future JavaScript SDKs, including Node.js, without the need for an SDK upgrade

Application Insights supports uploading source maps to your Azure Storage account blob container. Use source maps to unminify call stacks found on the End-to-end transaction details page. You can also use source maps to unminify any exception sent by the JavaScript SDK or the Node.js SDK.

Screenshot that shows selecting the option to unminify a call stack by linking with a storage account.

Create a new storage account and blob container

If you already have an existing storage account or blob container, you can skip this step.

  1. Create a new storage account.

  2. Create a blob container inside your storage account. Set Public access level to Private to ensure that your source maps aren't publicly accessible.

    Screenshot that shows setting the container access level to Private.

Push your source maps to your blob container

Integrate your continuous deployment pipeline with your storage account by configuring it to automatically upload your source maps to the configured blob container.

You can upload source maps to your Azure Blob Storage container with the same folder structure they were compiled and deployed with. A common use case is to prefix a deployment folder with its version, for example, 1.2.3/static/js/main.js. When you unminify via an Azure blob container called sourcemaps, the pipeline tries to fetch a source map located at sourcemaps/1.2.3/static/js/main.js.map.

If you're using Azure Pipelines to continuously build and deploy your application, add an Azure file copy task to your pipeline to automatically upload your source maps.

Screenshot that shows adding an Azure file copy task to your pipeline to upload your source maps to Azure Blob Storage.

Configure your Application Insights resource with a source map storage account

You have two options for configuring your Application Insights resource with a source map storage account.

End-to-end transaction details tab

From the End-to-end transaction details tab, select Unminify. Configure your resource if it's unconfigured.

  1. In the Azure portal, view the details of an exception that's minified.
  2. Select Unminify.
  3. If your resource isn't configured, configure it.
Properties tab

To configure or change the storage account or blob container that's linked to your Application Insights resource:

  1. Go to the Properties tab of your Application Insights resource.

  2. Select Change source map Blob Container.

  3. Select a different blob container as your source map container.

  4. Select Apply.

    Screenshot that shows reconfiguring your selected Azure blob container on the Properties pane.

View the unminified call stack

To view the unminified call stack, select an Exception Telemetry item in the Azure portal, find the source maps that match the call stack, and drag and drop the source maps onto the call stack in the Azure portal. The source map must have the same name as the source file of a stack frame, but with a map extension.

If you experience issues that involve source map support for JavaScript applications, see Troubleshoot source map support for JavaScript applications.

Animation demonstrating unminify feature.

Tree shaking

Tree shaking removes unused code from the final JavaScript bundle.

To take advantage of tree shaking, import only the necessary components of the SDK into your code. By doing this, you exclude unused code from the final bundle, which reduces its size and improves performance.

Tree shaking enhancements and recommendations

In version 2.6.0, the SDK deprecated and removed the internal usage of these static helper classes to improve support for tree-shaking algorithms. This change lets npm packages safely drop unused code.

  • CoreUtils
  • EventHelper
  • Util
  • UrlHelper
  • DateTimeUtils
  • ConnectionStringParser

The functions are now exported as top-level roots from the modules, making it easier to refactor your code for better tree shaking.

The static classes are now const objects that reference the new exported functions.

Tree shaking deprecated functions and replacements

This section applies only if you're using the deprecated functions and want to optimize package size. To reduce size and support all versions of Internet Explorer, use the replacement functions.

Existing Replacement
CoreUtils @microsoft/applicationinsights-core-js
CoreUtils._canUseCookies None. Don't use this function as it causes all of CoreUtils references to be included in your final code.
Refactor your cookie handling to use the appInsights.getCookieMgr().setEnabled(true/false) to set the value and appInsights.getCookieMgr().isEnabled() to check the value.
CoreUtils.isTypeof isTypeof
CoreUtils.isUndefined isUndefined
CoreUtils.isNullOrUndefined isNullOrUndefined
CoreUtils.hasOwnProperty hasOwnProperty
CoreUtils.isFunction isFunction
CoreUtils.isObject isObject
CoreUtils.isDate isDate
CoreUtils.isArray isArray
CoreUtils.isError isError
CoreUtils.isString isString
CoreUtils.isNumber isNumber
CoreUtils.isBoolean isBoolean
CoreUtils.toISOString toISOString or getISOString
CoreUtils.arrForEach arrForEach
CoreUtils.arrIndexOf arrIndexOf
CoreUtils.arrMap arrMap
CoreUtils.arrReduce arrReduce
CoreUtils.strTrim strTrim
CoreUtils.objCreate objCreateFn
CoreUtils.objKeys objKeys
CoreUtils.objDefineAccessors objDefineAccessors
CoreUtils.addEventHandler addEventHandler
CoreUtils.dateNow dateNow
CoreUtils.isIE isIE
CoreUtils.disableCookies disableCookies
Referencing either function causes CoreUtils to be referenced for backward compatibility.
Refactor your cookie handling to use the appInsights.getCookieMgr().setEnabled(false)
CoreUtils.newGuid newGuid
CoreUtils.perfNow perfNow
CoreUtils.newId newId
CoreUtils.randomValue randomValue
CoreUtils.random32 random32
CoreUtils.mwcRandomSeed mwcRandomSeed
CoreUtils.mwcRandom32 mwcRandom32
CoreUtils.generateW3CId generateW3CId
EventHelper @microsoft/applicationinsights-core-js
EventHelper.Attach attachEvent
EventHelper.AttachEvent attachEvent
EventHelper.Detach detachEvent
EventHelper.DetachEvent detachEvent
Util @microsoft/applicationinsights-common-js
Util.NotSpecified strNotSpecified
Util.createDomEvent createDomEvent
Util.disableStorage utlDisableStorage
Util.isInternalApplicationInsightsEndpoint isInternalApplicationInsightsEndpoint
Util.canUseLocalStorage utlCanUseLocalStorage
Util.getStorage utlGetLocalStorage
Util.setStorage utlSetLocalStorage
Util.removeStorage utlRemoveStorage
Util.canUseSessionStorage utlCanUseSessionStorage
Util.getSessionStorageKeys utlGetSessionStorageKeys
Util.getSessionStorage utlGetSessionStorage
Util.setSessionStorage utlSetSessionStorage
Util.removeSessionStorage utlRemoveSessionStorage
Util.disableCookies disableCookies
Referencing either causes CoreUtils to be referenced for backward compatibility.
Refactor your cookie handling to use the appInsights.getCookieMgr().setEnabled(false)
Util.canUseCookies canUseCookies
Referencing either causes CoreUtils to be referenced for backward compatibility.
Refactor your cookie handling to use the appInsights.getCookieMgr().isEnabled()
Util.disallowsSameSiteNone uaDisallowsSameSiteNone
Util.setCookie coreSetCookie
Referencing causes CoreUtils to be referenced for backward compatibility.
Refactor your cookie handling to use the appInsights.getCookieMgr().set(name: string, value: string)
Util.stringToBoolOrDefault stringToBoolOrDefault
Util.getCookie coreGetCookie
Referencing causes CoreUtils to be referenced for backward compatibility.
Refactor your cookie handling to use the appInsights.getCookieMgr().get(name: string)
Util.deleteCookie coreDeleteCookie
Referencing causes CoreUtils to be referenced for backward compatibility.
Refactor your cookie handling to use the appInsights.getCookieMgr().del(name: string, path?: string)
Util.trim strTrim
Util.newId newId
Util.random32 ---
No replacement, refactor your code to use the core random32(true)
Util.generateW3CId generateW3CId
Util.isArray isArray
Util.isError isError
Util.isDate isDate
Util.toISOStringForIE8 toISOString
Util.getIEVersion getIEVersion
Util.msToTimeSpan msToTimeSpan
Util.isCrossOriginError isCrossOriginError
Util.dump dumpObj
Util.getExceptionName getExceptionName
Util.addEventHandler attachEvent
Util.IsBeaconApiSupported isBeaconApiSupported
Util.getExtension getExtensionByName
UrlHelper @microsoft/applicationinsights-common-js
UrlHelper.parseUrl urlParseUrl
UrlHelper.getAbsoluteUrl urlGetAbsoluteUrl
UrlHelper.getPathName urlGetPathName
UrlHelper.getCompeteUrl urlGetCompleteUrl
UrlHelper.parseHost urlParseHost
UrlHelper.parseFullHost urlParseFullHost
DateTimeUtils @microsoft/applicationinsights-common-js
DateTimeUtils.Now dateTimeUtilsNow
DateTimeUtils.GetDuration dateTimeUtilsDuration
ConnectionStringParser @microsoft/applicationinsights-common-js
ConnectionStringParser.parse parseConnectionString

Service notifications

The SDK includes service notifications that provide actionable recommendations to help ensure your telemetry flows uninterrupted to Application Insights. You see the notifications as an exception message within Application Insights. The SDK ensures notifications are relevant to you based on your SDK settings, and it adjusts the verbosity based on the urgency of the recommendation. Keep service notifications on, but you can opt out via the featureOptIn configuration.

Currently, no active notifications are being sent.

The JavaScript SDK manages service notifications and regularly polls a public JSON file to control and update these notifications. To disable the polling made by the JavaScript SDK, disable the featureOptIn mode.

Troubleshooting

See the dedicated troubleshooting article.

Next steps