Analytics Middleware
Overview
Analytics track things. By their very nature they are side-effecting actions, usually by sending API calls to one or more analytics servers.
Calypso supports a variety of analytics methods including (but not limited to) Google Analytics, stat bumping, and Tracks events.
As we develop the different view components in React for Calypso, we should work hard to keep them as pure and simple as they can be. This brings with it many benefits, including the ability to easily test those components. Calling out these side-effecting operations can break those tests among other things.
Middleware is a stage in the Redux pipeline that runs between dispatching an action and when that action runs through the reducers. By incorporating the side-effecting operations at this point, we decouple those breaking effects from the other parts of the app.
This module provides just such a middleware: it allows React components to now fire off Redux actions indicating the intent to send an analytics metric instead of actually sending it, keeping the otherwise-unrelated dependencies out of the components.
Usage
As this middleware follows the Flux Standard Action pattern, you can start tracking analytics simply by adding a new meta block to your existing actions. A helper function withAnalytics() is provided to make this easy.
A suite of pure analytics action creators are also exposed which can be used in combination with withAnalytics() or by themselves if no other action beyond analytics tracking is required.
Examples
import {
withAnalytics,
bumpStat,
recordGoogleEvent,
recordTracksEvent,
recordPageView,
} from 'calypso/state/analytics/actions';
// track a page-view
dispatch( recordPageView( '/path/to/page', 'Page Title' ) );
// add event-tracking to an action
dispatch(
withAnalytics( recordGoogleEvent( 'selected_thing', 'my_thing' ), selectThing( myThing ) )
);
// withAnalytics() is auto-curried for convenience
const statBumper = withAnalytics( bumpStat( 'api_calls', 'success' ) );
dispatch( statBumper( apiSuccessAction() ) );
// works with pure actions and thunks
dispatch(
withAnalytics(
recordPageView( '/api/users', 'Fetch Users' ),
fetchUsers( siteId ) // returns a thunk which makes an API call
)
);
// passed as a component prop
const trackSelection = withAnalytics( recordTracksEvent( 'selected_page', { page: 'somePage' } ) );
const mapDispatchToProps = {
selectPage: trackSelection( selectPage ),
recordPageLoad: bumpStat( 'page_loaded', 'page_selected_page' ),
};
API
composeAnalytics :: [ Object ] -> Object
composeAnalytics( ...analytics ): Combines analytics actions by themselves into one multi-analytic-tracking action.
withAnalytics :: Object -> ( Object | function ) -> ( Object | function )
withAnalytics( analytics, action ): Combines analytics action with other action. Can be called with two arguments, which returns a new action, or with only an analytics action, which returns a new function of a single argument taking an action. This curried form is useful for reusing a single analytics action with multiple other actions.
bumpStat :: String -> String -> Object
bumpStat( group, name ): Creates an action to bump the stat with given group and name.
recordGoogleEvent :: String -> String -> String* -> String* -> Object
recordGoogleEvent( category, action, label, value ): Creates an action to record an event in Google Analytics. The label and value arguments are optional.
recordTracksEvent :: String -> Object -> Object
recordTracksEvent( name, properties ): Creates an action to record an event in Tracks. The properties object should contain name/value pairs for event properties to record.
recordPageView :: String -> String -> Object
recordPageView( url, title ): Creates an action to record a page view in both Google Analytics and in Tracks.
recordGooglePageView :: String -> String -> Object
recordGooglePageView( url, title ): Creates an action to record a page view in Google Analytics.
loadTrackingTool :: String -> String -> Object
loadTrackingTool ( trackingTool ): Creates an action to load a tracking tool that gets attached to the DOM on component mount. Pass tracking tool reference through to middleware and manage loading scripts there.
Property Enhancers
The above Redux actions denote the analytics data object to be sent to Tracks. Properties to be reported often need to be passed to the actions as arguments. There are times when it would be convenient to enhance the analytics data object with universal properties that are applicable to all sorts of tracking calls. This is when Enhancers come in handy. To enhance any analytics Redux action with an additional property:
const recorder = withEnhancer( recordPageView, [ enhancer1, enhancer2, enhancer3,... ] );
enhanceWithSiteType
- Enhances any analytics Redux action
- Adds the property
site_typespecifying the selected site's type:jetpackorwpcom site_typeis captured by default when tracking calls are handled by<PageViewTracker>- To include the
site_typeproperty in any other tracking calls, the respective analytics Redux action must be accompanied byenhanceWithSiteType(example)
enhanceWithSiteMainProduct
- Enhances the
ANALYTICS_PAGE_VIEW_RECORDaction forcalypso_page_viewof email and purchase related pages (i.e. paths with prefix defined inshould-report-omit-site-main-product.js) - Adds the property
site_main_productspecifying the main product user set up in the current site site- User signed up for a websitedomain- User signed up for a domain-only "site", without any email subscriptionemail- User signed up for a domain-only "site", with an email subscriptionsite_main_productis captured by default when tracking calls are handled by<PageViewTracker>- To include the
site_main_productproperty in any other tracking calls, the respective analytics Redux action must be accompanied byenhanceWithSiteMainProduct
enhanceWithUserIsDevAccount
- Enhances any analytics Redux action
- Adds the property
user_is_dev_account(0or1) to specify whether the user has theis_dev_account("I am a developer") setting enabled. user_is_dev_accountis captured by default when tracking calls are handled by [<PageViewTracker>]- To include the
user_is_dev_accountproperty in any other tracking calls, the respective analytics Redux action must be accompanied byenhanceWithUserIsDevAccount
enhanceWithGlobalSiteViewEnabled
- Enhances any analytics Redux action
- Adds the property
global_site_view_enabled(1or0) to specify whether the site has the nav redesign global site view enabled. global_site_view_enabledis captured by default when tracking calls are handled by [<PageViewTracker>]- To include the
global_site_view_enabledproperty in any other tracking calls, the respective analytics Redux action must be accompanied byenhanceWithGlobalSiteViewEnabled
Internal Helpers
These can be used in client code but are intended to be used internally within the middleware library to create service-specific handlers for tracking analytics.
recordEvent :: String -> Object -> Object
recordEvent( service, args ): Used to create event-tracking action-creators. The actions will be dispatched based on the service name and passed the args in the action payload.
recordPageView :: String -> String -> String* -> Object
recordPageView( url, title, service* ): Creates an action to record a page view. If service is omitted, the default behavior is to record in both Google Analytics and in Tracks.