npm package: @perceptinsight/percept-js
Description: The official Percept JavaScript browser client library
Latest version: 3.0.5

# percept-js

Official Percept JavaScript browser client library

## Quick Start Guide

### 1. Install

#### npm

```sh
npm install @perceptinsight/percept-js
```

#### yarn

```sh
yarn add @perceptinsight/percept-js
```

#### script tag

This SDK is also available through CDN. Copy the below script tag and paste before the </head> tag of every page you want to track.

```sh
<script crossorigin src="https://unpkg.com/@perceptinsight/percept-js"></script>
```

Once the script is loaded, you can use `window.percept` to access the methods

### 2. Initialize Percept SDK

```js
import Percept from '@perceptinsight/percept-js';

Percept.init('Your Project Token');
```

`init` method takes an optional `initOptions` param as second argument which can be used to configure auto tracked events and other settings.
`initOptions` properties:

| property                       | required | type                   | default value |
| ------------------------------ | -------- | ---------------------- | ------------- |
| `autoTrackPageviews`           | `false`  | `boolean`              | `true`        |
| `autoTrackRuntimeErrors`       | `false`  | `boolean`              | `true`        |
| `autoTrackWebvitals`           | `false`  | `boolean`              | `true`        |
| `autoTrackApiCalls`            | `false`  | `boolean`              | `true`        |
| `autoTrackStaticResourceCalls` | `false`  | `boolean`              | `false`       |
| `apiTrackingBlocklist`         | `false`  | `string` \| `string[]` | `[]`          |
| `autoFlushThresholdMs`         | `false`  | `number`               | 5000          |
| `autoFlushBatchSize`           | `false`  | `number`               | 50            |
| `autoCaptureClicks`            | `false`  | `boolean`              | `true`        |
| `enableLogs`                   | `false`  | `boolean`              | `false`       |
| `enableHeatmap`                | `false`  | `boolean`              | `true`        |
| `enableHotspot`                | `false`  | `boolean`              | `true`        |
| `enableExperiment`             | `false`  | `boolean`              | `false`       |
| `experimentFetchedCb`          | `false`  | `function`             | `undefined`   |
| `experimentRefetchIntervalMin` | `false`  | `number`               | `undefined`   |
| `callbacks`                    | `false`  | `function[]`           | `[]`          |

### 3. Set user id

After successfully initializing the SDK, On login set User id using the following function.

```JS
await Percept.setUserId('U1');
```

You can also pass user properties as part of this call as second parameter.

```JS
await Percept.setUserId('U1', {name: 'Test User'});
```

> NOTE: This is an asynchronous call

### 4. Set user properties

use `setUserProperties` method to set properties on the user profile created by `setUserId`

```JS
// first call this method
await Percept.setUserId('U1');

// sets user `isVerifiedAccount` property to true
Percept.setUserProperties({isVerifiedAccount: true})
```

We expose some default user property keys in `PerceptUserPropertyKeys`. Please use them as this helps in standarization and usage in the Engage feature provided by Percept.

```JS
import Percept, {PerceptUserPropertyKeys} from '@perceptinsight/percept-js'

// first call this method
await Percept.setUserId('U1');

// sets user `phone` property to '123456789' and `isVerifiedAccount` property to true
Percept.setUserProperties({[PerceptUserPropertyKeys.PHONE]: 123456789, isVerifiedAccount: true})
```

### 5. Send Event

Let's get started by sending event data. You can send an event from anywhere in your application.

```JS
// Track only event-name
Percept.capture('Referral Banner Click');
// Track event-name with property
Percept.capture('Screen View', {'screenName': 'Homepage'});
```

### 6. Timing Events

You can track the time it took any action to complete using `timeEvent` method. Calling this method will mark the start of the action and subsequent call to capture method will mark the end. The time duration is recorded in `pi_timed_event_duration` property.

```JS
// Start the time for the event 'Image Upload'
Percept.timeEvent('Image Upload');
// ... some time later. This call capture the 'Image Upload' event with 'pi_timed_event_duration' property
Percept.capture('Image Upload');
```

### 7. Set Global Property

Set global property which will be passed with all subsequent events

```JS
Percept.setGlobalProperty('global-property-key', 'value');
```

### 8. Remove Global Property

Remove any previously set global property

