JavaScript agent API

The JavaScript agent exposes an API that is available on monitored websites. Your website can interact with the API of the JavaScript agent to enrich or configure the collected data, send custom events, and more.

The JavaScript agent API and Web REST API are different. The Web REST API can be used to run queries against the collected data and to configure a new website.

The global object

The Instana JavaScript agent defines a new global function called ineum. This function is available immediately after the JavaScript snippet within the HTML document. That means that the function exists even when the agent itself is not downloaded. This was done to make ineum API calls easy and efficient.

When the agent is not yet downloaded, ineum queues all the executed API calls. After the agent is downloaded, these API calls are executed synchronously in the order in which they were made. From that point forth, ineum is replaced with a function that immediately executes API calls.

API structure

All ineum calls follow the same structure as shown:

ineum(commandName, ...args);

Parameters

Parameter Description
commandName (string) Identifies the command to be executed. For example, set metadata or report an error.
...args The actual arguments for the particular command. The number of arguments and their type are specific to each command.

The function ineum never returns anything (except for the command getPageLoadId).

TypeScript type definitions

TypeScript users can install and use the type definitions that are provided by the DefinitelyTyped project.

npm install --save @types/ineum

APIs

The following sections describe the available command names with their arguments.

Monitoring key

Monitoring keys can be set through the key command. The monitoring key is visible when you configure websites within the Instana user interface.

ineum('key', trackingKey);

Parameter

Parameter Description
trackingKey (string) The monitoring key for the website configuration in Instana.

Example

A correct configuration is shown within the Instana user interface.

Switching Monitoring Keys

Model each of your environments (production, staging, and test) as unique websites within Instana to configure different monitoring keys for the JavaScript agent depending on the deployment. If the monitoring keys are already available, store the monitoring keys in your configuration management system and use the stored value to replace the monitoring key.

If the website consists purely of static files or when no configuration management system is available, you can choose to employ a tool such as Google Tag Manager that helps you manage code snippets for your website. Alternatively, you can choose to hard-code the monitoring keys and execute a check within the web browser.

if (window.location.hostname === 'example.com') {
  ineum('key', 'production monitoring key');
} else if (window.location.hostname === 'qa.example.com') {
  ineum('key', 'QA monitoring key');
} else {
  ineum('key', 'test monitoring key');
}

Reporting URL

Beacons are transmitted to the reporting URL through HTTP GET and POST to deliver the monitoring data to Instana.

ineum('reportingUrl', reportingUrl);

Parameter

Parameter Description
reportingUrl (string) The URL to which the website monitoring data is sent.

Example

A correct configuration is shown within the Instana user interface for SaaS product users. On-premises users need to identify the correct URL based on their configured EUM Endpoint.

Multiple backends

In some cases, it might be desirable to make a JavaScript agent report to multiple backends. In this case, use the reportingBackends command to make the JavaScript agent report to multiple backends.

ineum('reportingBackends', reportingBackends);

Parameter

Parameter Description
reportingBackends (ReportingBackend[]) An array of ReportingBackend objects. Each of the objects defines a backend to which the website monitoring data is sent.

The ReportingBackend object is as shown:

{
  reportingUrl: 'http://example.com',  // The URL to which to send website monitoring data to.
  key: 'monitoring key'                // The monitoring key for the website configuration in Instana.
}

The command reportingBackends is available with Instana Release 230 and later.

Example

ineum('reportingBackends', [
      { reportingUrl: 'http://backend1.example.com', key: 'monitoring key 1' },
      { reportingUrl: 'http://backend2.example.com', key: 'moniroting key 2' }
    ]);

The reportingBackends command takes precedence over the reportingUrl command. After the reportingBackends command call is made, any reportingUrl command call is ignored.

Page

Instana can segment website metrics by logical pages. To do so, it needs a hint about page the user is looking at. This page name can be set through the page command. Set the page as early as possible. You can change the page to present document changes (for example, for single-page applications). This enables Instana to track page transitions in addition to page loads.

ineum('page', pageName);

Page transition events are recorded whenever the page name is changed through the API – except for the first invocation of this API during the page load phase.

To define pages, use logical names like product detail page or payment selection instead of window.title or window.href. Using product detail page or payment selection results in fewer pages that have a direct relation to the existing code. Whereas by using window.title or window.href results in numerous tracked pages that provide value in most of the cases because window.title contains product names.

