All Projects → adopted-ember-addons → Ember Metrics

adopted-ember-addons / Ember Metrics

Licence: mit
Send data to multiple analytics integrations without re-implementing new API

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Ember Metrics

ember-credit-card
"make your credit card form dreamy in one line of code"
Stars: ✭ 89 (-75%)
Mutual labels:  ember, ember-addon
Ember Websockets
Ember.js websockets and socket.io addon
Stars: ✭ 336 (-5.62%)
Mutual labels:  ember, ember-addon
ember-rapid-forms
Smart, Intuitive forms for Ember.js styled with Bootstrap, Multi layouts and Validation support.
Stars: ✭ 58 (-83.71%)
Mutual labels:  ember, ember-addon
ember-simple-auth-token
Ember Simple Auth extension that is compatible with token-based authentication like JWT.
Stars: ✭ 356 (+0%)
Mutual labels:  ember, ember-addon
ember-local-storage-decorator
Decorator for Ember.js to read and persist data in localStorage
Stars: ✭ 13 (-96.35%)
Mutual labels:  ember, ember-addon
glimmer-apollo
Ember and Glimmer integration for Apollo Client.
Stars: ✭ 32 (-91.01%)
Mutual labels:  ember, ember-addon
ember-new-relic
Adds New Relic to your Ember CLI app based on the app's environment
Stars: ✭ 29 (-91.85%)
Mutual labels:  ember, ember-addon
els-addon-typed-templates
Ember templates linting / autocomplete, based on Typescript language server
Stars: ✭ 27 (-92.42%)
Mutual labels:  ember, ember-addon
ember-gridstack
Ember components to build drag-and-drop multi-column grids powered by gridstack.js
Stars: ✭ 31 (-91.29%)
Mutual labels:  ember, ember-addon
ember-key-manager
A service for (un)binding keyboard up and down events.
Stars: ✭ 39 (-89.04%)
Mutual labels:  ember, ember-addon
Ember Light Table
Lightweight, contextual component based table for Ember 2.3+
Stars: ✭ 310 (-12.92%)
Mutual labels:  ember, ember-addon
Ember Apollo Client
🚀 An ember-cli addon for Apollo Client and GraphQL
Stars: ✭ 257 (-27.81%)
Mutual labels:  ember, ember-addon
ember-changeset-conditional-validations
Conditional validations for ember-changeset-validations
Stars: ✭ 26 (-92.7%)
Mutual labels:  ember, ember-addon
ember-headlessui
gavinjoyce.github.io/ember-headlessui/
Stars: ✭ 76 (-78.65%)
Mutual labels:  ember, ember-addon
ember-luxon
🕐 🌐 [deprecated] Addon thats brings Luxon to Ember applications.
Stars: ✭ 20 (-94.38%)
Mutual labels:  ember, ember-addon
ember-stripe-elements
A simple Ember wrapper for Stripe Elements.
Stars: ✭ 64 (-82.02%)
Mutual labels:  ember, ember-addon
ember-fsm
[Maintenance Mode] A promise-aware finite state machine implementation for Ember
Stars: ✭ 37 (-89.61%)
Mutual labels:  ember, ember-addon
ember-cli-daterangepicker
Just a simple component to use bootstrap-daterangepicker.
Stars: ✭ 32 (-91.01%)
Mutual labels:  ember, ember-addon
ember-deep-tracked
Deep auto-tracking for when you just don't care, and want things to work (at the cost of performance in some situtations)
Stars: ✭ 20 (-94.38%)
Mutual labels:  ember, ember-addon
ember-render-helpers
Complimentary render template helpers to the render modifiers
Stars: ✭ 19 (-94.66%)
Mutual labels:  ember, ember-addon

ember-metrics

Send data to multiple analytics services without re-implementing new API

Download count all time npm version Build Status Ember Observer Score

This addon adds a simple metrics service to your app that makes it simple to send data to multiple analytics services without having to implement a new API each time.

Using this addon, you can easily use bundled adapters for various analytics services, and one API to track events, page views, and more. When you decide to add another analytics service to your stack, all you need to do is add it to your configuration, and that's it!

Writing your own adapters for currently unsupported analytics services is easy too. If you'd like to then share it with the world, submit a pull request and we'll add it to the bundled adapters.

