@analytics/snowplow

中文文档
0.3.3发布于 2022/03/18MITESM + CJS近 30 天下载 7835

Snowplow integration for 'analytics' module for browser & node

原始使用文档
文档目录10 节
  1. Installation
  2. How to use
  3. Platforms Supported
  4. Browser usage
  5. Browser API
  6. Configuration options for browser
  7. Server-side usage
  8. Server-side API
  9. Configuration options for server-side
  10. Additional examples

Snowplow plugin for analytics

Integration with Snowplow Analytics for analytics package.

View the docs

Click to expand

Installation

Install analytics and @analytics/snowplow packages

npm install analytics
npm install @analytics/snowplow

How to use

The @analytics/snowplow package works in the browser and server-side in Node.js. To use, install the package, include in your project and initialize the plugin with analytics.

Below is an example of how to use the browser plugin.

import Analytics from 'analytics'
import snowplowPlugin from '@analytics/snowplow'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    // Minimal recommended configuration
    snowplowPlugin({
      name: 'snowplow',
      collectorUrl: 'collector.mysite.com',
      trackerSettings: {
        appId: 'myApp'
      }
    })
  ]
})

/* Track a page view */
// Enable some automatic tracking before page event
analytics.on('initialize:snowplow', ({ instance }) => {
  instance.plugins.snowplow.enableActivityTracking(10, 10)
  instance.plugins.snowplow.enableLinkClickTracking()
})

// Track page
analytics.page()

// or Track page view with additional entities
analytics.page({
  contexts: [
    {
      schema: 'iglu:com.acme/blog_post/jsonschema/1-0-0',
      data: {
        title: 'Re-thinking the structure of event data',
        category: 'Data Insights',
        author: 'Cara Baestlein',
        datePublished: '2020-01-24'
      }
    }
  ]
})

/* Track a custom event */
// Track structured event
analytics.track('playedVideo', {
  category: 'Videos',
  label: 'Fall Campaign',
  value: 42
})

// or Track Self Describing event
analytics.track('selfDescribingEvent', {
  schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
  data: {
    id: 42,
    title: 'Fall Campaign'
  }
})

// or Track Self Describing event with additional entities
analytics.track('selfDescribingEvent', {
  schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
  data: {
    id: 42,
    title: 'Fall Campaign',
    videoTimestampInMs: 1104
  },
  contexts: [
    {
      schema: 'iglu:com.acme/product/jsonschema/1-0-0',
      data: {
        id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
        category: 'clothing',
        subCategory: 'socks',
        price: 3.99
      }
    }
  ]
})

// or Track Enchanced Ecommerce event with product context
analytics.track('EnhancedEcommerceProductContext', {
  id: 'P12345',
  name: 'Android Warhol T-Shirt',
  list: 'Search Results',
  brand: 'Google',
  category: 'Apparel/T-Shirts',
  variant: 'Black',
  quantity: 1
})
analytics.track('EnhancedEcommerceAction', {
  action: 'add'
})

/* Identify a visitor */
analytics.identify('user-id-xyz')

After initializing analytics with the snowplowPlugin plugin, data will be sent into Snowplow Analytics whenever analytics.page, analytics.track, or analytics.identify are called.

See additional implementation examples for more details on using in your project.

Platforms Supported

The @analytics/snowplow package works in the browser and server-side in Node.js

Browser usage

The Snowplow Analytics client side browser plugin works with these analytic api methods:

Browser API

import Analytics from 'analytics'
import snowplowPlugin from '@analytics/snowplow'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    // Minimal recommended configuration
    snowplowPlugin({
      name: 'snowplow',
      collectorUrl: 'collector.mysite.com',
      trackerSettings: {
        appId: 'myApp'
      }
    })
  ]
})

Configuration options for browser