Instana provides sample projects that show how to collect meaningful page names for various frameworks and libraries. Raise a pull or support request for missing framework or library.

Parameter

Parameter Description
pageName (string) The name of the page.

Example

ineum('page', 'shopping-cart');

// Do you want to change meta data and the page name at the same time?
// Make sure to change the page name last as this immediately
// triggers a page transition beacon.
ineum('meta', 'product', 'skateboard');
ineum('page', 'article-details');

Automatic page detection (public preview)

Instana's website monitoring automatically detects page changes for single-page web applications. This feature is supported since website JavaScript agent 1.7.1.

Automatic page detection is used to track and record page transition events, and this feature is disabled by default. To enable the automatic page detection feature, use one of the following ways:

  • Add the autoPageDetection API command in the HTML head.

  • Configure website automatic instrumentation by using the following command:

    ineum('autoPageDetection', enabled);
    
Parameter
Parameter Description
enabled (boolean) To enable the automatic page detection
Example
ineum('autoPageDetection', true);
// page changes will be detected once set to true
Set logical page names

You can set logical page names by using the mappingRule parameter, which provides an array of regular expressions to map URL changes and replace with the provided name. To set the document title as the page name, you can enable the titleAsPageName parameter to true.

For static content applications, you can ignore the popstate event for page changes by setting the ignorePopstateEvent parameter to true.

If you enable automatic page detection by configuring website automatic instrumentation, the document title is set as the page name by default.

ineum('autoPageDetection', {mappingRule});
ineum('autoPageDetection', {titleAsPageName});
ineum('autoPageDetection',  {ignorePopstateEvent});
Parameter
Parameter Description
mappingRule (RegExp[], string) An array of RegExp objects matching the URL of the page change is replaced by the string provided. If the mapping result is empty, this transition is ignored.
titleAsPageName (boolean) To enable document title as page name
ignorePopstateEvent (boolean) To ignore popstate event
Example
ineum('autoPageDetection',  {mappingRule: [[/.*checkuserdetails.*/i, 'User Details']]});
// matches the regex and sets page name as User Details
ineum('autoPageDetection',  {mappingRule: [[/.*product[0-9]+contains-[A-Za-z]+-productID,-account-([A-Za-z].*)\1+/, 'Product Page : id $1'],[[/.*aboutPage.*-([A-Za-z].*)/, 'About Page id: $1']]]});
ineum('autoPageDetection',  {mappingRule: [[/^.*?-(profile.*?)-(accountId.*?)-(yes.*?)$/, '$1 : $2, Logged in: $3']]});
ineum('autoPageDetection',  {titleAsPageName:true});
ineum('autoPageDetection',  {ignorePopstateEvent:true});

Identifying users

User-specific information can optionally be sent with data that is transmitted to Instana. This information can then be used to unlock more capabilities such as:

  • Calculate the number of users affected by errors
  • To filter data for specific users
  • To see which user initiated a page load or AJAX call.

By default, Instana does not associate any user-identifiable information to beacons. Be aware of the respective data protection laws when you choose to do so. In Instana, user ID is a transparent string that is only used to calculate certain metrics. Therefore, identification of users is done through a user ID. userName and userEmail can also be used to have access to more filters and an effective presentation of user information.

The data that is already transmitted to Instana's server cannot be retroactively updated. Therefore, it is important to call this API as soon as possible in the page loading process.

Calling this API synchronously in the page loading process, for example, by rendering the information into the HTML document on the server side helps ensure that all beacons carry user information, the unique or affected user statistics are correct, and beacons are correctly filtered and grouped when analyzed.

ineum('user', userId, userName, userEmail);

Parameter

Parameter Description
userId (string, optional) An identifier for the user.
userName (string, optional) The username.
userEmail (string, optional) The user's email address.

You can pass null or undefined for values that you do not want to set.

Example

// Report everything to Instana
ineum('user', 'hjmna897k1', 'Tom Mason', 'tom@example.com');

// or only some data points
ineum('user', 'hjmna897k1');
ineum('user', null, null, 'tom@example.com');

Session Tracking

Session tracking can be used to gain insights into activity of end-users across page loads. Session tracking specifically enables Instana to determine end-user impact in the absence of defined user information.

