Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

analytics

> 编程语言
Open source

Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors

2.7K stars0 likes0 views
WebsiteGitHub

About

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

Table of Contents

Click to expand
  • Features
  • Why
  • Install
  • Usage
  • Demo
  • API
    • Configuration
    • analytics.identify
    • analytics.track
    • analytics.page
    • analytics.user
    • analytics.reset
    • analytics.ready
    • analytics.on
    • analytics.once
    • analytics.getState
    • analytics.storage
    • analytics.storage.getItem
    • analytics.storage.setItem
    • analytics.storage.removeItem
    • analytics.plugins
    • analytics.plugins.enable
    • analytics.plugins.disable
  • Events
  • Analytic plugins
  • Community Plugins
  • Creating analytics plugins
    • React to any event
    • Custom methods
  • Plugin Naming Conventions
  • Debugging analytics
  • TypeScript support
  • Contributing
  • Setup & Install dependencies
  • Development
  • Support

Features

  • Extendable - Bring your own third-party tool & plugins
  • Test & debug analytics integrations with time travel & offline mode
  • Add functionality/modify tracking calls with baked in lifecycle hooks
  • Isomorphic. Works in browser & on server
  • Queues events to send when analytic libraries are loaded
  • Conditionally load third party scripts
  • Works offline
  • TypeScript support

Why

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:

  • You should never be locked into an analytics tool
  • DX is paramount. Adding & removing analytic tools from your application should be easy
  • Respecting visitor privacy settings & allowing for opt-out mechanisms is crucial
  • A pluggable API makes adding new business requests easy

To add or remove an analytics provider, adjust the plugins you load into analytics during initialization.

Install

This module is distributed via npm, which is bundled with node and should be installed as one of your project's dependencies.

bash
npm install analytics --save

Or using yarn:

bash
yarn add analytics

Or using pnpm:

bash
pnpm add analytics

Or using bun:

bash
bun add analytics

Or as a script tag:

xml
<script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>

Usage

…
Node.js usage

For ES6/7 javascript you can import Analytics from 'analytics' for normal node.js usage you can import like so:

…
Browser usage

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.

xml
<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>

Demo

See Analytics Demo for a site example.

API

The core analytics API is exposed once the library is initialized with configuration.

Typical usage:

  1. Initialize with configuration
  2. Export the analytics instance with third-party providers (Google Analytics, HubSpot, etc)
  3. Use page, identify, track in your app
  4. Plugin custom business logic

Configuration

Analytics library configuration

After the library is initialized with config, the core API is exposed & ready for use in the application.

Arguments

  • config object - analytics core config
  • [config.app] (optional) string - Name of site / app
  • [config.version] (optional) string|number - Version of your app
  • [config.debug] (optional) boolean - Should analytics run in debug mode
  • [config.plugins] (optional) Array.<AnalyticsPlugin> - Array of analytics plugins

Example

javascript
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
  ]
})

analytics.identify

Identify a user. This will trigger identify calls in any installed plugins and will set user data in localStorage

Arguments

  • userId String - Unique ID of user
  • [traits] (optional) Object - Object of user traits
  • [options] (optional) Object - Options to pass to identify call
  • [callback] (optional) Function - Callback function after identify completes

Example

…

analytics.track

Track an analytics event. This will trigger track calls in any installed plugins

Arguments

  • eventName String - Event name
  • [payload] (optional) Object - Event payload
  • [options] (optional) Object - Event options
  • [callback] (optional) Function - Callback to fire after tracking completes

Example

…

analytics.page

Trigger page view. This will trigger page calls in any installed plugins

Arguments

  • [data] (optional) PageData - Page data overrides.
  • [options] (optional) Object - Page tracking options
  • [callback] (optional) Function - Callback to fire after page view call completes

Example

…

analytics.user

Get user data

Arguments

  • [key] (optional) string - dot.prop.path of user data. Example: 'traits.company.name'

Example

javascript
// 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')

analytics.reset

Clear all information about the visitor & reset analytic state.

Arguments

  • [callback] (optional) Function - Handler to run after reset

Example

javascript
// Reset current visitor
analytics.reset()

analytics.ready

Fire callback on analytics ready event

Arguments

  • callback Function - function to trigger when all providers have loaded

Example

javascript
analytics.ready((payload) => {
  console.log('all plugins have loaded or were skipped', payload);
})

analytics.on

Attach an event handler function for analytics lifecycle events.

Arguments

  • name String - Name of event to listen to
  • callback Function - function to fire on event

Example

javascript
// 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()

analytics.once

Attach a handler function to an event and only trigger it once.

Arguments

  • name String - Name of event to listen to
  • callback Function - function to fire on event

Example

javascript
// 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()

analytics.getState

Get data about user, activity, or context. Access sub-keys of state with dot.prop syntax.

Arguments

  • [key] (optional) string - dot.prop.path value of state

Example

javascript
// Get the current state of analytics
analytics.getState()

// Get a subpath of state
analytics.getState('context.offline')

analytics.storage

Storage utilities for persisting data. These methods will allow you to save data in localStorage, cookies, or to the window.

Example

javascript
// 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')

analytics.storage.getItem

Get value from storage

Arguments

  • key String - storage key
  • [options] (optional) Object - storage options

Example

javascript
analytics.storage.getItem('storage_key')

analytics.storage.setItem

Set storage value

Arguments

  • key String - storage key
  • value any - storage value
  • [options] (optional) Object - storage options

Example

javascript
analytics.storage.setItem('storage_key', 'value')

analytics.storage.removeItem

Remove storage value

Arguments

  • key String - storage key
  • [options] (optional) Object - storage options

Example

javascript
analytics.storage.removeItem('storage_key')

analytics.plugins

Async Management methods for plugins.

This is also where custom methods are loaded into the instance.

Example

javascript
// Enable a plugin by namespace
analytics.plugins.enable('keenio')

// Disable a plugin by namespace
analytics.plugins.disable('google-analytics')

analytics.plugins.enable

Enable analytics plugin

Arguments

  • plugins string|Array.<string> - name of plugins(s) to disable
  • [callback] (optional) Function - callback after enable runs

Example

javascript
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')
})

analytics.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScriptanalyticsanalytics-utilsgdpr-compliantmetrics

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言