Optiondescription
collectorUrl
required - string
The URL to a Snowplow collector
name
optional - string
The name to identify this instance of the tracker, use if using multiple tracker instances ('snowplow' default)
trackerSettings
optional - Object
The arg map to pass to the Snowplow Tracker
trackerSettings.appId
optional - string
The appId to identify this application
trackerSettings.platform
optional - string
Platform of tracking ("web" default)
trackerSettings.cookieDomain
optional - string
Domain to set cookie against
trackerSettings.discoverRootDomain
optional - string
Automatically discover root domain
trackerSettings.cookieName
optional - string
Prefix for cookies ("sp" default)
trackerSettings.cookieSameSite
optional - string
SameSite cookie setting ("None" default)
trackerSettings.cookieSecure
optional - boolean
Secure cookie setting (true default)
trackerSettings.encodeBase64
optional - boolean
Encode JSON objects as Base64 (true default)
trackerSettings.respectDoNotTrack
optional - bolean
Respect do not track (consider analytics-plugin-do-not-track) (false default)
trackerSettings.eventMethod
optional - string
Method to send events, GET, POST, Beacon (POST default)
trackerSettings.bufferSize
optional - number
Amount of events to buffer before sending (1 default)
trackerSettings.maxPostBytes
optional - number
Maximum size of POST or Beacon before sending (40000 default)
trackerSettings.crossDomainLinker
optional - string
function to configure which links to add cross domain linking
trackerSettings.cookieLifetime
optional - number
Cookie lifetime (63072000 default)
trackerSettings.stateStorageStrategy
optional - string
Use cookies and/or localstorage ("cookieAndLocalStorage" default)
trackerSettings.maxLocalStorageQueueSize
optional - number
Maximum numbers of events to buffer in localstorage to prevent filling local storage (1000 default)
trackerSettings.resetActivityTrackingOnPageView
optional - boolean
Flag to decide whether to reset page ping timers on virtual page view (true default)
trackerSettings.connectionTimeout
optional - boolean
The timeout, in milliseconds, before GET and POST requests will timeout (5000 default) (Snowplow JS 2.15.0+)
trackerSettings.anonymousTracking
optional - Object
Flag to enable anonymous tracking functionality (false default)
trackerSettings.anonymousTracking.withSessionTracking
optional - boolean
Flag to enable whether to continue tracking sessions in anonymous tracking mode (false default)
trackerSettings.anonymousTracking.withServerAnonymisation
optional - boolean
Flag which prevents collector from returning and capturing cookies and capturing ip address (false default)
trackerSettings.contexts
optional - Object
The auto contexts for each event
trackerSettings.contexts.webPage
optional - boolean
The webpage context, containing the page view id. (true default)
trackerSettings.contexts.performanceTiming
optional - boolean
Add performance timing information
trackerSettings.contexts.clientHints
optional - Object
Add Client Hint information (Snowplow JS 2.15.0+)
trackerSettings.contexts.clientHints.includeHighEntropy
optional - boolean
Capture High Entropy Client Hints (Snowplow JS 2.15.0+)
trackerSettings.contexts.gaCookies
optional - boolean
Add gaCookie information
trackerSettings.contexts.geolocation
optional - boolean
Add browser geolocation information
trackerSettings.contexts.optimizelyXSummary
optional - boolean
Add browser geolocation information
trackerSettings.plugins
optional - Array
Additional plugins to include at tracker initialisation. See https://docs.snowplowanalytics.com/docs/collecting-data/collecting-from-own-applications/javascript-trackers/browser-tracker/browser-tracker-v3-reference/plugins/

Server-side usage

The Snowplow Analytics server-side node.js plugin works with these analytic api methods:

Server-side API

import Analytics from 'analytics'
import snowplowPlugin from '@analytics/snowplow'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    snowplowPlugin({
      name: 'snowplow',
      collectorUrl: 'collector.mysite.com',
      appId: 'myApp'
    })
  ]
})

Configuration options for server-side