To track sessions, the JavaScript agent uses the localStorage browser API after making the trackSessions call. Technically a session is a random ID that is stored alongside two timestamps within browsers' localStorage under the key in-session.

Responsibility for adherence to privacy regulations lies with the caller of this API.

Initialize/Reuse Session

This API starts a new session or reuses an existing one when possible.

ineum('trackSessions', sessionInactivityTimeout, sessionTerminationTimeout);
Parameter
Parameter Description
sessionInactivityTimeout (number, optional) Describes how long a session remains active since the last trackSessions call in milliseconds. Defaults to three hours.
sessionTerminationTimeout (number, optional) Describes how long a session remains active since the first trackSessions call in milliseconds. Defaults to six hours.

You can pass null or undefined for values that you do not want to set.

Example
// Starts tracking sessions with the default timeouts
ineum('trackSessions');

// or specify custom timeouts
ineum('trackSessions', 900000 /* 15min */, 3600000 /* 1h */);

Terminate Session

Terminates the currently running session (if any) and removes the stored data from localStorage.

ineum('terminateSession');
Example
// Starts tracking sessions with the default timeouts
ineum('trackSessions');

// after some time…
ineum('terminateSession');

Metadata

Metadata can be used to annotate page loads and AJAX calls. Use metadata to track the UI configuration values, settings, feature flags… any additional context that might be useful for analysis.

ineum('meta', key, value);

Parameter

Parameter Description
key (string) The key of the key-value pair you want to add as metadata.
value (string) The value of the key-value pair you want to add as metadata.

Example

ineum('meta', 'version', '1.42.3');
ineum('meta', 'role', 'admin');

Page load backend trace ID

As part of the page load, a backend trace ID can be defined to allow for frontend or backend correlation. For more information, see backend correlation for more details. Defining the backend trace ID is required to gain correlation between page loads' backend and frontend processing. It is not required for correlation between the XMLHttpRequest or fetch requests. A trace ID must be a hex string with 16 or 32 characters.

ineum('traceId', traceId);

Parameter

Parameter Description
traceId (string) The trace ID of the associated backend trace.

Example

ineum('traceId', '89jkbds891jkn321');

Excluding URLs from tracking

You can define several regular expressions by using this API. With at least one match it does not result in data transmission to Instana. The regular expressions are evaluated in the following scenarios:

  • Evaluation against the documents' URLs (the URLs visible in the address bar, that is, window.location.href). All data transmission to Instana is disabled when one of the regular expressions matches.
  • Evaluation against resources' URLs, for example, URLs of JavaScript and CSS files. No information about resources matching one of the regular expressions is transmitted to Instana.
  • Evaluation against the target URLs of HTTP calls, for example, through XMLHttpRequest and fetch. No information about HTTP calls matching one of the regular expressions is transmitted to Instana.
ineum('ignoreUrls', ignoreUrls);

Instana also supports stripping of secrets from document URLs, that is, the URL visible in the browser address bar (see the secrets API). However, be aware that secrets stored in document URLs are almost leaked to all third-parties. We have a dedicated example app with description that shows why secrets stored in document URLs are prone to being leaked to all third-parties. Refer to this example app and description for more details. However, you might choose to ignore all monitoring data collection for these URLs through this API.

Parameter

Parameter Description
ignoreUrls (RegExp[]) An array of RegExp objects matches the URLs that you want to ignore.

Example

ineum('ignoreUrls', [
  /\/comet.+/i,
  /\/ws.+/i,
  /.*(&|\?)secret=.*/i
]);

Redacting secrets from URLs

Query parameters in collected URLs might contain sensitive data. Therefore, the JavaScript agent supports the specification of patterns for query parameter keys whose values are redacted. Redaction happens within the JavaScript agent, that is, within the web browser. Therefore, secrets do not reach the Instana servers for processing and are not available for analysis in the UI or retrieved through API.

ineum('secrets', secrets);

If a query parameter matches an entry from the list, the value is redacted and not sent to the Instana backend. If no ineum('secrets') is defined, Instana uses [/key/i, /secret/i, /password/i] as matching rule by default.

Parameter

Parameter Description
secrets (RegExp[]) An array of RegExp objects that match the query parameter key names whose values are treated as secrets.

Example

ineum('secrets', [/account/i, /user/i]);

