node package manager


Application Insights for Node.js

npm version Build Status

Azure Application Insights gathers correlated metrics, logs, and exceptions for each transaction (request) in a distributed system and reports these in the Azure Portal. Add this Node.js SDK to Node.js services in your system to include deep info about Node.js processes and their external dependencies such as database and cache services to those reports.

By default this library tracks incoming and outgoing HTTP requests, several system metrics, and exceptions. You can track more aspects of your app and system using the API described below.

Getting Started

  1. Create an Application Insights resource in Azure by following these instructions.
  2. Grab the Instrumentation Key (aka "ikey") from the resource you created in step 1. Later, you'll either add it to your app's environment variables or use it directly in your scripts.
  3. Add the Application Insights Node.js SDK to your app's dependencies and package.json:
    npm install --save applicationinsights
  4. As early as possible in your app's code, load the Application Insights package:
    let appInsights = require('applicationinsights');
  5. Configure the local SDK by calling appInsights.setup('_your_ikey_');, using the ikey you grabbed in step 2. Or put this ikey in the APPINSIGHTS_INSTRUMENTATIONKEY environment variable and call appInsights.setup() without parameters.

    For more configuration options see below.

  6. Finally, start automatically collecting and sending data by calling appInsights.start();.

Basic Usage

To track HTTP requests, unhandled exceptions and system metrics:

let appInsights = require("applicationinsights");
  • If the instrumentation key is set in the environment variable APPINSIGHTS_INSTRUMENTATIONKEY, .setup() can be called with no arguments. This makes it easy to use different ikeys for different environments.

Load the Application Insights library (i.e. require("applicationinsights")) as early as possible in your scripts, before loading other packages. This is needed so that the Application Insights libary can prepare later packages for tracking. If you encounter conflicts with other libraries doing similar preparation, try loading the Application Insights library after those.

Because of the way JavaScript handles callbacks, additional work is necessary to track a request across external dependencies and later callbacks. By default this additional tracking is enabled; disable it by calling appInsights.setAutoDependencyCorrelation(false) as described in the Configuration section below.


The appInsights object provides a number of configuration methods. They are listed in the following snippet with their default values.

let appInsights = require("applicationinsights");


By default, the SDK will send all collected data to the Application Insights service. If you collect a lot of data, you might want to enable sampling to reduce the amount of data sent. Set the samplingPercentage field on the Config object of a Client to accomplish this. Setting samplingPercentage to 100 (the default) means all data will be sent, and 0 means nothing will be sent.

If you are using automatic correlation, all data associated with a single request will be included or excluded as a unit.

Add code such as the following to enable sampling:

const appInsights = require("applicationinsights");
appInsights.client.config.samplingPercentage = 33; // 33% of all telemetry will be sent to Application Insights 

Automatic third-party instrumentation

In order to track context across asynchronous calls, some changes are required in third party libraries such as mongodb and redis. By default ApplicationInsights will use diagnostic-channel-publishers to monkey-patch some of these libraries. This can be disabled by setting the APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL environment variable. Note that by setting that environment variable, events may no longer be correctly associated with the right operation. Individual monkey-patches can be disabled by setting the APPLICATION_INSIGHTS_NO_PATCH_MODULES environment variable to a comma separated list of packages to disable, e.g. APPLICATION_INSIGHTS_NO_PATCH_MODULES=console,redis to avoid patching the console and redis packages.

Currently there are 6 packages which are instrumented: bunyan, console, mongodb, mongodb-core, mysql and redis.

The bunyan package and console messages will generate Application Insights Trace events based on whether setAutoCollectConsole is enabled. The mongodb, mysql and redis packages will generate Application Insights Dependency events based on whether setAutoCollectDependencies is enabled.

Track custom metrics

You can track any request, event, metric or exception using the Application Insights client. Examples follow:

let appInsights = require("applicationinsights");
appInsights.setup().start(); // assuming ikey in env var. start() can be omitted to disable any non-custom data 
let client = appInsights.client;
client.trackEvent("my custom event", {customProperty: "custom property value"});
client.trackException(new Error("handled exceptions can be logged with this method"));
client.trackMetric("custom metric", 3);
client.trackTrace("trace message");
let http = require("http");
http.createServer( (req, res) => {
  client.trackRequest(req, res); // Place at the beginning of your request handler 

Preprocess data with Telemetry Processors

public addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, correlationContext }) => boolean)

You can process and filter collected data before it is sent for retention using Telemetry Processors. Telemetry processors are called one by one in the order they were added before the telemetry item is sent to the cloud.

If a telemetry processor returns false or throws an error that telemetry item will not be sent.

All telemetry processors receive the telemetry data and its envelope to inspect and modify. They also receive a context object with available request information and the persistent request context as provided by appInsights.getCorrelationContext() (if automatic dependency correlation is enabled).

The TypeScript type for a telemetry processor is:

telemetryProcessor: (envelope: ContractsModule.Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, correlationContext }) => boolean;

For example, a processor that removes stack trace data from exceptions might be written and added as follows:

function removeStackTraces ( envelope, context ) {
  if ( === "Microsoft.ApplicationInsights.ExceptionData") {
    var data =;
    if (data.exceptions && data.exceptions.length > 0) {
      for (var i = 0; i < data.exceptions.length; i++) {
        var exception = data.exceptions[i];
        exception.parsedStack = null;
        exception.hasFullStack = false;
  return true;

More info on the telemetry API is available in the docs.

Use multiple instrumentation keys

You can create multiple Azure Application Insights resources and send different data to each by using their respective instrumentation keys ("ikey"). For example:

let appInsights = require("applicationinsights");
// configure auto-collection under one ikey 
// track some events manually under another ikey 
let otherClient = appInsights.getClient("_ikey-B_");
otherClient.trackEvent("my custom event");


  • Track dependencies

    let appInsights = require("applicationinsights");
    let client = appInsights.getClient();
    var success = false;
    let startTime =;
    // execute dependency call here.... 
    let duration = - startTime;
    success = true;
    client.trackDependency("dependency name", "command name", duration, success);
  • Assign custom properties to be included with all events

    appInsights.client.commonProperties = {
      environment: process.env.SOME_ENV_VARIABLE
  • Manually track all HTTP GET requests

    Note that all requests are tracked by default. To disable automatic collection, call .setAutoCollectRequests(false) before calling start().

    var server = http.createServer((req, res) => {
      if ( req.method === "GET" ) {
          appInsights.client.trackRequest(req, res);
      // other work here.... 
  • Track server startup time

    let start =;
    server.on("listening", () => {
      let duration = - start;
      appInsights.client.trackMetric("server startup time", duration);


  • Ongoing development takes place on the develop branch. Please submit pull requests to this branch.
  • Releases are merged to the master branch and published to npm.



  1. Install all dependencies with npm install.
  2. Set an environment variable to your instrumentation key (optional).
    // windows
    set APPINSIGHTS_INSTRUMENTATIONKEY=<insert_your_instrumentation_key_here>
    // linux/macos
    export APPINSIGHTS_INSTRUMENTATIONKEY=<insert_your_instrumentation_key_here>
  3. Run tests
    npm test

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact with any additional questions or comments.