Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
A lightweight analytics abstraction library for tracking page views, custom events, & identify visitors.
Designed to work with any third-party analytics tool or your own backend.
Read the docs or view the live demo app
Companies frequently change analytics requirements based on evolving needs. This results in a lot of complexity, maintenance, & extra code when adding/removing analytic services to a site or application.
This library aims to solves that with a simple pluggable abstraction layer.
Driving philosophy:
To add or remove an analytics provider, adjust the plugins you load into analytics during initialization.
This module is distributed via npm, which is bundled with node and should be installed as one of your project's dependencies.
npm install analytics --saveOr using yarn:
yarn add analyticsOr using pnpm:
pnpm add analyticsOr using bun:
bun add analyticsOr as a script tag:
<script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>… For ES6/7 javascript you can import Analytics from 'analytics' for normal node.js usage you can import like so:
… When importing global analytics into your project from a CDN, the library exposes via a global _analytics variable.
Call _analytics.init to create an analytics instance.
<script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>
<script>
const Analytics = _analytics.init({
app: 'my-app-name',
version: 100,
plugins: []
})
/* Track a page view */
Analytics.page()
/* Track a custom event */
Analytics.track('userPurchase', {
price: 20,
item: 'pink socks'
})
/* Identify a visitor */
Analytics.identify('user-id-xyz', {
firstName: 'bill',
lastName: 'murray',
email: '[email protected]'
})
</script>See Analytics Demo for a site example.
The core analytics API is exposed once the library is initialized with configuration.
Typical usage:
page, identify, track in your appAnalytics library configuration
After the library is initialized with config, the core API is exposed & ready for use in the application.
Arguments
object - analytics core configstring - Name of site / appstring|number - Version of your appboolean - Should analytics run in debug modeArray.<AnalyticsPlugin> - Array of analytics pluginsExample
import Analytics from 'analytics'
import pluginABC from 'analytics-plugin-abc'
import pluginXYZ from 'analytics-plugin-xyz'
// initialize analytics
const analytics = Analytics({
app: 'my-awesome-app',
plugins: [
pluginABC,
pluginXYZ
]
})Identify a user. This will trigger identify calls in any installed plugins and will set user data in localStorage
Arguments
String - Unique ID of userObject - Object of user traitsObject - Options to pass to identify callFunction - Callback function after identify completesExample
…Track an analytics event. This will trigger track calls in any installed plugins
Arguments
String - Event nameObject - Event payloadObject - Event optionsFunction - Callback to fire after tracking completesExample
…Trigger page view. This will trigger page calls in any installed plugins
Arguments
Object - Page tracking optionsFunction - Callback to fire after page view call completesExample
…Get user data
Arguments
string - dot.prop.path of user data. Example: 'traits.company.name'Example
// Get all user data
const userData = analytics.user()
// Get user id
const userId = analytics.user('userId')
// Get user company name
const companyName = analytics.user('traits.company.name')Clear all information about the visitor & reset analytic state.
Arguments
Function - Handler to run after resetExample
// Reset current visitor
analytics.reset()Fire callback on analytics ready event
Arguments
Function - function to trigger when all providers have loadedExample
analytics.ready((payload) => {
console.log('all plugins have loaded or were skipped', payload);
})Attach an event handler function for analytics lifecycle events.
Arguments
String - Name of event to listen toFunction - function to fire on eventExample
// Fire function when 'track' calls happen
analytics.on('track', ({ payload }) => {
console.log('track call just happened. Do stuff')
})
// Remove listener before it is called
const removeListener = analytics.on('track', ({ payload }) => {
console.log('This will never get called')
})
// cleanup .on listener
removeListener()Attach a handler function to an event and only trigger it once.
Arguments
String - Name of event to listen toFunction - function to fire on eventExample
// Fire function only once per 'track'
analytics.once('track', ({ payload }) => {
console.log('This is only triggered once when analytics.track() fires')
})
// Remove listener before it is called
const listener = analytics.once('track', ({ payload }) => {
console.log('This will never get called b/c listener() is called')
})
// cleanup .once listener before it fires
listener()Get data about user, activity, or context. Access sub-keys of state with dot.prop syntax.
Arguments
string - dot.prop.path value of stateExample
// Get the current state of analytics
analytics.getState()
// Get a subpath of state
analytics.getState('context.offline')Storage utilities for persisting data. These methods will allow you to save data in localStorage, cookies, or to the window.
Example
// Pull storage off analytics instance
const { storage } = analytics
// Get value
storage.getItem('storage_key')
// Set value
storage.setItem('storage_key', 'value')
// Remove value
storage.removeItem('storage_key')Get value from storage
Arguments
String - storage keyObject - storage optionsExample
analytics.storage.getItem('storage_key')Set storage value
Arguments
String - storage keyObject - storage optionsExample
analytics.storage.setItem('storage_key', 'value')Remove storage value
Arguments
String - storage keyObject - storage optionsExample
analytics.storage.removeItem('storage_key')Async Management methods for plugins.
This is also where custom methods are loaded into the instance.
Example
// Enable a plugin by namespace
analytics.plugins.enable('keenio')
// Disable a plugin by namespace
analytics.plugins.disable('google-analytics')Enable analytics plugin
Arguments
string|Array.<string> - name of plugins(s) to disableFunction - callback after enable runsExample
analytics.plugins.enable('google-analytics').then(() => {
console.log('do stuff')
})
// Enable multiple plugins at once
analytics.plugins.enable(['google-analytics', 'segment']).then(() => {
console.log('do stuff')
})No open issues yet, or sync has not completed.