React Native Monitoring API

Instana React Native agent API

The following section describes how to use the Instana React Native agent. You can use the Instana React Native agent through the Instana class methods that are explained here.

React Native agent supports TypeScript projects from version 2.0.6.

Setup

Initialize Instana in your App class componentDidMount(), as early as possible:

export default class App extends Component {
  componentDidMount() {
    Instana.setup(YOUR_INSTANA_APP_KEY, YOUR_INSTANA_REPORTING_URL, null);
    // Alternatively with configuration options
    Instana.setup(YOUR_INSTANA_APP_KEY, YOUR_INSTANA_REPORTING_URL, {'collectionEnabled': false});
  }
}

The following code is a TypeScript definition:

setup(your_instana_app_key: string, your_instana_app_reportingUrl: string, options?: Object): void;
setup(your_instana_app_key: string, your_instana_app_reportingUrl: string, {collectionEnabled: boolean}): void;

Setup parameters

Table 1. Setup parameters
Parameter
Description
key (String) Instana monitoring configuration key
reportingURL (String) URL pointing to the Instana instance to which the monitoring data should be sent

Session identifier

Each Instana agent instance has a unique session identifier that you might use for other purposes in your app.

static getSessionID()

The following code is a TypeScript definition:

getSessionID(): Promise<string>;

Session identifier parameters

Returns: Promise(String)

Session identifier example

var sessionID = await Instana.getSessionID();

Automatic HTTP monitoring

Instana agent provides automatic monitoring of HTTP requests.

Views

Instana can segment mobile app insights by logical views. To do so, set the view name by using the Instana.setView(String) method. The view is then associated to all monitored beacons until the view changes when setView is called again.

Do not use technical or generic names like the Class (for example, WebViewActivity) to define views. Instead, use readable names for views (for example, product detail page or payment selection). By focusing on the user experiences, team members who do not have intimate knowledge of the codebase can understand the insights that are provided.

Instana.setView(String) is called when a screen is presented to the user, rather than when a screen is created (as in a Fragment that might be created once but shown multiple times). When you set the view name, Instana can track page transitions in addition to page loads.

static setView(String name)

The following code is a TypeScript definition:

setView(name: string): void;

Views parameters

Table 2. Views parameters
Parameter
Description
name (String) The name of the view.

Views example

Instana.setView('Webview: FitBit authorization');

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 the following examples:

  • Calculate the number of users affected by errors
  • Filter data for specific users
  • See which user initiated a view change or HTTP request

By default, Instana does not associate any user-identifiable information to beacons. Be aware of the respective data protection laws when you are choosing to do so. Identify users through a user ID. For Instana, it is a transparent String that is used only to calculate certain metrics. userName and userEmail can also be used to have access to more filters and a better presentation of user information.

In cases where you are handling anonymous users and thus don't have access to user IDs, you might alternatively use session IDs. Session IDs are not as helpful as user IDs when you are filtering data but they are a good indicator to calculate affected or unique user metrics. Set a username such as Anonymous to have a clear differentiation between authenticated and unauthenticated users. Session IDs can be sensitive data (depending on the framework or platform used). Consider hashing session IDs to avoid transmitting data to Instana that can grant access.

Data already transmitted to Instana's server cannot be retroactively updated. For this reason, it is important to call this API as early as possible in the app launch process.

static setUserID(String ID)
static setUserName(String email)
static setUserEmail(String name)

The following code is a TypeScript definition:

setUserID(id: string): void;
setUserName(name: string): void;
setUserEmail(email: string): void;

User parameters

Table 3. User parameters
Parameter
Description
ID (String) An identifier for the user.
email (String) The user's email address.
name (String) The user's name.

User example

export default class App extends Component {
  componentDidMount() {
    Instana.setup(YOUR_INSTANA_APP_KEY, YOUR_INSTANA_REPORTING_URL);
    Instana.setUserID('1234567890');
    Instana.setUserEmail('instana@example.com');
    Instana.setUserName('instana react-native agent demo');
  }
}