Currently supported services and options

  1. GoogleAnalytics

  2. Mixpanel

  3. GoogleTagManager

    • id: Container ID, e.g. GTM-XXXX

    • dataLayer: An array containing a single POJO of information, e.g.:

    dataLayer = [{
      'pageCategory': 'signup',
      'visitorType': 'high-value'
    }];
    
    • envParams: A string with custom arguments for configuring GTM environments (Live, Dev, etc), e.g.:
    envParams: "gtm_auth=xxxxx&gtm_preview=env-xx&gtm_cookies_win=x"
    
  4. Segment

  5. Piwik

  6. Intercom

  7. Facebook Pixel

    dataProcessingOptions: {
      method: ['LDU'],
      country: 1,
      state: 1000
    }
    
  8. Amplitude

  9. Azure App Insights

Community adapters

  1. Adobe Dynamic Tag Management

Installing The Addon

ember install ember-metrics

Compatibility

  • Ember.js v3.16 or above
  • Ember CLI v2.13 or above
  • Node.js v10 or above

Configuration

To setup, you should first configure the service through config/environment:

module.exports = function(environment) {
  var ENV = {
    metricsAdapters: [
      {
        name: 'GoogleAnalytics',
        environments: ['development', 'production'],
        config: {
          id: 'UA-XXXX-Y',
          // Use `analytics_debug.js` in development
          debug: environment === 'development',
          // Use verbose tracing of GA events
          trace: environment === 'development',
          // Ensure development env hits aren't sent to GA
          sendHitTask: environment !== 'development',
          // Specify Google Analytics plugins
          require: ['ecommerce']
        }
      },
      {
        name: 'Mixpanel',
        environments: ['production'],
        config: {
          token: '0f76c037-4d76-4fce-8a0f-a9a8f89d1453'
        }
      },
      {
        name: 'Segment',
        environments: ['production'],
        config: {
          key: '4fce-8a0f-a9a8f89d1453'
        }
      },
      {
        name: 'Piwik',
        environments: ['production'],
        config: {
          piwikUrl: 'http://piwik.my.com',
          siteId: 42
        }
      },
      {
        name: 'Intercom',
        environments: ['production'],
        config: {
          appId: 'def1abc2'
        }
      },
      {
        name: 'FacebookPixel',
        environments: ['production'],
        config: {
          id: '1234567890',
          dataProcessingOptions: {
            method: ['LDU'],
            country: 1,
            state: 1000
          }
        }
      },
      {
        name: 'Amplitude',
        environments: ['production'],
        config: {
          apiKey: '12345672daf5f3515f30f0000f1f0000cdfe433888',
          options: {
            trackingOptions: {
              ip_address: false
            },
            // ...other amplitude configuration options
            // https://developers.amplitude.com/#sdk-advanced-settings
          }
        }
      },
      {
        name: 'AzureAppInsights',
        environments: ['production'],
        config: {
          instrumentationKey: '123',
          // ...other appInsights configuration options
          // https://github.com/microsoft/ApplicationInsights-JS#configuration
        }
      },
      {
        name: 'LocalAdapter',
        environments: ['all'], // default
        config: {
          foo: 'bar'
        }
      }
    ]
  }
}

Adapter names are PascalCased. Refer to the list of supported adapters above for more information.

The metricsAdapters option in ENV accepts an array of objects containing settings for each analytics service you want to use in your app in the following format:

/**
 * @param {String} name Adapter name
 * @param {Array} environments Environments that the adapter should be activated in
 * @param {Object} config Configuration options for the service
 */
{
  name: 'Analytics',
  environments: ['all'],
  config: {}
}

Values in the config portion of the object are dependent on the adapter. If you're writing your own adapter, you will be able to retrieve the options passed into it:

// Example adapter
export default BaseAdapter.extend({
  init() {
    const { apiKey, options } = Ember.get(this, 'config');
    this.setupService(apiKey);
    this.setOptions(options);
  }
});

To only activate adapters in specific environments, you can add an array of environment names to the config, as the environments key. Valid environments are:

  • development
  • test,
  • production
  • all (default, will be activated in all environments)

Content Security Policy

If you're using ember-cli-content-security-policy, you'll need to modify the content security policy to allow loading of any remote scripts. In config/environment.js, add this to the ENV hash (modify as necessary):

// example for loading Google Analytics
contentSecurityPolicy: {
  'default-src': "'none'",
  'script-src': "'self' www.google-analytics.com",
  'font-src': "'self'",
  'connect-src': "'self' www.google-analytics.com",
  'img-src': "'self'",
  'style-src': "'self'",
  'media-src': "'self'"
}

Usage

In order to use the addon, you must first configure it, then inject it into any Object registered in the container that you wish to track. For example, you can call a trackPage event across all your analytics services whenever you transition into a route, like so:

// app/routes/application.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  metrics: service(),
  router: service(),

  init() {
    this._super(...arguments);

    let router = this.router;
    router.on('routeDidChange', () => {
      const page = router.currentURL;
      const title = router.currentRouteName || 'unknown';

      this.metrics.trackPage({ page, title });
    });
  }
});

