grafana
The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
- 78k
- TypeScript
- AGPL-3.0
- 12 h ago
Microsoft Application Insights SDK for JavaScript
Repo microsoft/ApplicationInsights-JS, read from GitHub 1 min ago. microsoft has not joined Take My Repo.
microsoft/ApplicationInsights-JS is a public repo on GitHub by microsoft. Microsoft Application Insights SDK for JavaScript. It declares the MIT license on GitHub. It is written mainly in TypeScript, has 687 stars and last changed on 2026-11-20. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-21.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
URGENT ACTION: Stop using az416426.vo.msecnd.net
To avoid any global OUTAGE you MUST change ALL of your CDN usage from
https://az416426.vo.msecnd.net/scripts/...to our primary CDN endpointhttps://js.monitor.azure.com/scripts/....See/follow Issue #2457 for updated details
We are currently investigating the available options on how we can avoid / migrate / mitigate this situation, but at this point it is HIGHLY likely that there will be either a temporary or permanent outage of this domain. As we currently have no known way to “migrate” this domain to a different CDN.
This SDK is intended for browser environments and is not suitable for other environments, like Node.js applications.
For instrumenting a Node.js app, the recommended SDK is the ApplicationInsights-node.js repository.
ES3 support has been removed from the latest version (v3.x), if required see for ES3/IE8 Support
| Version | Details |
|---|---|
| 3.x (main) |
Current supported release from April '2023. Supports dynamic configuration changes/updates after initialization. Supports all features of v2 except with the known Breaking changes from previous versions and does NOT support the previous v1.x compatible API proxy layer, it also removes support for ES3 / IE8. Minimum supported Runtime is now ES5 (IE9+). |
| 2.x (master) |
Feature freeze from March '2023. Will only receive critical bug fixes when no workaround exists — no new features or back-porting from later versions. Supports adding / removing extensions and full unloading/removal of the SDK after initialization. Last version to support ES3 (IE8+), also provides a v1.x compatible API proxy layer for upgrading from V1.x. |
| 1.0.x (legacy-v1) |
No longer actively maintained -- please Upgrade. The documentation for applicationinsights-js@1.0.x has moved here. If you are looking to upgrade to the new version of the SDK, please see the Upgrade Guide. |
💡 Note When multiple instances of Application Insights with different major version are active within a single session, errors may arise. For further details, please refer to the version conflict doc.
connectionString setting of the Application Insights JavaScript SDK.Install via NPM. Then, set up an instance of Application Insights in your app.
Note: Typings are included with this package, so you do not need to install a separate typings package.
npm i --save @microsoft/applicationinsights-web
Pasting a script snippet at the beginning of every <head> tag for each page you want to monitor.
import { ApplicationInsights } from '@microsoft/applicationinsights-web' const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE' /* ...Other Configuration Options... */ } }); appInsights.loadAppInsights(); appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview
If your app does not use NPM, you can directly instrument your webpages with Application Insights by pasting this snippet at the top of each your pages. Preferably, it should be the first script in your <head> section so that it can monitor any potential issues with all of your dependencies.
The current version of the snippet is version 8, the version is identified by the "sv:" in the script.
<script type="text/javascript"> !(function (cfg){var k,x,D,E,L,C,b,U,O,A,e,t="track",n="TrackPage",i="TrackEvent",I=[t+"Event",t+"Exception",t+"PageView",t+"PageViewPerformance","addTelemetryInitializer",t+"Trace",t+"DependencyData",t+"Metric","start"+n,"stop"+n,"start"+i,"stop"+i,"setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"];function a(){cfg.onInit&&cfg.onInit(e)}k=window,x=document,D=k.location,E="script",L="ingestionendpoint",C="disableExceptionTracking",b="crossOrigin",U="POST",O=cfg.pn||"aiPolicy",t="appInsightsSDK",A=cfg.name||"appInsights",(cfg.name||k[t])&&(k[t]=A),e=k[A]||function(u){var n=u.url||cfg.src,s=!1,p=!1,l={initialize:!0,queue:[],sv:"10",config:u,version:2,extensions:void 0};function d(e){var t,n,i,a,r,o,c,s;!0!==cfg.dle&&(o=(t=function(){var e,t={},n=u.connectionString;if("string"==typeof n&&n)for(var i=n.split(";"),a=0;a<i.length;a++){var r=i[a].split("=");2===r.length&&(t[r[0].toLowerCase()]=r[1])}return t[L]||(e=(n=t.endpointsuffix)?t.location:null,t[L]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||u.instrumentationKey||"",t=(t=(t=t[L])&&"/"===t.slice(-1)?t.slice(0,-1):t)?t+"/v2/track":u.endpointUrl,t=u.userOverrideEndpointUrl||t,(n=[]).push((i="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=e,c=t,(s=(r=f(o,"Exception")).data).baseType="ExceptionData",s.baseData.exceptions=[{typeName:"SDKLoadFailed",message:i.replace(/\./g,"-"),hasFullStack:!1,stack:i+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(D&&D.pathname||"_unknown_")+"\nEndpoint: "+c,parsedStack:[]}],r)),n.push((s=e,i=t,(c=(a=f(o,"Message")).data).baseType="MessageData",(r=c.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+s+")").replace(/\"/g,"")+'"',r.properties={endpoint:i},a)),e=n,o=t,JSON&&((c=k.fetch)&&!cfg.useXhr?c(o,{method:U,body:JSON.stringify(e),mode:"cors"}):XMLHttpRequest&&((s=new XMLHttpRequest).open(U,o),s.setRequestHeader("Content-type","application/json"),s.send(JSON.stringify(e)))))}function f(e,t){return e=e,t=t,i=l.sv,a=l.version,r=D,(o={})["ai.device."+"id"]="browser",o["ai.device.type"]="Browser",o["ai.operation.name"]=r&&r.pathname||"_unknown_",o["ai.internal.sdkVersion"]="javascript:snippet_"+(i||a),{time:(r=new Date).getUTCFullYear()+"-"+n(1+r.getUTCMonth())+"-"+n(r.getUTCDate())+"T"+n(r.getUTCHours())+":"+n(r.getUTCMinutes())+":"+n(r.getUTCSeconds())+"."+(r.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z",iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:o,data:{baseData:{ver:2}},ver:undefined,seq:"1",aiDataContract:undefined};function n(e){e=""+e;return 1===e.length?"0"+e:e}var i,a,r,o}var i,a,t,r,g=-1,h=0,m=["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=function(){return c(n,null)};function c(t,r){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~t.indexOf("ai.3")&&(t=t.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<m.length;e++)if(0<t.indexOf(m[e])){g=e;break}var n,o=function(e){var a;l.queue=[],p||(0<=g&&h+1<m.length?(a=(g+h+1)%m.length,i(t.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+m[a]+i})),h+=1):(s=p=!0,d(t)))},c=function(e,t){p||setTimeout(function(){t&&!l.core&&o()},500),s=!1},i=function(e){var n,i=x.createElement(E),e=(cfg.pl?cfg.ttp&&cfg.ttp.createScript?i.src=cfg.ttp.createScriptURL(e):i.src=(null==(n=window.trustedTypes)?void 0:n.createPolicy(O,{createScriptURL:function(e){try{var t=new URL(e);if(t.host&&"js.monitor.azure.com"===t.host)return e;a(e)}catch(n){a(e)}}})).createScriptURL(e):i.src=e,cfg.nt&&i.setAttribute("nonce",cfg.nt),r&&(i.integrity=r),i.setAttribute("data-ai-name",A),cfg[b]);function a(e){d("AI policy blocked URL: "+e)}return!e&&""!==e||"undefined"==i[b]||(i[b]=e),i.onload=c,i.onerror=o,i.onreadystatechange=function(e,t){"loaded"!==i.readyState&&"complete"!==i.readyState||c(0,t)},cfg.ld&&cfg.ld<0?x.getElementsByTagName("head")[0].appendChild(i):setTimeout(function(){x.getElementsByTagName(E)[0].parentNode.appendChild(i)},cfg.ld||0),i};i(t)}cfg.sri&&(i=n.match(/^((http[s]?:\/\/.*\/)\w+(\.\d+){1,5})\.(([\w]+\.){0,2}js)$/))&&6===i.length?(T="".concat(i[1],".integrity.json"),a="@".concat(i[4]),S=window.fetch,t=function(e){if(!e.ext||!e.ext[a]||!e.ext[a].file)throw Error("Error Loading JSON response");var t=e.ext[a].integrity||null;c(n=i[2]+e.ext[a].file,t)},S&&!cfg.useXhr?S(T,{method:"GET",mode:"cors"}).then(function(e){return e.json()["catch"](function(){return{}})}).then(t)["catch"](o):XMLHttpRequest&&((r=new XMLHttpRequest).open("GET",T),r.onreadystatechange=function(){if(r.readyState===XMLHttpRequest.DONE)if(200===r.status)try{t(JSON.parse(r.responseText))}catch(e){o()}else o()},r.send())):n&&o();try{l.cookie=x.cookie}catch(w){}function e(e){for(;e.length;)!function(t){l[t]=function(){var e=arguments;s||l.queue.push(function(){l[t].apply(l,e)})}}(e.pop())}e(I);var v,y,S=!(l.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4}),T=(u.extensionConfig||{}).ApplicationInsightsAnalytics||{};return(S=!0!==u[C]&&!0!==T[C]||S)&&(e(["_"+(v="onerror")]),y=k[v],k[v]=function(e,t,n,i,a){var r=y&&y(e,t,n,i,a);return!0!==r&&l["_"+v]({message:e,url:t,lineNumber:n,columnNumber:i,error:a,evt:k.event}),r},u.autoExceptionInstrumented=!0),l}(cfg.cfg),(k[A]=e).queue&&0===e.queue.length?(e.queue.push(a),e.trackPageView({})):a();})({ src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js", // name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied // ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout, // useXhr: 1, // Use XHR instead of fetch to report failures (if available), // dle: true, // Prevent the SDK from reporting load failure log crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag // onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called) // sri: false, // Custom optional value to specify whether fetching the snippet from integrity file and do integrity check // pl: false, // Custom optional value to specify whether to enable the trusted type policy check on snippet // pn: "aiPolicy", // Custom optional value to specify the name of the trusted type policy that would be implemented on the snippet, default is "aiPolicy" // ttp: null, // Custom optional value to specify the trusted type policy that would be applied on the snippet src // nt: null, // Custom optional value to specify the nounce tag value that would be applied on the script when we drop it on the page cfg: { // Application Insights Configuration connectionString: "YOUR_CONNECTION_STRING" } }); </script>
💡 Note
For readability and to reduce possible JavaScript errors, all of the possible configuration options are listed on a new line in snippet code above, if you don't want to change the value of a commented line it can be removed.
ConnectionString format should follow "InstrumentationKey=xxxx;...." If the string provided does not meet this format, the sdk load process would fail
This version of the snippet detects and reports an exception when loading the SDK from the CDN fails, this exception is reported to the Azure Monitor portal (under the failures > exceptions > browser), and provides visibility into failures of this type so that you are aware your application is not reporting telemetry (or other exceptions) as expected. This signal is an important measurement in understanding that you have lost telemetry because the SDK did not load or initialize, this provides clarity that you are missing the following telemetry:
For details on this exception see SDK Load Failure page.
Reporting of this failure as an exception to the portal does not use the configuration option disableExceptionTracking from the application insights configuration and therefore if this failure occurs it will always be reported by the snippet, even when the window.onerror support is disabled.
Reporting of SDK load exceptions is specifically NOT supported on IE 8 (or less). This assists with reducing the minified size of the snippet by assuming that most environments are not exclusively IE 8 or less. If you have this requirement and you wish to receive these exceptions, you will need to either include a fetch poly fill or create you own snippet version that uses XDomainRequest instead of XMLHttpRequest, it is recommended that you use the provided snippet source code as a starting point.
💡 Note
If you are using a previous version of the snippet, it is highly recommended that you update to the latest version so that you will receive these previously unreported issues.
All configuration options have now been move towards the end of the script to help avoid accidentally introducing JavaScript errors that would not just cause the SDK to fail to load, but also it would disable the reporting of the failure.
Each configuration option is shown above on a new line, if you don't wish to override the default value of an item listed as [optional] you can remove that line to minimize the resulting size of your returned page.
The available configuration options are: -
| Name | Type | Description |
|---|---|---|
| src | string [required] | The full URL for where to load the SDK from. This value is used for the "src" attribute of a dynamically added <script /> tag. You can use the public CDN location or your own privately hosted one. |
| name | string [optional] | The global name for the initialized SDK, defaults to appInsights. So window.appInsights will be a reference to the initialized instance. Note: if you provide a name value or a previous instance appears to be assigned (via the global name appInsightsSDK) then this name value will also be defined in the global namespace as window.appInsightsSDK=<name value>, this is required by the SDK initialization code to ensure it's initializing and updating the correct snippet skeleton and proxy methods. |
| ld | number in ms [optional] | Defines the load delay to wait before attempting to load the SDK. Default value is 0ms and any negative value will immediately add a script tag to the <head> region of the page, which will then block the page load event until to script is loaded (or fails). |
| useXhr | boolean [optional] | This setting is used only for reporting SDK load failures. Reporting will first attempt to use fetch() if available and then fallback to XHR, setting this value to true just bypasses the fetch check. Use of this value is only be required if your application is being used in an environment where fetch would fail to send the failure events. |
| crossOrigin | string [optional] | By including this setting, the script tag added to download the SDK will include the crossOrigin attribute with this string value. When not defined (the default) no crossOrigin attribute is added. Recommended values are not defined (the default); ""; or "anonymous" (For all valid values see HTML attribute: crossorigin documentation) |
| onInit | function(aiSdk) { ... } [optional] | This callback function which is called after the main SDK script has been successfully loaded and initialized from the CDN (based on the src value), it is passed a reference to the sdk instance that it is being called for and it is also called before the first initial page view. If the SDK has already been loaded and initialized this callback will still be called. NOTE: As this callback is called during the processing of the sdk.queue array you CANNOT add any additional items to the queue as they will be ignored and dropped. (Added as part of snippet version 5 -- the sv:"#" value within the snippet script, the current version is 7) |
| cfg | object [required] | The IConfiguration passed to the Application Insights SDK during initialization. |
| cr | boolean [optional] | Controls CDN fallback retry behavior. By default (true), if the SDK fails to load from the configured src URL, the snippet automatically attempts to load from multiple supported CDN domains in case one or more of them is temporarily unavailable. Set to false to disable this fallback and only attempt the single configured src URL. |
| sri | boolean [optional] | Custom optional value to specify whether to fetch the snippet from an integrity file and perform an integrity check. When this option is used, the integrity file is loaded first, affecting the load order and script execution. Hence the ld option will be ignored. Additionally, if the page navigates away before the integrity file is loaded, some events may be lost. |
| dle | boolean [optional] | When set to true, prevents the SDK from reporting load failure telemetry. |
| pl | boolean [optional] | Custom optional value to specify whether to enable the Trusted Type policy check on the snippet. |
| pn | string [optional] | Custom optional value to specify the name of the Trusted Type policy that would be implemented on the snippet, default is 'aiPolicy'. |
| ttp | TrustedTypePolicy [optional] | Custom optional value to specify the Trusted Type policy that would be applied on the snippet src. |
| nt | string [optional] | Custom optional value to specify the nonce attribute value that will be applied to the script tag when it is added to the page. |
Important: When the SDK Loader (snippet) detects that the page is being loaded by Internet Explorer (via the
msieortrident/user agent strings), it will automatically rewrite thesrcURL to load the v2.x version of the SDK instead of v3.x. For example,ai.3.gbl.min.jswill be changed toai.2.gbl.min.js.This means that if your application uses the SDK Loader with a v3.x CDN URL and any of your users visit the page with Internet Explorer, they will receive the 2.x version of the SDK. As a result, any APIs or features that are only available in v3.x or later — including the new OpenTelemetry-based APIs — will not exist on the SDK instance for those users. Your code should account for this by checking for the existence of newer APIs before calling them, or by using only APIs that are available in both v2.x and v3.x.
This fallback does not apply when using the NPM package directly, as NPM installations always load the specific version you have installed.
<script type="text/javascript"> !function(T,l,y){<!-- Removed the Snippet code for brevity -->}(window,document,{ src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js", crossOrigin: "anonymous", onInit: function (sdk) { sdk.addTelemetryInitializer(function (envelope) { envelope.data.someField = 'This item passed through my telemetry initializer'; }); }, // Once the application insights instance has loaded and initialized this method will be called cfg: { // Application Insights Configuration connectionString: "YOUR_CONNECTION_STRING" }}); </script>
URGENT ACTION: Stop using az416426.vo.msecnd.net
To avoid any global OUTAGE you MUST change ALL of your CDN usage from
https://az416426.vo.msecnd.net/scripts/...to our primary CDN endpointhttps://js.monitor.azure.com/scripts/....See/follow Issue #2457 for updated details
We are currently investigating the available options on how we can avoid / migrate / mitigate this situation, but at this point it is HIGHLY likely that there will be either a temporary or permanent outage of this domain. As we currently have no known way to “migrate” this domain to a different CDN.
To help with global resiliency, we have added and updated our primary CDN endpoint (source URL) so that if required we can address any outages without the need for everyone to update the URL used by the Application Insights snippet within their application.
All active CDN endpoints contain all of the previous (and future) versions of the SDK and there is currently no plans to stop or block accessing the snippet from the previous (legacy/backup) URL.
Due to Issue #2457 we are now declaring that you MUST always use js.monitor.azure.com domain.
| State | CDN Endpoint | Description |
|---|---|---|
| Primary | https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js | Provides additional resiliency, allowing us to redirect to a different CDN provider should there be an unexpected issue (if required). |
❗ |
❗ Due to #1813 this URL is now being classified as Deprecated and we will be actively making changes to the SDK to warnings in your telemetry if we detect this domain being used. Due to Issue #2457 we are now declaring that you MUST always use js.monitor.azure.com domain. |
For either the NPM or Snippet setup, you can also configure your instance of Application Insights using a Connection String. Simply replace the instrumentationKey field with the connectionString field.
import { ApplicationInsights } from '@microsoft/applicationinsights-web' const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE' /* ...Other Configuration Options... */ } }); appInsights.loadAppInsights(); appInsights.trackPageView();
Use this approach if you would like to host AI JS SDK script on your endpoint or bundle it with other scripts.
<!-- use your own path to JS SDK script --> <script type="text/javascript" src="/pathToAIJSSDK.js"></script>
After JS script has loaded, include the following snippet to initialize Application Insights:
<!-- the snippet below assumes that JS SDK script has already loaded --> <script type="text/javascript"> var snippet = { config: { connectionString: "InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx" } }; var init = new Microsoft.ApplicationInsights.ApplicationInsights(snippet); var appInsights = init.loadAppInsights(); appInsights.trackPageView(); </script>
If initialized using the snippet, your Application Insights instance is located by default at window.appInsights
appInsights.trackEvent({name: 'some event'}); appInsights.trackPageView({name: 'some page'}); appInsights.trackPageViewPerformance({name : 'some page', url: 'some url'}); appInsights.trackException({exception: new Error('some error')}); appInsights.trackTrace({message: 'some trace'}); appInsights.trackMetric({name: 'some metric', average: 42}); appInsights.trackDependencyData({absoluteUrl: 'some url', responseCode: 200, method: 'GET', id: '|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7'}); appInsights.startTrackPage("pageName"); appInsights.stopTrackPage("pageName", null, {customePropertiesName: "some value"}, {customerMeasurementsName: 144}); appInsights.startTrackEvent("event"); appInsights.stopTrackEvent("event", null, {customePropertiesName: "some value"}, {customerMeasurementsName: 150}); appInsights.flush();
For manually tracked dependencies, see the dependency ID format and W3C correlation notes.
Custom properties can be included in your telemetry through the properties named argument. This can be done with any of the Track APIs except stopTrackPage and stopTrackEvent.
appInsights.trackEvent({ name: 'some event', properties: { // accepts any type prop1: 'string', prop2: 123.45, prop3: { nested: 'objects are okay too' } } });
When using stopTrackPage and stopTrackEvent, you can pass in data categorized by types:
Strings: These should be included under the properties field. Numbers: Add these under the measurements field. Remember, the order of the properties and measurements should not be altered. You can achieve this using the following code structure:
appInsights.startTrackEvent("event name"); appInsights.stopTrackEvent("event name", { stringProp1: 'string', stringProp2: {nested: "objects are okay too", key: "value"} // In this example, stringProp2 will be sent as: "stringProp2": "{\"nested\":\"objects are okay too\",\"key\":\"value\"}". }, {numProp1: 3.15, numProp2: 90000} )
The Application Insights JavaScript SDK includes an OpenTelemetry-compatible tracing API that allows you to use familiar OpenTelemetry patterns for distributed tracing while automatically sending telemetry to Azure Application Insights.
Key Features:
Learn More:
For comprehensive documentation on the OpenTelemetry tracing API, including tracer management, span utilities, helper functions, and detailed examples, see:
Note: This is an OpenTelemetry-compatible tracing API implementation, not a full OpenTelemetry SDK. Only tracing APIs are supported (metrics and logs APIs are not included).
All autocollection is ON by default. The full version of the Application Insights Javascript SDK auto collects:
Telemetry initializers are used to modify the contents of collected telemetry before being sent from the user's browser. They can also be used to prevent certain telemetry from being sent, by returning false. Multiple telemetry initializers can be added to your Application Insights instance, and they are executed in order of adding them.
The input argument to addTelemetryInitializer is a callback that takes a ITelemetryItem as an argument and returns a boolean or void. If returning false, the telemetry item is not sent, else it proceeds to the next telemetry initializer, if any, or is sent to the telemetry collection endpoint.
var telemetryInitializer = (envelope) => { envelope.tags["ai.cloud.role"] = "your role name"; envelope.tags["ai.cloud.roleInstance"] = "your role instance"; } appInsights.addTelemetryInitializer(telemetryInitializer);
var telemetryInitializer = (envelope) => { envelope.data.someField = 'This item passed through my telemetry initializer'; }; appInsights.addTelemetryInitializer(telemetryInitializer); appInsights.trackTrace({message: 'This message will use a telemetry initializer'}); appInsights.addTelemetryInitializer(() => false); // Nothing is sent after this is executed appInsights.trackTrace({message: 'this message will not be sent'}); // Not sent
A dependency listener is a callback function that allows you to perform additional manipulation of the request details before the request is performed.
This includes :-
input and init arguments.traceparent header (traceId, spanId, traceFlags)A Dependency Initializer is very similar to a Telemetry Initializer in that it allows you modify the contents of collected telemetry before being sent from the user's browser. And you can also returning false to cause the event to not be emitted.
The differences between a telemetry initializer and a dependency initializer are :-
false to drop the event the event does NOT count against the maxAjaxCallsPerView as this blocks the event call from being tracked, and while returning false from a Telemetry Initializer will also stop the event from being reported because this is further down the processing pipeline the dependency event IS counted against the maxAjaxCallsPerView limit.{ [key: string]: any } object that is also available to the Dependency Listeners. This allows a listener to add additional details to the context (before the XHR/fetch request is sent), and the initializer will be called after the request has completed.Most configuration fields are named such that they can be defaulted to falsey. All fields are optional except for instrumentationKey or a connectionString containing the instrumentation key.
| Name | Type | Default | Description |
|---|---|---|---|
| instrumentationKey | string [Required if connectionString not supplied] |
null | Instrumentation key that you obtained from the Azure Portal. |
| connectionString | string [Require if instrumentationKey not supplied] |
null | The Connection string that you obtained from the Azure portal |
| accountId | string | null | An optional account id, if your app groups users into accounts. No spaces, commas, semicolons, equals, or vertical bars |
| sessionRenewalMs | numeric | 1800000 | A session is logged if the user is inactive for this amount of time in milliseconds. Default is 30 minutes |
| sessionExpirationMs | numeric | 86400000 | A session is logged if it has continued for this amount of time in milliseconds. Default is 24 hours |
| maxBatchSizeInBytes | numberic | 10000 | Max size of telemetry batch. If a batch exceeds this limit, it is immediately sent and a new batch is started |
| maxBatchInterval | numeric | 15000 | How long to batch telemetry for before sending (milliseconds) |
| disableExceptionTracking | boolean | false | |
| disableTelemetry | boolean | false | If true, telemetry is not collected or sent. Default is false. |
| enableDebug | boolean | false | 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 will result in dropped telemetry whenever an internal error occurs. This can be useful for quickly identifying issues with your configuration or usage of the SDK. If you do not want to lose telemetry while debugging, consider using loggingLevelConsole or loggingLevelTelemetry instead of enableDebug. |
| enableDebugExceptions | boolean | false | Removed from v3.x, Prior to v2.8.12 this was the only supported value and the documented enableDebug was incorrect, since v2.8.12 both enableDebug and enableDebugExceptions is supported. |
| loggingLevelConsole | numeric | 0 | Logs internal Application Insights errors to console. 0: off, 1: Critical errors only, 2: Everything (errors & warnings) |
| loggingLevelTelemetry | numeric | 1 | Sends internal Application Insights errors as telemetry. 0: off, 1: Critical errors only, 2: Everything (errors & warnings) |
| diagnosticLogInterval | numeric | 10000 | (internal) Polling interval (in ms) for internal logging queue |
| samplingPercentage | numeric | 100 | Percentage of events that will be sent. Default is 100, meaning all events are sent. Set this if you wish to preserve your datacap for large-scale applications. |
| autoTrackPageVisitTime | boolean | false | 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 is 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. |
| disableAjaxTracking | boolean | false | If true, Ajax calls are not autocollected. Default is false. |
| disableFetchTracking | boolean | false | If true, Fetch requests are not autocollected. Default is false (Since v2.8.0, previously true) |
| excludeRequestFromAutoTrackingPatterns | string[] | RegExp[] | undefined | 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. |
| addRequestContext | (requestContext: IRequestionContext) => {[key: string]: any} | undefined | Provide a way to enrich dependencies logs with context at the beginning of api call. Default is undefined. You will need to check if xhr exists if you configure xhr related conetext. You will 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. |
| overridePageViewDuration | boolean | false | 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. |
| maxAjaxCallsPerView | numeric | 500 | Default 500 - controls how many ajax calls will be monitored per page view. Set to -1 to monitor all (unlimited) ajax calls on the page. |
| disableDataLossAnalysis | boolean | true | If false, internal telemetry sender buffers will be checked at startup for items not yet sent. |
| disableCorrelationHeaders | boolean | false | If false, the SDK will add two headers ('Request-Id' and 'Request-Context') to all dependency requests to correlate them with corresponding requests on the server side. Default is false. |
| correlationHeaderExcludedDomains | string[] | undefined | Disable correlation headers for specific domains |
| correlationHeaderExcludePatterns | regex[] | undefined | Disable correlation headers using regular expressions |
| correlationHeaderDomains | string[] | undefined | Enable correlation headers for specific domains |
| disableFlushOnBeforeUnload | boolean | false | Default false. If true, flush method will not be called when onBeforeUnload event triggers |
| enableSessionStorageBuffer | boolean | true | Default true. If true, the buffer with all unsent telemetry is stored in session storage. The buffer is restored on page load |
| cookieCfg | ICookieCfgConfig [Optional] (Since 2.6.0) |
undefined | Defaults to cookie usage enabled see ICookieCfgConfig settings for full defaults. |
disableCookiesUsage |
alias for cookieCfg.enabled[Optional] |
false | Default false. A boolean that indicates whether to disable the use of cookies by the SDK. If true, the SDK will not store or read any data from cookies. isCookieUseDisable is deprecated in favor of disableCookiesUsage, when both are provided disableCookiesUsage take precedence. (Since v2.6.0) If cookieCfg.enabled is defined it will take precedence over these values, Cookie usage can be re-enabled after initialization via the core.getCookieMgr().setEnabled(true). |
| cookieDomain | alias for cookieCfg.domain[Optional] |
null | Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. (Since v2.6.0) If cookieCfg.domain is defined it will take precedence over this value. |
| cookiePath | alias for cookieCfg.path[Optional] (Since 2.6.0) |
null | Custom cookie path. This is helpful if you want to share Application Insights cookies behind an application gateway. If cookieCfg.path is defined it will take precedence over this value. |
| isRetryDisabled | boolean | false | 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) |
| isStorageUseDisabled | boolean | false | If true, the SDK will not store or read any data from local and session storage. Default is false. |
| isBeaconApiDisabled | boolean | true | If false, the SDK will send all telemetry using the Beacon API |
| disableXhr | boolean | false | Don't use XMLHttpRequest or XDomainRequest (for IE < 9) by default instead attempt to use fetch() or sendBeacon. If no other transport is available it will still use XMLHttpRequest |
| onunloadDisableBeacon | boolean | false | Default false. when tab is closed, the SDK will send all remaining telemetry using the Beacon API |
| onunloadDisableFetch | boolean | false | If fetch keepalive is supported do not use it for sending events during unload, it may still fallback to fetch() without keepalive |
| sdkExtension | string | null | Sets the sdk extension name. Only alphabetic characters are allowed. The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (e.g. 'ext_javascript:2.0.0'). Default is null. |
| isBrowserLinkTrackingEnabled | boolean | false | Default is false. If true, the SDK will track all Browser Link requests. |
| appId | string | null | 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 cannot be used automatically, but can be set manually in the configuration. Default is null |
| enableCorsCorrelation | boolean | false | If true, the SDK will add 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 |
| namePrefix | string | undefined | An optional value that will be used as name postfix for localStorage and session cookie name. |
| sessionCookiePostfix | string | undefined | An optional value that will be used as name postfix for session cookie name. If undefined, namePrefix is used as name postfix for session cookie name. |
| userCookiePostfix | string | undefined | An optional value that will be used as name postfix for user cookie name. If undefined, no postfix is added on user cookie name. |
| enableAutoRouteTracking | boolean | false | Automatically track route changes in Single Page Applications (SPA). If true, each route change will send a new Pageview to Application Insights. Hash route changes changes (example.com/foo#bar) are also recorded as new page views. |
| enableRequestHeaderTracking | boolean | false | If true, AJAX & Fetch request headers is tracked, default is false. If ignoreHeaders is not configured, Authorization and X-API-Key headers are not logged. |
| enableResponseHeaderTracking | boolean | false | If true, AJAX & Fetch request's response headers is tracked, default is false. If ignoreHeaders is not configured, WWW-Authenticate header is not logged. |
| enableAjaxErrorStatusText | boolean | false | Default false. If true, include response error data text |
| enableAjaxPerfTracking | boolean | false | Default false. Flag to enable looking up and including additional browser window.performance timings in the reported ajax (XHR and fetch) reported metrics. |
| maxAjaxPerfLookupAttempts | numeric | 3 | Defaults to 3. The maximum number of times to look for the window.performance timings (if available), this is required as not all browsers populate the window.performance before reporting the end of the XHR request and for fetch requests this is added after its complete. |
| ajaxPerfLookupDelay | numeric | 25 | Defaults to 25ms. The amount of time to wait before re-attempting to find the windows.performance timings for an ajax request, time is in milliseconds and is passed directly to setTimeout(). |
| distributedTracingMode | numeric or DistributedTracingModes |
DistributedTracingModes.AI_AND_W3C |
Sets the distributed tracing mode. If AI_AND_W3C mode or W3C mode is set, W3C trace context headers (traceparent/tracestate) will be generated and included in all outgoing requests. AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services. |
| enableUnhandledPromiseRejectionTracking | boolean | false | If true, unhandled promise rejections will be autocollected and reported as a javascript error. When disableExceptionTracking is true (dont track exceptions) the config value will be ignored and unhandled promise rejections will not be reported. |
| disableInstrumentationKeyValidation | boolean | false | If true, instrumentation key validation check is bypassed. Default value is false. |
| enablePerfMgr | boolean | false | [Optional] When enabled (true) this will create local perfEvents for code that has been instrumented to emit perfEvents (via the doPerf() helper). This can be used to identify performance issues within the SDK based on your usage or optionally within your own instrumented code. More details are available by the basic documentation. Since v2.5.7 |
| perfEvtsSendAll | boolean | false | [Optional] 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 this event being created and it's parent property is not null or undefined. Since v2.5.7 |
| createPerfMgr | (core: IAppInsightsCore, notificationManager: INotificationManager) => IPerfManager | undefined | Callback function that will be called to create a the IPerfManager instance when required and enablePerfMgr is enabled, this enables you to override the default creation of a PerfManager() without needing to setPerfMgr() after initialization. |
| idLength | numeric | 22 | [Optional] Identifies the default length used to generate new random session and user id's. Defaults to 22, previous default value was 5 (v2.5.8 or less), if you need to keep the previous maximum length you should set this value to 5. |
| customHeaders | [{header: string, value: string}] |
undefined | [Optional] The ability for the user to provide extra headers when using a custom endpoint. customHeaders will not be added on browser shutdown moment when beacon sender is used. And adding custom headers is not supported on IE9 or earlier. |
| convertUndefined | any |
undefined | [Optional] Provide user an option to convert undefined field to user defined value. |
| eventsLimitInMem | number | 10000 | [Optional] The number of events that can be kept in memory before the SDK starts to drop events when not using Session Storage (the default). |
| disableIkeyDeprecationMessage | boolean | true | [Optional] Disable instrumentation Key deprecation error message. If true, error message will NOT be sent. Note: instrumentation key support will end soon, see aka.ms/IkeyMigrate for more details. |
| bufferOverride since 2.8.12 |
IStorageBuffer | undefined | [Optional] Identifies a simple interface to allow you to override the storage mechanism used for tracking unsent and unacknowledged events, when not provided defaults to using SessionStorage interface. You MUST supply both the getItem and setItem functions when defined. |
| storagePrefix | string[] | undefined | [Optional] An optional value that will be added as name prefix for storage name. |
| featureOptIn (#feature) since 3.0.3 |
IFeatureOptIn | undefined | [Optional] Set Feature opt in details. |
| throttleMgrCfg since 3.0.3 |
{[key: number]: IThrottleMgrConfig} |
undefined | [Optional] Set throttle mgr configuration by key. |
| retryCodes | number[] | undefined | Identifies the status codes that will cause event batches to be resent, when null or undefined the SDK will use it's defaults [401, 408, 429, 500, 502, 503, 504]. 403 was removed in version 3.1.1. |
| disablePageUnloadEvents | string[] | undefined | [Optional] An array of the page unload events that you would like to be ignored. See detailed documentation. Unload events include "beforeunload", "unload", "visibilitychange" (with 'hidden' state) and "pagehide". This can be used to avoid jQuery 3.7.1+ deprecation warnings by configuring as disablePageUnloadEvents: ["unload"]. |
| disablePageShowEvents | string[] | undefined | [Optional] An array of page show events that you would like to be ignored. See detailed documentation. Page Show events include "pageshow" and "visibilitychange" (with 'visible' state). |
| expCfg since 3.3.1 |
IExceptionConfig |
undefined | Set additional configuration for exceptions, such as more scripts to include in the exception telemetry. |
| redactQueryParams | string[] | ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature"] |
[Optional] Extends the list of query parameter names that are automatically replaced with "REDACTED" when redactUrls is enabled. Use this to mask application-specific tokens such as auth_token or api_key. |
| redactUrls | boolean | true | [Optional] Controls whether URL fields processed by the SDK have credentials and sensitive query-string values removed via the built-in field redaction helper. Set to false only if you explicitly want to send the original URL without masking. |
Application Insights SDK uses page lifecycle events to reliably send telemetry data before your page closes or navigates away. These events are essential for ensuring no telemetry data is lost during navigation, page refreshes, or tab/browser closures.
What these configurations do:
About visibility state: When a browser tab becomes hidden (switching to another tab) or visible (returning to the tab), the browser fires "visibilitychange" events with document.visibilityState changing to "hidden" or "visible". The SDK uses these events to optimize telemetry sending.
const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE', // Disable the deprecated 'unload' event to avoid jQuery 3.7.1+ deprecation warnings // This also prevents Chrome's warnings about the unload event disablePageUnloadEvents: ["unload"], /* ...Other Configuration Options... */ } }); appInsights.loadAppInsights(); appInsights.trackPageView();
For more detailed information about browser compatibility and configuration options, see the Page Unload Events documentation.
You can use the featureOptIn configuration to enable or customize specific SDK features.
| Name | Default | Description | Note |
|---|---|---|---|
zipPayload |
none*(version 3.3.7) |
Enables compression using the Compression API to zip telemetry payloads. | If this feature is turned on and the CompressionStream API is available, the payload will be compressed using the CompressionStream API. Compression will only occur if the event is asynchronous. For events like unloads, compression will not be applied. Note: if user set payloadPreprocessor, this zip compression will not be applied. |
zipPayloadV2 |
none |
Enables endpoint-safe compression for versioned CDN rollout. | Recognized Microsoft Application Insights ingestion endpoints may be compressed automatically. Custom endpoints remain JSON unless the Application Insights channel sets enableCompressionForCustomEndpoint: true. Older SDKs ignore this key. |
To enable a feature such as zipPayload, set the featureOptIn property in the SDK configuration as shown below:
const appInsights = new ApplicationInsights({ config: { connectionString: "YOUR_CONNECTION_STRING", // Other configuration options... featureOptIn: { zipPayload: { mode: FeatureOptInMode.enable, // Set the opt-in status for the feature blockCdnCfg: false, // Define whether to block changes from CDN config } as IFeatureOptInDetails } } });
See feature opt-in status for more details.
The legacy zipPayload key remains supported for backward compatibility and uses the same endpoint safety checks in current SDKs.
For CDN rollout, first ship and gain adoption of an SDK that supports zipPayloadV2, then publish a new CDN configuration using only
zipPayloadV2. Keep zipPayload absent so older SDKs do not enable compression for custom endpoints.
Legacy configuration retains precedence at runtime: zipPayload: disable turns compression off regardless of zipPayloadV2, while
zipPayload: enable turns endpoint-safe compression on regardless of zipPayloadV2. When legacy zipPayload is none or undefined,
the SDK delegates to zipPayloadV2. Changing either feature dynamically re-evaluates this precedence without copying or modifying the
other feature's value.
extensionConfig should be initialized under the specific extension rather than being defined in the root configuration. This allows for more granular configuration tailored to each extension's needs.
For instance, to configure the dependencies plugin, you would initialize it as follows:
const appInsights = new ApplicationInsights({ config: { connectionString: 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY_GOES_HERE', extensionConfig: { [DependenciesPlugin.identifier]: { ignoreHeaders: [] } } } });
| Name | Type | Default | Extenstion | Description |
|---|---|---|---|---|
| ignoreHeaders | string[] | ["Authorization", "X-API-Key", "WWW-Authenticate"] | DependenciesPlugin | 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. Need to be defined in depenedency plugin extension config, see more here |
Cookie Configuration for instance based cookie management added in version 2.6.0.
| Name | Type | Default | Description |
|---|---|---|---|
| enabled | boolean | true | A boolean that indicates whether the use of cookies by the SDK is enabled by the current instance. If false, the instance of the SDK initialized by this configuration will not store or read any data from cookies |
| domain | string | null | Custom cookie domain. This is 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 it will use any value from the root cookiePath value. |
| ignoreCookies | string[] | undefined | Specify the cookie name(s) to be ignored, this will cause any matching cookie name to never be read or written. They may still be explicitly purged or deleted. You do not need to repeat the name in the blockedCookies configuration.(Since v2.8.8) |
| blockedCookies | string[] | undefined | Specify the cookie name(s) to never be written, this will cause any cookie name to never be created or updated, they will still be read unless also included in the ignoreCookies and may still be explicitly purged or deleted. If not provided defaults to the same list provided in ignoreCookies. (Since v2.8.8) |
| getCookie | (name: string) => string |
null | Function to fetch the named cookie value, if not provided it will use the internal cookie parsing / 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, separated from setCookie to avoid the need to parse the value to determine whether the cookie is being added or removed.if not provided it will use the internal cookie parsing / caching. |
From version 2.6.0, cookie management is now available directly from the instance and can be disabled and re-enabled after initialization.
If disabled during initialization via the disableCookiesUsage or cookieCfg.enabled configurations, you can now re-enable via the ICookieMgr setEnabled function.
The instance based cookie management also replaces the previous CoreUtils global functions of disableCookies(), setCookie(...), getCookie(...) and deleteCookie(...). And to benefit from the tree-shaking enhancements also introduced as part of version 2.6.0 you should no longer uses the global functions.
General Guidance
microsoft/ApplicationInsights-JS is a public repo on GitHub by microsoft. Microsoft Application Insights SDK for JavaScript.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-20. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
Vendor-agnostic analytics for Angular2 applications.
π RuView turns commodity WiFi signals into real-time spatial intelligence, vital sign monitoring, and presence detection — all without a single pixel of video.
Apache Superset is a Data Visualization and Data Exploration Platform
Python tool for converting files and office documents to Markdown.
Microsoft PowerToys is a collection of utilities that supercharge productivity and customization on Windows
21 Lessons, Get Started Building with Generative AI
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
The new Windows Terminal and the original Windows console host, all in the same place!
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/microsoft/ApplicationInsights-JSTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.