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

3.0.0 • Public • Published

Crosslytics

Build Status Coverage Status License

Tired of writing repetitive code to send the same analytics data to all your different tracking services? Or formatting the same data slightly differently for each service, like using eventAction for Google Analytics but event_name for Intercom?

Use Crosslytics for a unified event definition and analytics reporting API: Define events once and report them to all your analytics services with a single call. We've also abstracted the services themselves into a pluggable Tracker architecture so you can use only the services you need and quickly add support for new ones.

Why not use Segment? We didn't want to add another hosted service dependency, so we came up with a light-weight library to send telemetry directly. The meat of Crosslytics lies with its unified datamodels. The models are in fact based on the Segment spec, so usage semantics should actually be very similar.

Usage

Define events

Define some events by subclassing TrackedEvent. Since the Crosslytics library is isomorphic, you only have to do this once. You can then share the same event definitions between your client and server code:

// events.ts
type DashboardPanelEventArgs = {
  'Panel ID': string,
  'Panel Type'?: number,
  'Panel Name'?: string
};
 
export class DashboardPanelCreated implements TrackedEvent<DashboardPanelEventArgs> {
  readonly name = 'DashboardPanel Created';
  readonly category = 'Dashboard';
  readonly argPriority: (keyof DashboardPanelEventArgs)[] = [
    'Panel ID',
    'Panel Type',
    'Panel Name'
  ];
}

Server-side

Node.js with Express

Do a one-time setup of trackers in your application code using Express middleware:

// server.ts
import * as express from 'express';
import { Crosslytics, Identity } from 'crosslytics';
import { GoogleAnalyticsTracker } from 'crosslytics-node-google-analytics-tracker';
// Other trackers as desired, e.g.
// import { IntercomTracker } from 'crosslytics-node-intercom-tracker';
 
const app = express();
app.use((req: Request, res: Response, next: NextFunction) => {
  // Store a reference to use later
  req.telemetry = new Crosslytics();
 
  const gaTracker = new GoogleAnalyticsTracker('UA-12345678-9');
  req.telemetry.trackers.set(gaTracker.id, gaTracker);
 
  // Add more trackers as desired
  // const intercomTracker = new IntercomTracker('token');
  // req.telemetry.trackers.set('token', intercomTracker);
 
  // Set current user if you know who it is
  req.telemetry.identify({userId: ''});
  next();
});

Now you can report events to all trackers using a single call:

// dashboard.controller.ts
import { DashboardPanelCreated } from './events';
app.route('panel').post((req: Request, res: Response, next: NextFunction) => {
  ... // App stuff
  
  const ev = new DashboardPanelCreated({
    'Panel ID': '123456',
    'Panel Name': 'Test Panel'
  });
  req.telemetry.track(ev); // Wait if you want
});

Client-side

React with Redux

We recommend adding analytics metadata to Redux Actions. For example, you could include an action.analytics property when you want an action to be tracked. This way, you can setup Redux middleware to report analytics and greatly reduce the amount of tracking code you need to write.

First, do a one-time setup of trackers and create a middleware:

// middleware.ts
import { Action, Middleware } from 'redux';
import { Crosslytics, Identity, TrackedEvent } from 'crosslytics';
import { GoogleAnalyticsTracker } from 'crosslytics-browser-google-analytics-tracker';
// Other trackers as desired, e.g.
// import { IntercomTracker } from 'crosslytics-browser-intercom-tracker';
 
export const crosslytics = new Crosslytics();
 
const gaTracker = new GoogleAnalyticsTracker('UA-12345678-9');
crosslytics.trackers.set(gaTracker.id, gaTracker);
 
// Add more trackers as desired
// const intercomTracker = new IntercomTracker('token');
// crosslytics.trackers.set('token', intercomTracker);
 
// Create a middleware to use with your Redux store
export function analyticsMiddleware(crosslytics: Crosslytics): Middleware {
  return () => next => <T, A extends TrackableAction<T>>(action: A) => {
    if (action.analytics) {
      crosslytics.track(action.analytics);
    }
    return next(action);
  };
}
 
// Woohoo TypeScript type-safety
interface TrackableAction<T> extends Action { analytics?: TrackedEvent<T> }

Then add the middleware to your Redux store (also one-time):

// store.ts
import { createStore, applyMiddleware } from 'redux';
import { analyticsMiddleware, crosslytics } from './middelware.ts';
 
let store = createStore(
  reducers, // defined elsewhere
  applyMiddleware(
    analyticsMiddleware
    // other middleware
  )
);
 
// If you're using a router, you can also track page views
const history = createHistory(); // your router of choice, e.g. 'react-router-redux'
history.listen(location => crosslytics.page({ url: location.pathname }));

Finally, you can now just add an action.analytics property to your actions and the events will be tracked automatically by the middleware. An example async action creator:

// dashboards.actions.ts
 
// See server example: this is the same event defintion across client and server
import { DashboardPanelCreated } from './events';
 
// Action for successful panel creation
export const panelCreated = (panel) => {
  const ev = new DashboardPanelCreated({
    'Panel ID': panel.id,
    'Panel Name': panel.name
  });
  return {
    type: 'PANEL_CREATED', // Could even reuse ev.name here
    payload: panel,
    analytics: ev
  };
};

Trackers

Docs coming soon

Readme

Keywords

none

Package Sidebar

Install

npm i crosslytics

Weekly Downloads

6

Version

3.0.0

License

Apache-2.0

Last publish

Collaborators

  • bsouthga
  • christian.yang