Metadata

Arbitrary metadata can be attached to all data that is transmitted to Instana. You can use it to track UI configuration values, settings, feature flags, and any additional context that might be useful for analysis.

Instana currently supports up to 50 meta key-value pairs.

static setMeta(String key, String value)

The following code is a TypeScript definition:

setMeta(key: string, value: string): void;

Metadata parameters

Table 4. Metadata parameters
Parameter
Description
value (String) The value of the key-value pair you want to add as metadata.
key (String) The key of the key-value pair you want to add as metadata.

Metadata example

export default class App extends Component {
  componentDidMount() {
    Instana.setMeta('randomKey1', 'randomValue1');
    Instana.setMeta('randomKey2', 'randomValue2');
  }
}

Report custom events

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

static reportEvent(String eventName, {
  startTime: Number startTime,
  duration: Number duration,
  viewName: String viewName,
  backendTraceId: String backendTraceId,
  meta: Map meta
})

The following code is a TypeScript definition:

reportEvent(eventName: string, options?: {
  startTime?: number;
  duration?: number;
  viewName?: string;
  meta?: Map<string, string>;
  backendTracingId?: string;
  customMetric?: number;
 }): void;

Custom events parameters

Table 5. Custom events parameters
Parameter
Description
eventName (String) Defines what kind of event, which happened in your app, should result in the transmission of a custom beacon
startTime (Number, optional) A timestamp in milliseconds since Epoch indicating at which time the event started. Changes back to now() - duration when not defined.
duration (Number, optional) The duration in milliseconds of how long the event lasted. The default is zero.
viewName (String, optional) A string that you can pass to group the request to a view. If you send explicitly nil, the viewName is ignored. Alternatively you can leave out the parameter viewName to use the current view name that you set in setView(String name)).
backendTracingId (String, optional) Identifier to create a backend trace for this event
meta (object, optional) A JavaScript object with string values that 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 (double, optional) Custom metric data with precision up to 4 decimal places. Do not include sensitive information in this metric.

Custom events example

Instana.reportEvent('myCustomEvent', {
  startTime: Date.now() - 500,
  duration: 300,
  viewName: 'overridenViewName',
  backendTracingId: '31ab91fc1092',
  meta: {
    state: 'running'
  },
  customMetric: 123.4567
});

Excluding URLs from Monitoring

URLs can be ignored by providing regular expressions or by adding them to the ignoreURLs list. This function is useful when you want to ignore all HTTP requests that contain any sensitive data such as a password.

Keep in mind that the agent needs to convert each string that you provide to the setIgnoreURLsByRegex method into a native regex expression for each supported platform. You can track promise rejections, which inform you about any issue that the agent encountered while you are interpreting your input.

static setIgnoreURLsByRegex([]String regexArray)

The following code is a TypeScript definition:

setIgnoreURLsByRegex(regexArray: Array<string>): Promise<any>;

Exclude URL parameters

Table 6. Exclude URL parameters
Parameter
Description
regexArray An array of String objects containing the regex matching the URLs you want to ignore.

Returns: Promise(Boolean). If rejected, the exception contains a list of all the parameters that failed to be converted to native regex.

Exclude URL example

export default class App extends Component {
  componentDidMount() {
    setIgnoreURLsByRegex();
    async function setIgnoreURLsByRegex() {
      try {
        await Instana.setIgnoreURLsByRegex(["http:\/\/localhost:8081.*", "/.*([&?])password=.*/i"]);
      } catch (e) {
        console.warn(e);
      }
    }
  }
}

The example ignores all queries to the Metro bundler and all URLs that contain a password in the query.

Redact URL query parameters