For example, https://example.com/accounts/status?account=acount_name&user=user_name is collected and displayed as https://example.com/accounts/status?account=<redacted>&user=<redacted>.

The JavaScript agent does not support treating path parameters (/account/<account id>/status) or matrix parameters (/account;accountId=<account id>/status) as secrets.

Secrets that are stored in document URLs are almost leaked to all third-parties. For more information, see a dedicated example app with description that shows why secrets stored in document URLs are prone to being leaked to all third-parties.

Redacting fragment from URLs

The fragment of collected URLs might contain sensitive information. Therefore, the JavaScript agent supports the specification of patterns for fragment values that can be redacted based on the URL path. This redaction takes place within the JavaScript agent in the web browser. As a result, sensitive information is prevented from reaching the Instana servers for processing. Sensitive information remains inaccessible for analysis in the UI or retrieval through the API.

ineum('fragment', fragment);

If a segment of your URL path matches an entry in the list, the fragment value is redacted and not sent to the Instana backend. By default, Instana does not redact URL fragments.

Parameter

Parameter Description
fragment (RegExp[]) An array with a RegExp object that matches the URL path whose fragment is redacted.

Example

ineum('fragment', [/example.com/i]);

For example, https://example.com/accounts/status?account=acount_name#fragmentinformation is collected and displayed as https://example.com/accounts/status?account=acount_name#<redacted>.

Excluding User-Timings from tracking

Instana automatically collect markers and measures that are made through the User-Timing API and turn them into custom events. This means that the User-Timing API can be used as a vendor-neutral way to report pure timing data to Instana.

By using the User-Timing API, you can define several regular expressions that, when at least one matches, does not result in a collection of specific user-timings. By default, the following conditions are ignored:

  • React's user-timings: the marks and measures that start with the ⚛️ or ⛔ emoji
  • Angular's user-timings: the marks and measures that start with Zone
  • Marks and measures whose names start with either start or end
ineum('ignoreUserTimings', ignoreUserTimings);

Parameter

Parameter Description
ignoreUserTimings (RegExp[]) An array of RegExp objects matching names of user timing marks and measures you want to ignore.

Example

ineum('ignoreUserTimings', [
  /^\u269B/,
  /^\u26D4/,
  /^Zone(:|$)/,
  /mySecretTiming/i
]);

Configuring Maximum Waiting after Page Load

To collect additional metrics, for example first input delay and cumulative layout shift, the JavaScript agent waits until

  • All the metrics are available
  • The page is unloaded (for example tab is closed)
  • Until a maximum waiting time elapses

You can use this API to re-configure the maximum waiting time. By default, Instana waits for up to one second after the page load is finished that is the onLoad event ends.

ineum('maxMaitForPageLoadMetricsMillis', durationMillis);

Parameter

Parameter Description
durationMillis (number) The maximum time in milliseconds to wait after the page load has finished before the page load beacon is transmitted.

Example

ineum('maxMaitForPageLoadMetricsMillis', 500);

Retrieving the Page Load ID

It can sometimes be useful to manually receive the ID of the page load, e.g. when wanting to do custom correlation. This function returns undefined till the JavaScript agent is not loaded. After the JavaScript agent is loaded, it always returns the same string.

ineum('getPageLoadId');

Returns

The page load ID as a string or undefined.

Example

var pageLoadId = ineum('getPageLoadId');
console.log(pageLoadId);

Error tracking

Manual error reporting

It is possible to report caught errors. This can be used to integrate Instana with frameworks and libraries that catch uncaught errors.

ineum('reportError', error, opts);
Parameter
Parameter Description
error (Error or string) JavaScript Error object or an error message.
opts (ErrorReportingOpts, optional) An object that looks like as follows.
{
  componentStack: '...' // an optional string

  meta: {               // An optional JavaScript object with `string` values which can be used
    widgetType: 'chart' // to send metadata to Instana just for this singular event. In contrast to
  }                     // the usage of the metadata API, this metadata is not included in subsequent
                        // beacons.
}
Example
ineum('reportError', new Error('Something failed'), {
  componentStack: '…',
  meta: {
    widgetType: 'chart'
  }
});
React integration

It is possible to get better error insights when you integrate the JavaScript agent with React error boundaries. Specifically, it results in component stack traces to be available in addition to the error (function) stack traces.

