observalyze-sdk
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

observalyze-sdk

This is the client SDK for sending events to Observalyze from your web application. It can be used in both web and server environments. The logged events are used to give insight into the usage of your platform or application.

Observalyze is built with privacy in mind, see #Privacy for some notes on the topic.

Visit Observalyze for more info on how it can be used to gain more insight into what your visitors are doing on your platform.

Installation

First visit observalyze.com to create an account and then visit https://www.observalyze.com/app/projects to obtain the apiKey for your project.

There are two different methods of installation. If you use node or want to use observalyze in combination with a bundler:

npm i --save observalyze-sdk

# You will then be able to do
# import { initialize } from 'observalyze';

The other method is to include it via a script tag:

<script src="https://www.observalyze.com/sdk" type="text/javascript" data-api-key="[your observalyze api key]"></script>

By using https://www.observalyze.com/sdk you will always load the latest version of the SDK. We advise to pin the SDK to a major version, so that no incompatible changes to the SDK are automatically applied to your project. You can do this by adding a version to the URL: https://www.observalyze.com/sdk@1, this will include SDK version 1.x in your project. You can also pin to a specific version, by using https://www.observalyze.com/sdk@1.0.0.

Auto log is enabled by default in the browser, see below for more details.

Usage

The SDK can be used in both a server and a browser environment.

There are two types of events that can be send: 'generic' events, and 'normal' events. Both types of events allow you to send events with a key of your choice to Observalyze. The key is used there to generate reports and generate usage insights.

See below for a detailed explanation of the configuration options.

Server

import { initialize } from 'observalyze';

const OBSERVALYZE_KEY = process.env['OBSERVALYZE_API_KEY'];

const observalyze = initialize({ apiKey });

(async () => {
  // log a generic event, such as server startup for example.
  await observalyze.logGenericEvent('my-event');

  // Or, if you have some kind of client or user identifier, let's assume it is called userId
  await observalyze.logEvent('my-user-client', userId);)
})();

Browser

When you use a bundler to include observalyze in your application, the process it almost similar to the Server section above.

If you use the script tag to include Observalyze, it will be made available as a global:

<script src="https://www.observalyze.com/sdk" type="text/javascript" data-api-key="[your observalyze api key]"></script>
<script type="text/javascript">
  /**
   * By including data-api-key in the script tag it will automatically be initialized.
   * If you omit the data-api-key you need to initialize it manually:
   */
  const observalyze = observalyzeSdk.initialize({ apiKey: 'xxx' });
</script>

Automatic logging

If you load the SDK in the browser, automatic logging is enabled by default. This feature enables you to add Observalyze event logging to your application without having to use any Javascript for it!

Auto logging is utilized by updating your HTML elements with two different attributes: data-ose-click and data-ose-appear.

Click means that a logEvent is invoked where the key is the value of data-ose-click, when the element is clicked.

Appear triggers an event log when the element appears in the DOM, so no user interaction is required. This allows you to log page changes for example. The visibility of the element does not influence this functionality, if the element is in the DOM and has the data-ose-appear attribute, its logged.

To disable auto logging, provide { autoLog: { enabled: false }} in the configuration. See #Configuration for details on how to configure auto logging to monitor only parts of your application.

Events

Generic events

These types of events are events that are not directly linked to a user or visitor. For example when the application starts, or a payment webhook is triggered in the server component.

const observalyze = await initialize({ apiKey: 'xxx' });
// ...
await observalyze.logGenericEvent('event-key');

These events are not linked to a client or session.

Normal events

These are events that can be linked to a specific account or guest. In normal operating mode, the SDK will generate a unique identifier for the browser used. The generation of the identifier ensures that the event data cannot be linked back to a specific account.

const observalyze = await initialize({ apiKey: 'xxx' });
// ...
await observalyze.logEvent('custom-key');

Even though the invocation is the same as for the generic events, the event is enriched, by the SDK, with a random client identifier, and an identifier for the current session of the user. Once the session expires, a new session identifier will be generated. (You need to provide your own storage implementation in order for this to work in non-browser environments. Which is straight-forward, it follows the Storage interface).

You can optionally provide a custom client identifier as a second parameter for the logEvent invocation, if its different than what was provided at initialization.

Configuration

Obtain your API key by creating an Observalyze account, if you do not have one already. First, acquire the api key for your project from your projects page.

Then initialize the SDK in your application as explained above.

Options

option type required script attr description
apiKey string Yes data-api-key The api key, retrieved from the projects page, linking the event to your project. If the value is left blank, no events will be send out.
debug boolean No data-debug="true" When set to true, logging will be send to the console, for debugging purposes.
domains string[] No data-domains An explicit allow list for domains to enable Observalyze on. If the current domain is not in the list, logging is disabled. The domain must match exactly, so use www.example.com to enable on that domain. In the script tag, separate multiple domains with a , character
client string No data-client If you prefer to use your own client identifier for a browser instead of the generated one, provide it as an option.
requester Requester No N/A A custom implementation for http request, as explained in #Requester
storage Storage No N/A By default, non-generic events use localStorage in the browser to store some anonymous data. If localStorage is not available, or you want a different type of storage, you can provide your own.

Auto Log

If you manually configure the SDK, provide an autoLog attribute. To disable it, use { apiKey: 'xxx', autoLog: { enabled: false }}. For enabling, provide { apiKey: 'xxx', autoLog: { enabled: true, element: 'body' }}. Element can be a querySelector that can serve as inpot for document.querySelectorAll. The default is body, all changes inside the body tag will then be monitored.

In the script, use:

<script
  src="https://www.observalyze.com/sdk"
  type="text/javascript"
  data-api-key="[your observalyze api key]"
  data-auto="true"
  data-auto-element="#app"
></script>

<!-- or -->

<script
  src="https://www.observalyze.com/sdk"
  type="text/javascript"
  data-api-key="[your observalyze api key]"
  data-auto="false"
></script>

Note: Auto log is only availble in a browser environment.

Requester

The SDK uses fetch to send data, if available. Which is in the browser, and Node versions 18 or higher. If you are using the SDK in a non-browser environment and fetch is not available, you should provide your own HTTP implementation.

The requester is expected to adhere to the following interface:

export interface Requester {
  post: <T, D = any>(url: string, apiKey: string, data?: D | undefined) => Promise<HttpResponse<T>>;
}

Axios example

This is a sample implementation of a requester in typescript.

const requester: Requester = {
  post: async function <T, D = any>(url: string, apiKey: string, data: D): Promise<HttpResponse<T>> {
    try {
      const response = await axios.post<T>(url, data, {
        headers: { Authorization: `Bearer ${apiKey}` },
      });
      return {
        statusCode: response.status,
        data: response.data,
      };
    } catch (error) {
      if (axios.isAxiosError(error)) {
        return {
          statusCode: parseInt(error.status ?? '0', 10),
          data: error.response?.data ?? {},
        };
      }
    }

    return {
      statusCode: 0,
      data: {},
    };
  },
};

Privacy

This SDK will store two different values in the browser localStorage. observalyze.client and observalyze.session are used to link the event to other events send from the same browser. observalyze.client will not be used if you provide your own client identifier in the configuration.

These values can be removed from localStorage at any moment, the SDK will re-generate new values automatically.

Disclaimer

Note that Observalyze cannot be held liable in any way for any loss or damage as the result of the use of this package or the platform. Please use at your own risk.

Package Sidebar

Install

npm i observalyze-sdk

Weekly Downloads

160

Version

1.0.1

License

none

Unpacked Size

350 kB

Total Files

26

Last publish

Collaborators

  • daangemist