Website Monitoring API

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 has not been downloaded yet. This was done to make ineum API calls easy and efficient.

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

API Structure

All ineum calls follow the same structure. They look like this:

ineum(commandName, ...args)

Parameters

  • commandName (string): Identifies what command should be executed, e.g. set meta data or report an error.
  • ...args: The actual arguments for the particular command. The number of arguments and their type are specific to each command and are explained within the following sections in more detail.

Note that the function ineum never returns anything (with the exception of command getPageLoadId, see below).

APIs

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

Monitoring Key

Monitoring keys can be set via the key command. The monitoring key can be seen when configuring websites within the Instana user interface.

ineum('key', trackingKey);

Parameters

  • trackingKey (string): The monitoring key for the website configuration in Instana.

Examples

A correct configuration is shown within the Instana user interface.

Reporting URL

When deployed in On-Premises environments, the tracking script is not supposed to send its data to instana.io. Instead, it needs to send data to the On-Premises installed Instana backend. The reportingUrl command can be used to configure this URL.

ineum('reportingUrl', reportingUrl);

Parameters

  • reportingUrl (string): The URL to which to send website monitoring data to.

Examples

A correct configuration is shown within the Instana user interface.

Page

Instana can segment website metrics by logical pages. To do so, it needs a hint what page the user is currently looking at. This page name can be set via the page command. We recommend to set the page as early as possible. Additionally, it is perfectly fine to change the page at some point to present document changes (e.g. for single-page applications). This will enable Instana to track page transitions in addition to page loads.

ineum('page', pageName);

Parameters

  • pageName (string): The name of the page.

Examples

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

Generally speaking, we recommend not to use window.title or window.href to define pages. This will result in a large number of tracked pages that will not provide value in the majority of cases, e.g. because window.title contains product names. Instead, we recommend the usage of logical names for pages. For example product detail page or payment selection. This will result in fewer pages which will have a direct relation to actually existing code.

We provide sample projects that show how to collect meaningful page names for a variety of frameworks and libraries. Should your framework/library be missing, feel free to raise a pull or support request.

Identifying Users

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

  • calculate the number of users affected by errors,
  • to filter data for specific users and
  • to see which user initiated a page load / AJAX call.

By default, Instana will not associate any user-identifiable information to beacons. Please be aware of the respective data protection laws when choosing to do so. We generally recommend identification of users via a user ID. For Instana this is a completely transparent string that is only used to calculate certain metrics. userName and userEmail can also be used to have access to more filters and a more pleasant presentation of user information.

In cases in which you are handling anonymous users and thus don’t have access to user IDs you could alternatively use session IDs. Session IDs are not as helpful as user IDs when filtering data but they are a good indicator to calculate affected/unique user metrics. We recommend setting a user name such as Anonymous to have a clear differentiation between authenticated and unauthenticated users. Session IDs can be sensitive data (depending on the framework/platform used). Please consider hashing session IDs to avoid transmitting data to Instana that can grant access.

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

Parameters

  • userId (string, optional): An identifier for the user.
  • userName (string, optional): The user name.
  • userEmail (string, optional): The user’s email address.

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

Examples

// 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');

Meta Data

Meta data can be used to annotate page loads and AJAX calls. Consider using this to track UI configuration values, settings, feature flags… any additional context that might be useful for analysis.

ineum('meta', key, value);

Parameters

  • key (string): The key of the key-value pair you want to add as meta data.
  • value (string): The value of the key-value pair you want to add as meta data.

Examples

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/backend correlation. See our dedicated section on backend correlation for more details. This is only required in order to gain correlation between page loads’ backend and frontend processing. It is not required for correlation between XMLHttpRequest or fetch requests.

ineum('traceId', traceId);

Parameters

  • traceId (string): The trace ID of the associated backend trace.

Examples

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

Excluding URLs from Tracking