The following code snippet shows how React's componentDidCatch can be extended to achieve this integration. For more information about componentDidCatch lifecycle, see the React documentation.

componentDidCatch(error, info) {
  ineum('reportError', error, {
    componentStack: info.componentStack
  });

  // your regular error boundary code
}
Angular 2+ integration

Angular catches all errors by default and log them to the console. This means that the JavaScript agent does not have access to these errors. The following TypeScript snippet shows how to integrate Angular's caught errors with Instana.

For more information about Angular error handlers, see the Angular documentation.

import { ErrorHandler, NgModule } from '@angular/core';

class CustomErrorHandler implements ErrorHandler {
  handleError(error) {
    ineum('reportError', error);

    // Continue to log caught errors to the console
    console.error(error);
  }
}

@NgModule({
  providers: [{ provide: ErrorHandler, useClass: CustomErrorHandler }],
})
class MyModule {
  // the rest of your application code…
}
Vue integration

Vue can assign a global handler for uncaught errors that are propagated from the application. The following code snippet shows how to integrate Vue's error handling with Instana.

For more information about Vue error handlers, see the Vue documentation.

app.config.errorHandler = (err, instance, info) => {
  ineum('reportError', err);
  // your regular error handling code
}

Excluding errors from tracking

It is possible to explicitly stop some errors from being reported to Instana. This can be used to ignore known or unfixable errors.

ineum('ignoreErrorMessages', ignoreErrorMessages);
Parameter
Parameter Description
ignoreErrorMessages (RegExp[]) An array of RegExp objects to match the errors you want to exclude from error tracking.
Example
ineum('ignoreErrorMessages', [/^script error/i]);

Insights Into Script errors

Websites embedding many third-party scripts typically encounter a steady number of Script Errors. Instana provides guidance on how to make these errors accessible, that is how to get access to the real error message and stack. Sometimes, you might not be able to follow these instructions, for example because the third-party does not add the necessary Access-Control-Allow-Origin header. For these case, Instana provides alternative means to improve insights into Script Errorss.

This mechanism is no silver bullet. It grants you improved visibility and you encounter more helpful tracked errors, but you will still see (a reduced number of) Script Errors. For more information, see the cross-origin guidance.

Explicit tracking Of DOM Event Listener errors

This puts the Instana agent into the call stack of every DOM event listener. The Instana agent automatically puts try/catch statements around the event listeners' functions. This allows better insights into cross-origin errors.

This feature is disabled by default as the value is questionable for most of our customers. Furthermore, it is not guaranteed that better information about script errors can be collected by doing this as web browsers have started to patch this hole in the web security model.

ineum('wrapEventHandlers', enabled);
Parameter
Parameter Description
enabled (boolean) The flag for disabling or enabling this feature.
Example
ineum('wrapEventHandlers', true);
Explicit tracking Of Timer errors

This puts the Instana agent into the call stack of all timers. The Instana agent automatically put try/catch statements around the timer handlers' functions. This allows better insights into cross-origin errors.

This feature is disabled by default as the value is questionable for most of our customers. Furthermore, it is not guaranteed that better information about script errors can be collected by doing this as web browsers have started to patch this hole in the web security model.

ineum('wrapTimers', enabled);
Parameter
Parameter Description
enabled (boolean) The flag to disable or enable this feature.
Example
ineum('wrapTimers', true);
Ignoring Script errors

If you aren't able to get insights into script errors using any of the previously mentioned mechanisms, you might want to stop them from being reported to Instana. This can be useful to ensure that error statistics remain actionable. To stop script errors from being reported to Instana, you can use the following snippet.

ineum('ignoreErrorMessages', [/^script error/i]);

Reporting Custom events

For more information on Global Custom Events, see the Events page.

Custom events enable reporting about nonstandard activities, important interactions, and custom timings to Instana. This can be especially helpful when analyzing uncaught errors (breadcrumbs) and to track additional performance metrics.

ineum('reportEvent', eventName, {
  duration: duration,
  timestamp: timestamp,
  backendTraceId: backendTraceId,
  error: error,
  componentStack: componentStack,
  meta: meta,
  customMetric: customMetric
});

Parameter