Optiondescription
collectorUrl
required - string
The URL to a Snowplow collector
appId
required - string
The appId to identify this application
name
optional - string
The name to identify this instance of the tracker ('snowplow' default)
protocol
optional - string
'http' or 'https' ('https' default)
port
optional - string
collector port (80 or 443 default)
method
optional - string
The method to send events to collector, 'post' or 'get' ('post' default)
bufferSize
optional - string
Only send events once n are buffered. Defaults to 1 for GET requests and 10 for POST requests.
retries
optional - string
The number of times the tracker will try to resend an event. Defaults to 5.
maxSockets
optional - string
Node.js agentOptions object to tune performance (6 default)
platform
optional - string
Sets the platform https://bit.ly/302dSQy ('srv' default)
screenResolution
optional - object
Sets device screen resolution if available
screenResolution.width
optional - number
Positive Integer for screen width
screenResolution.height
optional - number
Positive Integer for screen height
viewport
optional - object
Sets device viewport if available
viewport.width
optional - number
Positive Integer for viewport width
viewport.height
optional - number
Positive Integer for viewprt height
colorDepth
optional - number
Positive Integer, in bits per pixel
timezone
optional - string
Set user’s timezone e.g. 'Europe/London'
lang
optional - string
Ser user's lang e.globalThis. 'en'

Additional examples

Below are additional implementation examples.

Server-side ES6
import Analytics from 'analytics'
import snowplowPlugin from '@analytics/snowplow'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    snowplowPlugin({
      name: 'snowplow',
      collectorUrl: 'collector.mysite.com',
      appId: 'myApp'
    })
    // ...other plugins
  ]
})

/* Track a page view */
// Track page
analytics.page()

// or Track page view with additional entities
analytics.page({
  contexts: [
    {
      schema: 'iglu:com.acme/blog_post/jsonschema/1-0-0',
      data: {
        title: 'Re-thinking the structure of event data',
        url:
          'https://snowplowanalytics.com/blog/2020/01/24/re-thinking-the-structure-of-event-data/',
        category: 'Data Insights',
        author: 'Cara Baestlein',
        datePublished: '2020-01-24'
      }
    }
  ]
})

/* Track a custom event */
// Track structured event
analytics.track('playedVideo', {
  category: 'Videos',
  label: 'Fall Campaign',
  value: 42
})

// or Track Self Describing event
analytics.track('selfDescribingEvent', {
  schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
  data: {
    id: 42,
    title: 'Fall Campaign'
  }
})

// or Track Self Describing event with additional entities
analytics.track('selfDescribingEvent', {
  schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
  data: {
    id: 42,
    title: 'Fall Campaign',
    videoTimestampInMs: 1104
  },
  contexts: [
    {
      schema: 'iglu:com.acme/product/jsonschema/1-0-0',
      data: {
        id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
        category: 'clothing',
        subCategory: 'socks',
        price: 3.99
      }
    }
  ]
})

// or Track Enchanced Ecommerce event with product context
analytics.track('ScreenView', {
  name: 'Product Page',
  id: 'p-123',
  contexts: [
    {
      schema: 'iglu:com.acme/product/jsonschema/1-0-0',
      data: {
        id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
        category: 'clothing',
        subCategory: 'socks',
        price: 3.99
      }
    }
  ]
})

/* Identify a visitor */
analytics.identify('user-id-xyz', {
  firstName: 'bill',
  lastName: 'murray'
})

Server-side Node.js with common JS

If using node, you will want to import the .default

const analyticsLib = require('analytics').default
const snowplowPlugin = require('@analytics/snowplow').default

const analytics = analyticsLib({
  app: 'my-app-name',
  plugins: [
    snowplowPlugin({
      name: 'snowplow',
      collectorUrl: 'collector.mysite.com',
      appId: 'myApp'
    })
  ]
})

/* Track a page view */
// Track page
analytics.page()

// or Track page view with additional entities
analytics.page({
  contexts: [
    {
      schema: 'iglu:com.acme/blog_post/jsonschema/1-0-0',
      data: {
        title: 'Re-thinking the structure of event data',
        url:
          'https://snowplowanalytics.com/blog/2020/01/24/re-thinking-the-structure-of-event-data/',
        category: 'Data Insights',
        author: 'Cara Baestlein',
        datePublished: '2020-01-24'
      }
    }
  ]
})

/* Track a custom event */
// Track structured event
analytics.track('playedVideo', {
  category: 'Videos',
  label: 'Fall Campaign',
  value: 42
})