See this example with Native Classes

If you wish to only call a single service, just specify it's name as the first argument:

// only invokes the `trackPage` method on the `GoogleAnalyticsAdapter`

metrics.trackPage('GoogleAnalytics', {
  title: 'My Awesome App'
});

Context

Often, you may want to include information like the current user's name with every event or page view that's tracked. Any properties that are set on metrics.context will be merged into options for every Service call.

import { set } from '@ember/object';

set(this, 'metrics.context.userName', 'Jimbo');
this.metrics.trackPage({ page: 'page/1' }); // { userName: 'Jimbo', page: 'page/1' }

Native Class usage

If you are using an app built with the Ember Octane Blueprint or otherwise implementing Native Class syntax in your routes, the following example can be used to report route transitions to ember-metrics:

// app/routes/application.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';

export default class ApplicationRoute extends Route {
  @service metrics
  @service router

  constructor() {
    super(...arguments);

    let router = this.router;
    router.on('routeDidChange', () => {
      const page = router.currentURL;
      const title = router.currentRouteName || 'unknown';

      this.metrics.trackPage({ page, title });
    });
  }
}

API

Service API

There are 4 main methods implemented by the service, with the same argument signature:

  • trackPage([analyticsName], options)

    This is commonly used by analytics services to track page views. Due to the way Single Page Applications implement routing, you will need to call this on the activate hook of each route to track all page views.

  • trackEvent([analyticsName], options)

    This is a general purpose method for tracking a named event in your application.

  • identify([analyticsName], options)

    For analytics services that have identification functionality.

  • alias([analyticsName], options)

    For services that implement it, this method notifies the analytics service that an anonymous user now has a unique identifier.

If an adapter implements specific methods you wish to call, then you can use invoke

  • invoke(method, [analyticsName], options)

    metrics.invoke('trackLink', 'Piwik', { url: 'my_favorite_link' , linkType: 'download' });
    

Lazy Initialization

If your app implements dynamic API keys for various analytics integration, you can defer the initialization of the adapters. Instead of configuring ember-metrics through config/environment, you can call the following from any Object registered in the container:

import { Route } from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  metrics: service(),

  afterModel(model) {
    const metrics = this.metrics;
    const id = model.googleAnalyticsKey;

    metrics.activateAdapters([
      {
        name: 'GoogleAnalytics',
        environments: ['all'],
        config: {
          id
        }
      }
    ]);
  }
});

Because activateAdapters is idempotent, you can call it as many times as you'd like. However, it will not reinstantiate existing adapters.

Since ember-metrics now automatically removes all unused adapters, it's also important to force the inclusion of the adapter via config/environment. NOTE: If the adapter is already defined in the metricsAdapters array of config/environment then this step is not necessary.

// config/environment
module.exports = function(environment) {
  var ENV = {
    'ember-metrics': {
      includeAdapters: ['google-analytics']
    }
  };

  return ENV;

Writing Your Own Adapters

First, generate a new Metrics Adapter:

$ ember generate metrics-adapter foo-bar

This creates app/metrics-adapters/foo-bar.js and a unit test at tests/unit/metrics-adapters/foo-bar-test.js, which you should now customize.

Required Methods

The standard contracts are optionally defined, but init and willDestroy must be implemented by your adapter.

init

This method is called when an adapter is activated by the service. It is responsible for adding the required script tag used by the integration, and for initializing it.

willDestroy

When the adapter is destroyed, it should remove its script tag and property. This is usually defined on the window.

Usage

Once you have implemented your adapter, you can add it to your app's config, like so:

module.exports = function(environment) {
  var ENV = {
    metricsAdapters: [
      {
        name: 'MyAdapter',
        environments: ['all'],
        config: {
          secret: '29fJs90qnfEa',
          options: {
            foo: 'bar'
          }
        }
      }
    ]
  }
}

Testing

For unit tests using old QUnit testing API (prior to RFC 232), you will need to specify the adapters in use under needs, like so:

moduleFor('route:foo', 'Unit | Route | foo', {
  needs: [
    'service:metrics',
    '[email protected]:google-analytics', // bundled adapter
    '[email protected]:mixpanel', // bundled adapter
    'metrics-adapter:local-dummy-adapter' // local adapter
  ]
});

Contributors

We're grateful to these wonderful contributors who've contributed to ember-metrics:

Installation

  • git clone this repository
  • npm install
  • bower install

Running

Running Tests

  • ember test
  • ember test --server

Building

  • ember build

For more information on using ember-cli, visit http://www.ember-cli.com/.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].