Parameter Description
eventName (string) Defines what kind of event happened on your website that might result in the transmission of a custom beacon.
timestamp (number, optional) A timestamp indicates at which time the event took place. Falls back to now() - duration when not defined.
duration (number, optional) The duration in milliseconds of how long the event took.
backendTraceId (string, optional) Use this parameter to relate a beacon to a backend trace. Its value must be a hex string with 16 or 32 characters.
error (Error, optional) A JavaScript error object to provide more context. If you want to report that an error occurred, use the dedicated error reporting API.
componentStack (string, optional) A string representing a component hierarchy. Typically provided by component-based frameworks.
meta (object, optional) A JavaScript object with string values, which can be used to send metadata to Instana just for this singular event. In contrast to the usage of the metadata API, this metadata is not included in subsequent beacons.
customMetric (number, optional) A custom metric data with precision up to four decimal places. Do not include sensitive information in this metric.

Example

ineum('reportEvent', 'login');

ineum('reportEvent', 'full example', {
  timestamp: Date.now(),
  duration: 42,
  backendTraceId: '31ab91fc109223fe',
  error: new Error('whooops – sorry!'),
  componentStack: 'a component stack',
  meta: {
    state: 'running'
  },
  customMetric: 123.2342
});

Cross-Origin request backend correlation

Instana's backend correlation works by setting custom headers on XMLHttpRequest / fetch requests. The JavaScript agent sets these headers that are then read by the server. Within the browser, the same-origin policy restricts the transmission of custom headers. More specifically, custom headers can be set only for same-origin requests or for requests to other origins that allow transmission of custom headers. For example, by default a website that is being served by https://example.com:443 cannot make XMLHttpRequests to https://shop.example.com:443 as these are two different origins.

To work around this security restriction, cross-origin resource sharing (CORS) is available. With CORS, origins can be allowed for cross-origin resource access. If you already have cross-origin resource access within your application, then you are most likely already using some CORS headers.

To enable Instana backend correlation, complete the following steps:

  1. Allow Instana's correlation headers for cross-origin requests by responding on the server-side with the following headers.

    Your server must respond with these headers for both preflight requests and regular requests. Preflight requests (identifiable through the OPTIONS HTTP method) are executed by the browser to verify that requests might be issued to the server.

    Access-Control-Allow-Origin: https://your-origin.example.com
    Access-Control-Allow-Headers: X-INSTANA-T, X-INSTANA-S, X-INSTANA-L
    
  2. Inform the JavaScript agent that CORS is configured correctly and that it must set these correlation headers:

    ineum('allowedOrigins', urls);
    

Parameter

Parameter Description
urls (RegExp[]) An array of RegExp objects to match allowed URLs.

Since

The allowedOrigins command is available with Instana Release 185 and later. Use the alias whitelistedOrigins with older releases.

Alias

The command whitelistedOrigins is a deprecated alias for allowedOrigins.

Example

ineum('allowedOrigins', [/.*api\.example\.com.*/]);

Check that your application works correctly after these changes. Instructing the JavaScript agent to add backend correlation headers (that is allowing origins) without configuring CORS on the server side, has a high probability of breaking your website!

Capture HTTP request or response headers

The HTTP request or response headers on XMLHttpRequest or fetch requests can be captured by the JavaScript agent. You can define the HTTP headers that you want the JavaScript agent to capture by the captureHeaders command.

Within the browser, the same-origin policy restricts the access of custom headers. Without cross-origin resource sharing (CORS) configuration, the JavaScript agent might not be able to capture all HTTP headers. To enable CORS, see Cross-Origin Request Backend Correlation. With CORS, only the CORS-satisfied request or response headers and the ones that are defined in Access-Control-Expose-Headers can be collected by the JavaScript agent.

Notes:
  • For headers in request, usually you can capture only the headers that you add to the HTTP request, not the built-in ones that are added by the browser. For example, the User-Agent header is a characteristic string with which servers and network peers identify the application, operating system, vendor, and version of the requesting user agent. It is added by the browser and cannot be captured by the JavaScript agent.
  • For headers in response, if not blocked by cross-origin policy, both built-in or custom headers from server side can be captured by the JavaScript agent.

Parameter

Parameter Description
captureHeaders (RegExp[]) An array of RegExp objects to match the key of HTTP request or response headers that you want the JavaScript agent to capture.

Since

The captureHeaders command is available from Instana release 216.

Example

ineum('captureHeaders', [/content-type/i]);