Avo Inspector Web SDK
Quick Start Guide
Find the Quick Start Guide in our GitHub repo.
1. Installation
Installation option 1: NPM / Yarn
Inspector library is available through npm. Run the following command to install it:
npm install avo-inspectorImport
import * as Inspector from 'avo-inspector';Initialization
Obtain the API key in the Sources tab in your Avo.app workspace.
You will need to create an instance of AvoInspector with the constructor:
constructor(options: {
apiKey: string;
env: AvoInspectorEnv;
version: string;
appName?: string;
suffix?: string;
publicKey?: string;
});All the following methods are available in the AvoInspector class.
Parameters:
apiKey- the API key you get in your Avo accountenv- current environment:"dev","staging"or"prod"appVersion- your application version. A lot of Inspector features rely on versioning and you need to provide a comparable string here to get value from them. We recommend using semantic versioning or integers that are incremented in every release.appName- your application name. Optional; Provide it to make it easier to distinguish between data from different apps.suffix- optional. If you are using more than 1 instance of Avo Inspector in the same project provide a unique string here.publicKey- optional. Your 64-character hex public key for property value validation. Generate keys usingavo inspector generate-keys.
Property value validation
You can enable property value validation to validate property values against the constraints defined in your tracking plan, such as allowed values, regex patterns, and min/max ranges.
To enable property value validation:
- Enable property value validation in settings - Go to workspace settings in your Avo workspace and enable property value validation.
To be able to decrypt the property values in the Inspector Debugger, you need to generate a public/private key pair:
Step 1: Generate encryption keys
Run the following command in the Avo CLI to generate a public/private key pair:
node -e "const { createECDH } = require('crypto'); const ecdh = createECDH('prime256v1'); ecdh.generateKeys(); console.log('Private Key:', ecdh.getPrivateKey('hex')); console.log('Public Key:', ecdh.getPublicKey('hex', 'compressed'));"This will output:
- Public key - Used by Avo to encrypt property values
- Private key - Used by you to decrypt values in the Inspector Debugger
Step 2: Store your private key securely
Save your private key in a secure location like a password manager. You’ll need this to decrypt values in the Inspector Debugger. Never share or expose your private key to a third party.
Step 3: Add the public key to the Inspector initialization
Pass the public key in the constructor options:
const inspector = new Inspector.AvoInspector({
apiKey: 'YOUR-API-KEY',
env: 'dev',
version: '1.0.0',
appName: 'My App',
publicKey: 'YOUR-64-CHARACTER-HEX-PUBLIC-KEY',
});Once enabled, property values will be encrypted and sent to Avo for validation. You can view the encrypted values and any property value issues in the Inspector Debugger, and decrypt them locally using your private key.
Installation option 2: HTML Tag
Warning! This step is not enough to connect Avo Inspector. Make sure to proceed to step 2 to complete your setup.
Paste the HTML script tag snippet within the <head> tag of your page, or into a tag manager like Google Tag Manager (GTM).
When pasting the HTML script snippet into GTM, paste it into a GTM Tag and have it load as early as possible. It needs to be loaded before you call your events.
Make sure to update __API_KEY__, __ENV__, __VERSION__ and __APP_NAME__ based on your project. Obtain the API key in the Sources tab in your Avo.app workspace.
<script>
!(function () {
var t = (window.inspector = window.inspector || []);
(t.methods = [
'trackSchemaFromEvent',
'trackSchema',
'setBatchSize',
'setBatchFlushSeconds',
]),
(t.factory = function (e) {
return function () {
var r = Array.prototype.slice.call(arguments);
return r.unshift(e), t.push(r), t;
};
});
for (var e = 0; e < t.methods.length; e++) {
var r = t.methods[e];
t[r] = t.factory(r);
}
(t.load = function () {
var t = document.createElement('script');
(t.type = 'text/javascript'),
(t.async = !0),
(t.src = 'https://cdn.avo.app/inspector/inspector-v1.min.js');
var e = document.getElementsByTagName('script')[0];
e.parentNode.insertBefore(t, e);
}),
(t._scriptVersion = 1);
})();
// Update the following variables to match your project.
inspector.__API_KEY__ = 'YOUR-API-KEY';
inspector.__ENV__ = 'dev'; // or "prod"
inspector.__VERSION__ = 'YOUR-APP-VERSION';
// inspector.__APP_NAME__ = "YOUR-APP-NAME"; // Optional
// inspector.__PUBLIC_KEY__ = "YOUR-64-CHARACTER-HEX-PUBLIC-KEY"; // Optional, for property value validation
inspector.load();
</script>When Setting Up GTM, you can use the inspect tool in your browser to see if your GTM tag is firing the track call correctly.
To enable property value validation with the HTML tag, uncomment the __PUBLIC_KEY__ line and add your public key. See the property value validation section above for instructions on generating keys.
2. Send event schemas to Avo Inspector
This is the core of the Avo Inspector SDK.
Call **one of the methods** in this section every time an event is tracked.
Track option 1
inspector.trackSchemaFromEvent(eventName: string, eventProperties: {
[propName: string]: any;
}): void;Extracts the event schema from event properties represented by the second parameter ({ [propName: string]: any; }) and sends the schema to Avo for analysis.
Parameters:
eventName- string event name, also known as event type.eventProperties- The actual event properties, which will be converted to an event schema on the device and the event schema sent to Avo. The resulting keys will be object field names and the values will be object field value types converted to schema types.Example format:
var eventProperties = { userId: 1337, emailAddress: 'jane.doe@avo.app', key: 'value', };
Track option 2
inspector.trackSchema(eventName: string, eventSchema: Array<{
propertyName: string;
propertyType: string;
children?: any;
}>): void;This method allows you to process the event schema before sending it.
It’s handy to extract the schema from your event properties with extractSchema (see below), process it, and then provide it to this method.
Parameters:
eventName- string event name, also known as event type.eventSchema- actual event schema that will be sent to Avo. Keys are event parameters names and values are event parameters types.Example format:
var returnedSchema = [ { propertyName: 'userId'; propertyType: 'int'; }, { propertyName: 'emailAddress'; propertyType: 'string'; }, { propertyName: 'key'; propertyType: 'string'; }, ];See supported schema types here.
Other methods
1. Extract schema from event properties
inspector.extractSchema(eventProperties: {
[propName: string]: any;
}): Array<{
propertyName: string;
propertyType: string;
children?: any;
}>This is the method used by trackSchemaFromEvent internally. The event schema is extracted from the event properties’ JS object, itself in the form of a JS object as well.
Parameters:
eventProperties- An event properties object. Keys are event properties’ names and values are event properties’ values. The format is the same as theeventPropertiesparameter in thetrackSchemaFromEventmethod.Return Value:
- A JS object containing the event schema of the given event properties. The keys are the event properties’ names and the values are the event properties’ types. The format is the same as
eventSchemaparameter in thetrackSchemamethod.
2. Print logs
inspector.enableLogging(enable: boolean): void;enableLogging controls printing of tracked event schemas and other helpful information to logcat. Enabled by default in development environments.
Parameters:
enable- boolean flag that sets whether Avo Inspector SDK will print logs.
3. Controlling the batch size
setBatchSize(newBatchSize: number): void;Enables manual control over events batching. The default batch size in production is 30, i.e. the library attempts to send event schemas to the server when it has 30 or more schemas. In development batching is disabled by default.
Parameters:
int newBatchSize- sets batch size.
4. Controlling the batching interval
setBatchFlushSeconds(newBatchFlushSeconds: number): void;Enables manual control over events batching. The default production batch flush interval is 30 seconds, i.e. the library attempts to send event schemas to the server when 30 or more seconds pass, given that there are unsent schemas.
Parameters:
int newBatchFlushSeconds- sets batch flush time in seconds.
5. Controlling the network timeout
setNetworkTimeout(newNetworkTimeout: number): void;
getNetworkTimeout(): number;Enables manual control over the network timeout. The default network timeout is 2 seconds.
Using in web workers
The Web SDK maintains some shared state across the tracking calls and stores the data for batching, which makes it not suitable for web workers usage.
If you have event tracking in web workers, we recommend to set up a listener in the main thread and send your event data there, where an inspector instance will be listening, processing and sending the event schemas to Avo.
This approach will allow you to use the shared batching and sessions across all web workers and the main thread.
Parameters:
number newNetworkTimeout- sets network timeout in milliseconds.
GTM and CDPs
Find our guides to connect Inspector through the GTM or a CDP below: