Client Integration Guide - Javascript (Browser)

NPM

Built For Total Downloads Software License Source Code

This SDK is a browser side SDK that captures AJAX API calls and user context and sends to Moesif’s API analytics service.

If you’re already using a Moesif server SDK to instrument your APIs, you can use this SDK in conjunction with the server SDK to collect customer context like email, sign up date, and web attribution via identifyUser() and identifyCompany() methods.

When you call start(), this SDK will log API calls to:

  • Your own APIs (such as APIs powering your Single Page Apps)
  • 3rd party APIs (such as to Stripe and Twilio)
  • Decentralized APIs such as DApps communicating with Ethereum Web3/interactions with smart contracts

It has native support for RESTful, GraphQL, Ethereum Web3, and JSON-RPC APIs.

Full documentation on Moesif integration is available here.

Source Code on GitHub

How to install

Your Moesif Application Id can be found in the Moesif Portal. After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the Moesif Portal, click on the top right menu, and then clicking Installation.

Using CDN to load the library

<script src="//unpkg.com/moesif-browser-js@^1/moesif.min.js"></script>
<script type="text/javascript">
// Initialize the SDK. Must be called before any other methods
moesif.init({
  applicationId: 'Your Moesif Application Id'
  // add other option here
});

// Start capturing AJAX API Calls
moesif.start();

// Identify the user with Moesif such as when user logs in
moesif.identifyUser('12345');
</script>

Put the above script tags in between the <head> tags of your html page. It will attach a global moesif object. You can access it either via moesif or window.moesif.

Alternative installation via NPM

This SDK is also available as a package on NPM. The moesif-browser-js SDK is indended for running on the client side. For instrumneting APIs on the server side, there is a separate SDK, moesif-express available on NPM.

To install into a project using NPM with a front-end packager such as Browserify or Webpack:

npm install --save moesif-browser-js

You can then require the lib like a standard NPM module:

var moesif = require('moesif-browser-js');

// Initialize the SDK. Must be called before any other methods
moesif.init({
  applicationId: 'Your Moesif Application Id'
  // add other option here
});

// Start capturing AJAX API Calls
moesif.start();

// Identify the user with Moesif such as when user logs in
moesif.identifyUser('12345');

With the require method, the moesif object is not attached to any global scope, but you can attach to the global window object easily:

window.moesif = moesif;

List of Methods on the moesif Object

init, (obj) => null

Initialize the SDK with your Application Id and any other options. On init, the SDK will capture initial user context like UTM parameters and referrer info. Must be called before any other methods like start() or identifyUser.

var options = {
  applicationId: 'Your Moesif Application Id'
};

moesif.init(options);

start, () => null

moesif.start()

Call start when you want to start logging AJAX API calls.

stop, () => null

moesif.stop()

Stops logging API calls. It is not required to call this, since recording will stop automatically when the browser tab is closed. If you want more control, you can call stop directly. Call start again to restart logging.

identifyUser, (string, object) => null

Identify the user with Moesif with a user id such as when a user logs into your app. You can also add custom metadata containing fields like the customer’s name and email as the second argument.

// When the user logs in and you have their unique userId, call identifyUser()
moesif.identifyUser('12345');

// Optionally, you can also send custom metadata like customer email and name
moesif.identifyUser('12345', {
  email: "johndoe@acmeinc.com",
  title: "software engineer",
  string_field: "some string"
  number_field: 123,
  object_field: {
    field_a: "value_a",
    field_b: "value_b"
  }
});

identifyCompany, (string, object, string) => null

Like identifyUser, but for tracking companies or accounts. Recommended for B2B companies. Optionally, you can add custom metadata as the second argument, and a company domain as the third argument. If set, company domain is used by Moesif to enrich your company data.

// When the company logs in and you have their companyId or accountId, call identifyCompany()
moesif.identifyCompany('67890');

// Optionally, you can also send custom metadata like company domain and plan details
moesif.identifyCompany('67890', {
    alexa_ranking: 500,
    plan_name: 'free'
    number_field: 123,
    object_field: {
      field_a: 'value_a',
      field_b: 'value_b'
    }
  }, 'acmeinc.com');

identifySession, (string) => null

If you have a specific session token you want to track, you can pass to Moesif. Once called, the new session token will be used until identifySession is called again.

moesif.identifySession('d23xdefc3ijhcv93hf4h38f90h43f');

useWeb3, (web3) => boolean

Sets the web3 JSON-RPC to use the web3 object passed in. If no argument is passed in, it will try to restart capturing using the global web3 object. Return true if successful.

moesif.useWeb3(myWeb3Object)

Configuration options

The options is an object that is passed into the SDK’s init method.

applicationId - string, required

This is the collector API key that is obtained from your Moesif account. Collector Application Id’s are write-only keys and can be safely used on the client side.

skip, (event) => boolean, optional

Optional function that to determine on if a particular event should be skipped logging. The parameter passed in is an event model. Detail on the event model here.

maskContent, (event) => event, optional

Optional function that let you mask any sensitive data in the event model, and then return the masked event. Important that do not remove required fields in the event model. See the spec on the event model to see what is required.

getMetadata, (event) => object, optional

Optional function that allow you to append arbitrary JSON metadata to API calls before being logged to Moesif.

full options example:


var options = {
  applicationId: 'Your Moesif Application Id',
  skip: function(event) {
    if (event.request.uri.includes('google')) {
      return true;
    }
    return false;
  },
  maskContent: function(event) {
    if (event.request.headers['secret']) {
      event.request.headers['secret'] = '';
    }
    return event;
  },
  getMetadata: function(event) {
    if (event.request.uri.includes('stripe')) {
      return {
        type: 'payment'
      };
    }
  }
};

moesif.init(options);

disableFetch, boolean, optional, default false.

Starting from version 1.4.0, this SDK also instruments fetch API if it is not polyfilled. Some browsers may use fetch under XmlHTTPRequest, then it is possible events get duplicated. In this case, disable fetch will fix the issue.

Ethereum dApp support

DApps (Decentralized Apps) are frontend apps which interact with blockchains such as Ethereum over an API. For Ethereum, this API layer uses JSON-RPC and is called the Ethereum Web3 API which Moesif supports natively.

Moesif can capture the API call data directly from the client side with moesif-browser-js which in turn can be used for debugging and monitoring issues, and alert you of anomalies.

Review the tutorial for building an Ethereum DApp with Integrated Web3 Monitoring.

Please also checkout this document on how Moesif supports decentralized apps built on top of Ethereum Web3 and JSON-RPCs.

Web3 object

Many Dapp clients such as the Metamask extension and Mist Browser, will inject a web3 object directly in the browser’s global scope.

The default moesif-browser-js config will automatically instrument the injected web3 object and capture outgoing API transactions to the Ethereum network.

For advanced scenarios where your code uses a different web3 object than the one injected, then you should call moesif.useWeb3(myWeb3); This insures the correct web3 instance is instrumented.

This can happen if you let users modify the selected web3 provider or change their network.

if (typeof web3 !== 'undefined') {
  myWeb3 = new Web3(web3.currentProvider);
  // No action needed by Moesif
} else {
  // set the custom provider you want from Web3.providers
  myWeb3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

  moesif.useWeb3(myWeb3);
}

Duplicate API events

By default, moesif-browser-js captures both outgoing API calls from XMLHttpRequest and the web3 object. This way you can see both blockchain related transactions along with other 3rd party APIs like Twilio or Stripe.

If the Web3 provider is also using the XMLHttpRequest (such as the HttpProvider), it’s possible that the same API call is captured twice. This is expected.

moesif-browser-js adds metadata depending on the captured source. For events that are captured via web3, we add additional event metadata for the web3 provider used.

As an example:

{
  "_web3": {
    "via_web3_provider": true,
    "is_metamask": true
  }
}

Examples

  • Example setup for react-boilerplate. For React apps, if you set up server side rendering, please ensure that this library is only initiated on the client side.
  • Example setup for an Etherum Dapp.

Credits for moesif-browser-js

Some of the build scripts and directory structure is based on Mixpanel’s Javascript Client Library, which is under Apache 2.0 license. Some utilities are based on underscore.

Other integrations

To view more more documentation on integration options, please visit the Integration Options Documentation.