Query parameters that are in the collected URLs might contain sensitive data. Therefore, the Instana agent supports the specification of regex patterns for query parameter keys whose values need to be redacted. Any value that needs to be redacted is replaced with the string <redacted>. The redaction happens within the Instana agent before the agent reports to the Instana server. Therefore, secrets do not reach the Instana servers for processing and are not available for analysis in the Instana UI or retrieval by using Instana API.

By default, the Instana agent is configured with a list of three regex patterns to automatically redact query parameter values for the keys "password", "key", and "secret".

static setRedactHTTPQueryByRegex([]String regexArray)

The following code is a TypeScript definition:

setRedactHTTPQueryByRegex(regexArray: Array<string>): Promise<any>;

Redact URL query parameters

Table 7. Redact URL query parameters
Parameter
Description
regex ([NSRegularExpression]) An array of String matching the keys for the values that you want to redact.

Redact URL query example

export default class App extends Component {
  componentDidMount() {
    setRedactHTTPQueryByRegex();
    async function setRedactHTTPQueryByRegex() {
      try {
        await Instana.setRedactHTTPQueryByRegex(["pass(word|wort)"]);
      } catch (e) {
        console.warn(e);
      }
    }
  }
}

This example redacts the values for the HTTP parameter keys "password" or "passwort".

The captured URL https://example.com/accounts/?password=123&passwort=459 is collected and displayed as https://example.com/accounts/?password=<redacted>&passwort=<redacted>.

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

Capture HTTP headers

Optionally, the Instana agent can capture the HTTP headers of every tracked request and response.

A list of regex patterns can be defined to determine which headers should be captured.

If the same header name is present in both a request and its response, only the header value of the response is considered.

static setCaptureHeadersByRegex([]String regexArray)

The following code is a TypeScript definition:

setCaptureHeadersByRegex(regexArray: Array<string>): Promise<any>;

Capture HTTP headers example

export default class App extends Component {
  componentDidMount() {
    setCaptureHeadersByRegex();
    async function setCaptureHeadersByRegex() {
      try {
        await Instana.setCaptureHeadersByRegex(["cache-control", "etag"]);
      } catch (e) {
        console.warn(e);
      }
    }
  }
}

Slow sending mode

By default, the slow sending mode feature is disabled. If required, you can enable this feature.

By default, if the sending of a beacon fails, the Instana agent tries to resend the beacon until the beacon is successfully sent. However, this behavior does not work well with some cellular networks. By enabling the slow sending mode feature, you can change the interval of sending the beacon to the time value that is assigned to the slowSendInterval parameter. Each sending consists of only one beacon instead of a batch (a maximum of 100 beacons in a batch). The Instana agent stays in slow sending mode until one beacon is sent successfully.

The valid time range for the slowSendInterval parameter is 2-3600 seconds.

The following code is a TypeScript definition:

setup(key: string, reportingUrl: string, {slowSendInterval: number}): void;

Slow sending mode example

export default class App extends Component {
  componentDidMount() {
    var options = {}
    options.slowSendInterval = 120.0;
    Instana.setup('<your key>', '<your reporting url>', options);
  }
}

User session ID

By default, the user session is tracked and a Universally Unique Identifier (UUID) is randomly generated. This ID remains unchanged while the app is installed. You can configure the expiration time of the user session ID by using the usiRefreshTimeIntervalInHrs parameter.

The following parameter values indicate the status of the user session ID:

  • Negative number: This value indicates that the user session ID never expires. The default value is -1.

  • Positive number: This value means that the user session ID is refreshed after the set time. A new UUID is generated and used.

  • Zero: This value denoted by 0.0 means that the user session ID is disabled.

The following code is a TypeScript definition:

setup(key: string, reportingUrl: string, {usiRefreshTimeIntervalInHrs: number}): void;

User session ID example

export default class App extends Component {
  componentDidMount() {
    var options = {}
    options.usiRefreshTimeIntervalInHrs = 24.0;
    Instana.setup('<your key>', '<your reporting url>', options);
  }
}