// or Track Self Describing event
analytics.track('selfDescribingEvent', {
  schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
  data: {
    id: 42,
    title: 'Fall Campaign'
  }
})

// or Track Self Describing event with additional entities
analytics.track('selfDescribingEvent', {
  schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
  data: {
    id: 42,
    title: 'Fall Campaign',
    videoTimestampInMs: 1104
  },
  contexts: [
    {
      schema: 'iglu:com.acme/product/jsonschema/1-0-0',
      data: {
        id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
        category: 'clothing',
        subCategory: 'socks',
        price: 3.99
      }
    }
  ]
})

// or Track Enchanced Ecommerce event with product context
analytics.track('ScreenView', {
  name: 'Product Page',
  id: 'p-123',
  contexts: [
    {
      schema: 'iglu:com.acme/product/jsonschema/1-0-0',
      data: {
        id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
        category: 'clothing',
        subCategory: 'socks',
        price: 3.99
      }
    }
  ]
})

/* Identify a visitor */
analytics.identify('user-id-xyz', {
  firstName: 'bill',
  lastName: 'murray'
})

Using in HTML

Below is an example of importing via the unpkg CDN. Please note this will pull in the latest version of the package.

<!DOCTYPE html>
<html>
  <head>
    <title>Using @analytics/snowplow in HTML</title>
    <script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>
    <script src="https://unpkg.com/@analytics/snowplow/dist/@analytics/snowplow.min.js"></script>
    <script type="text/javascript">
      /* Initialize analytics */
      var Analytics = _analytics.init({
        app: 'my-app-name',
        plugins: [
          // Minimal recommended configuration
          analyticsSnowplow({
            name: 'snowplow',
            collectorUrl: 'collector.mysite.com',
            trackerSettings: {
              appId: 'myApp'
            }
          })
        ]
      })

      /* Track a page view */
      // Enable some automatic tracking before page event
      analytics.on('initialize:snowplow', ({ instance }) => {
        instance.plugins.snowplow.enableActivityTracking(10, 10)
        instance.plugins.snowplow.enableLinkClickTracking()
      })

      // Track page
      analytics.page()

      // or Track page view with additional entities
      analytics.page({
        contexts: [
          {
            schema: 'iglu:com.acme/blog_post/jsonschema/1-0-0',
            data: {
              title: 'Re-thinking the structure of event data',
              category: 'Data Insights',
              author: 'Cara Baestlein',
              datePublished: '2020-01-24'
            }
          }
        ]
      })

      /* Track a custom event */
      // Track structured event
      analytics.track('playedVideo', {
        category: 'Videos',
        label: 'Fall Campaign',
        value: 42
      })

      // or Track Self Describing event
      analytics.track('selfDescribingEvent', {
        schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
        data: {
          id: 42,
          title: 'Fall Campaign'
        }
      })

      // or Track Self Describing event with additional entities
      analytics.track('selfDescribingEvent', {
        schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
        data: {
          id: 42,
          title: 'Fall Campaign',
          videoTimestampInMs: 1104
        },
        contexts: [
          {
            schema: 'iglu:com.acme/product/jsonschema/1-0-0',
            data: {
              id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
              category: 'clothing',
              subCategory: 'socks',
              price: 3.99
            }
          }
        ]
      })

      // or Track Enchanced Ecommerce event with product context
      analytics.track('EnhancedEcommerceProductContext', {
        id: 'P12345',
        name: 'Android Warhol T-Shirt',
        list: 'Search Results',
        brand: 'Google',
        category: 'Apparel/T-Shirts',
        variant: 'Black',
        quantity: 1
      })
      analytics.track('EnhancedEcommerceAction', {
        action: 'add'
      })

      /* Identify a visitor */
      analytics.identify('user-id-xyz')
    </script>
  </head>
  <body>
    ....
  </body>
</html>

Using in HTML via ES Modules

Using @analytics/snowplow in ESM modules.