```JS
Percept.removeGlobalProperty('global-property-key');
```

### 9. Get all global properties

Get all global properties

```JS
Percept.getAllGlobalProperties();
```

### 10. Clear

Call clear function on logout to delete all user related information

```JS
await Percept.clear()
```

## Events auto tracked by sdk

### 1. Page Views with utm params

Page views are auto tracked as `$pageView` event. It can be disabled by setting `autoTrackPageviews` to false in init options.\
It has `url` property. Following properties are also available when found in url:\
 `utm_source`, `utm_medium` & `utm_campaign`\

### 2. Web vitals

Web vitals are tracked as `$webVitals` event. It has following properties:\
`pi_metric_id`\
`pi_metric_name` - CLS/FCP/FID/INP/LCP/TTFB\
`pi_metric_value`\
`pi_metric_rating` - good/bad/needs improvement\
`pi_metric_navigation_type`\
`pi_metric_debug_target` - origin target if available\
`url` - the page from which this metric was captured

You can read more about web vitals here: https://web.dev/articles/vitals

### 3. Unhandled runtime errors

Unhandled runtime errors are tracked as `$unhandledError` event. It can be disabled by setting `autoTrackRuntimeErrors` to false in init options.\
Following properties are available as part of this event:
| property |
| -------------------------- |
| pi_unhandled_error_event |
| pi_unhandled_error_url |
| pi_unhandled_error_line |
| pi_unhandled_error_col |
| pi_unhandled_error_stack |
| pi_unhandled_error_msg |
| pi_unhandled_error_name |
| url |

### 4. Network calls

Ajax calls are tracked as `$fetch` and other network calls are tracked as `$resource` event. It is disabled by default and can be enabled by setting `autoTrackApiCalls` to true in init options.\
You can ask Percept Insight to not track certain network calls by passing the relevant url string/regex or string array in `apiTrackingBlocklist` parameter in init options.

All [performance resource timing data](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming) provided by browser are available as properties of these events.

Following extra properties are available as part of `$fetch` event:
| property |
| -------------------------- |
| pi_fetch_url |
| pi_fetch_status_code |
| pi_fetch_status_text |
| pi_fetch_request_type |
| pi_fetch_successful |
| pi_fetch_time_taken |

## Handling Experiments

### 1. Enabling Experiments

To enable experiment tracking, set the `enableExperiment` option to `true` in the `initOptions`. You can also specify a callback function to handle the experiment data when it is fetched.

```JS
const initOptions = {
  enableExperiment: true,
  experimentFetchedCb: (data) => {
    const { experimentData, experimentUserType, isExperimentDataResolved } = data;
    if (isExperimentDataResolved) {
      console.log('Experiment data fetched:', experimentData);
    } else {
      console.log('Experiment data could not be resolved.');
    }
  },
  experimentRefetchIntervalMin: 10, // Refetch experiment data every 10 minutes
};

Percept.init('Your Project Token', initOptions);
```

Note: The `experimentRefetchIntervalMin` option sets the interval in minutes for automatically refetching experiment data. The interval must be at least 5 minutes. If a value less than 5 is provided, it will be automatically set to 5 minutes and a warning will be logged.

### 2. Fetching Experiment Data

You can fetch experiment data at any time using the `getExperiment` method. This method returns a promise that resolves to the variant data for the specified experiment.

```JS
const experimentName = 'example-experiment';
const variant = await Percept.getExperiment(experimentName);

if (variant) {
  console.log(`User is in variant: ${variant}`);
} else {
  console.log('No variant data available');
}
```

### 3. Refetching Experiment Data

If you have set the `experimentRefetchIntervalMs` option, the SDK will automatically refetch the experiment data at the specified interval. You can also manually refetch the experiment data using the `refetchExperiment` method.

```JS
await Percept.refetchExperiment();
```

### 4. Getting All Active Experiments

You can get all active experiments and their variants using the `getAllActiveExperiments` method.

```JS
const activeExperiments = await Percept.getAllActiveExperiments();
console.log('Active experiments:', activeExperiments);
```

### 5. Getting Experiment User Type

You can get the user type for experiments using the `getExperimentUserType` method.

```JS
const userType = await Percept.getExperimentUserType();
console.log('Experiment user type:', userType);
```