It is common to call some APIs from JavaScript (e.g. via XMLHttpRequest or fetch) to ensure that a connection is working or for WebSocket fallback purposes such as long polling. While this can be tracked, it is often not very helpful to track these types of AJAX calls. Using the ignoreUrls command, an array of regular expressions can be set for which no AJAX calls will be tracked.

ineum('ignoreUrls', ignoreUrls);

Parameters

  • ignoreUrls (RegExp[]): An array of RegExp objects matching the URLs you want to ignore.

Examples

ineum('ignoreUrls', [
  /\/comet.+/i,
  /\/ws.+/i
]);

Resource Timing Buffer Clearing

Whether or not the resource timing buffer is cleared after collecting resource timing information. This is used to ensure that the buffer always has sufficient capacity for new resource timing entries. This defaults to true.

ineum('autoClearResourceTimings', automaticallyClear);

Parameters

  • automaticallyClear (boolean): The flag for enabling/disabling this feature.

Examples

ineum('autoClearResourceTimings', false);

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 will return undefined as long as the JavaScript agent hasn’t been loaded yet. Once loaded, it will always return the same string.

ineum('getPageLoadId');

Returns

  • The page load ID as a string or undefined.

Examples

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);
Parameters
  • error (string): The error message.
  • opts (ErrorReportingOpts, optional): An object that looks like this:
{
  componentStack: '...' // an optional string, see below
}
Examples
ineum('reportError', new Error('Something failed'), {
  componentStack: '…'
});
React Integration

It is possible to get better error insights when integrating the JavaScript agent with React error boundaries. Specifically, it will result 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. Refer to the React documentation for more information about the componentDidCatch lifecycle.

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

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

Angular will catch all errors by default and log them to the console. This means that the JavaScript agent will never have access to these errors. The following TypeScript snippet shows how to integrate Angular’s caught errors with Instana.

Refer to the Angular documentation about error handlers to learn more.

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…
}

Excluding Errors from Tracking

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

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

Insights Into Script Errors

Websites embedding a large number of third-party scripts typically encounter a steady number of Script Errors. We do provide guidance on how to make these errors accessible, i.e. how to get access to the real error message and stack. Sometimes though, you may not be able to follow these instructions, e.g. because the third-party will not add the necessary Access-Control-Allow-Origin header. For these case, we provide alternative means to improve insights into Script Errorss.

Please note that 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. We still advise to read through and attempt implementation of the cross-origin guidance first.

Explicit Tracking Of DOM Event Listener Errors

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

This feature is disabled by default.

ineum('wrapEventHandlers', enabled);
Parameters
  • enabled (boolean): The flag for disabling/enabling this feature.
Examples
ineum('wrapEventHandlers', true);
Explicit Tracking Of Timer Errors

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

This feature is disabled by default.

ineum('wrapTimers', enabled);
Parameters
  • enabled (boolean): The flag for disabling/enabling this feature.
Examples
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 may want to stop them from being reported to Instana. This can be useful in order 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]);

Cross-Origin Request Backend Correlation

Instana’s backend correlation works by setting custom headers on XMLHttpRequest / fetch requests. These headers are set by the JavaScript agent and then read by the server. Within the browser, the transmission of custom headers is restricted by the same-origin policy. More specifically, custom headers can only be set for same-origin requests or for requests to other origins which allow custom headers to be transmitted. For example, a website being served by https://example.com:443 cannot by default 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 whitelisted 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, the following needs to be done:

  1. Allow Instana’s correlation headers for cross-origin requests by responding on the server side with the following headers. Please note that your server must respond with these headers for both preflight requests and regular requests. Preflight requests (identifiable via the OPTIONS HTTP method) are executed by the browser to verify that requests may 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
  1. Inform the JavaScript agent that CORS was correctly configured and that it should set these correlation headers:
ineum('whitelistedOrigins', urls);

Parameters

  • urls (RegExp[]): An array or RegExp objects to match whitelisted URLs.

Examples

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

Please make sure that your application works correctly after those changes. Instructing the JavaScript agent to add backend correlation headers (i.e. whitelisting origins) without configuring CORS, has a high probability of breaking your website!