<!DOCTYPE html>
<html>
  <head>
    <title>Using @analytics/snowplow in HTML via ESModules</title>
    <script>
      // Polyfill process.
      // **Note**: Because `import`s are hoisted, we need a separate, prior <script> block.
      window.process = window.process || { env: { NODE_ENV: 'production' } }
    </script>
    <script type="module">
      import analytics from 'https://unpkg.com/analytics/lib/analytics.browser.es.js?module'
      import analyticsSnowplow from 'https://unpkg.com/@analytics/snowplow/lib/analytics-plugin-snowplow.browser.es.js?module'
      /* Initialize analytics */
      const Analytics = analytics({
        app: 'analytics-html-demo',
        debug: true,
        plugins: [
          // Minimal recommended configuration
          analyticsSnowplow({
            name: 'snowplow',
            collectorUrl: 'collector.mysite.com',
            trackerSettings: {
              appId: 'myApp'
            }
          })
          // ... add any other third party analytics plugins
        ]
      })

      /* Track a page view */
      // Enable some automatic tracking before page event
      analytics.on('initialize:snowplow', ({ instance }) => {
        instance.plugins.snowplow.enableActivityTracking(10, 10)
        instance.plugins.snowplow.enableLinkClickTracking()
      })

      // Track page
      analytics.page()

      // or Track page view with additional entities
      analytics.page({
        contexts: [
          {
            schema: 'iglu:com.acme/blog_post/jsonschema/1-0-0',
            data: {
              title: 'Re-thinking the structure of event data',
              category: 'Data Insights',
              author: 'Cara Baestlein',
              datePublished: '2020-01-24'
            }
          }
        ]
      })

      /* Track a custom event */
      // Track structured event
      analytics.track('playedVideo', {
        category: 'Videos',
        label: 'Fall Campaign',
        value: 42
      })

      // or Track Self Describing event
      analytics.track('selfDescribingEvent', {
        schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
        data: {
          id: 42,
          title: 'Fall Campaign'
        }
      })

      // or Track Self Describing event with additional entities
      analytics.track('selfDescribingEvent', {
        schema: 'iglu:com.acme/video_played/jsonschema/1-0-0',
        data: {
          id: 42,
          title: 'Fall Campaign',
          videoTimestampInMs: 1104
        },
        contexts: [
          {
            schema: 'iglu:com.acme/product/jsonschema/1-0-0',
            data: {
              id: 'f9cb6cb6-5ca8-47a6-9035-d9c6ac13029e',
              category: 'clothing',
              subCategory: 'socks',
              price: 3.99
            }
          }
        ]
      })

      // or Track Enchanced Ecommerce event with product context
      analytics.track('EnhancedEcommerceProductContext', {
        id: 'P12345',
        name: 'Android Warhol T-Shirt',
        list: 'Search Results',
        brand: 'Google',
        category: 'Apparel/T-Shirts',
        variant: 'Black',
        quantity: 1
      })
      analytics.track('EnhancedEcommerceAction', {
        action: 'add'
      })

      /* Identify a visitor */
      analytics.identify('user-id-xyz')
    </script>
  </head>
  <body>
    ....
  </body>
</html>

See the full list of analytics provider plugins in the main repo.

版本与发布记录

@analytics/snowplow 共发布 11 个版本,首次发布于 2020/08/03;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.3.3latest2022/03/184 年前
0.3.22022/02/134 年前
0.3.12022/02/114 年前
0.3.02022/02/064 年前
0.2.52021/03/205 年前
0.2.42021/03/155 年前

关于 @analytics/snowplow 的常见问题

@analytics/snowplow 是什么?

Snowplow integration for 'analytics' module for browser & node

如何安装 @analytics/snowplow?

在项目目录运行 npm install @analytics/snowplow,或使用 pnpm add / yarn add / bun add。

@analytics/snowplow 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/analytics__snowplow 是否存在。

@analytics/snowplow 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@analytics/snowplow 可以商用吗?

@analytics/snowplow 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@analytics/snowplow 的下载量有多少?

根据 npm 官方下载统计,@analytics/snowplow 在 2026/10/06 – 2026/11/04 这 30 天内被下载 7,835 次,日均约 261 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@analytics/snowplow 还在维护吗?

最新版本 0.3.3 发布于 2022/03/18(4 年前);至今共发布 11 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/08/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。