@chordcommerce/analytics

中文文档
1.24.5发布于 2026/10/31MITTypeScriptES Module近 30 天下载 3710

Chord Commerce event tracking

原始使用文档
文档目录18 节
  1. Requirements
  2. Installation
  3. Usage
  4. CommonJS Import
  5. Configuration
  6. Formatters
  7. Using with Typescript
  8. API Reference
  9. Releasing
  10. How it works
  11. PR titles must follow conventional commits
  12. When a release happens (and when it doesn't)
  13. Monorepo scoping
  14. Pre-releases
  15. Beta release workflow
  16. Promoting beta to production
  17. Dry run
  18. Support

@chordcommerce/analytics

The @chordcommerce/analytics library provides simple methods for sending tracking events to Chord from your website, with an optional debugging mode to validate event properties.

Visit docs.chord.co for guides, examples, and an API reference.

Requirements

The library supports sending events via Chord CDP or Segment. If using Segment, analytics.js must also be installed in your project.

Installation

To install @chordcommerce/analytics, run the following command in your project directory:

npm install @chordcommerce/analytics
# or
yarn add @chordcommerce/analytics

Usage

Initialize @chordcommerce/analytics as follows:

import ChordAnalytics from '@chordcommerce/analytics'

const chord = new ChordAnalytics(options) // see below for configuration options

chord.trackCartViewed({ cart }) // sends a "Cart Viewed" event to the CDP

CommonJS Import

If you are using an older version of NodeJS (<v11) or Webpack, importing using the above ES6 import will probably fail. You can instead import using CommonJS:

const { ChordPixel } = require('@chordcommerce/analytics/dist/cjs')

Configuration

@chordcommerce/analytics can be initialized with the following options:

PropertyRequiredDescription
cdpfalseRequired when using a CDP other than Chord. A reference to the CDP library, or a function that returns a reference to the CDP library. For example, if using Segment's analytics.js library, this could be window.analytics or () => window.analytics.
cdpDomainfalseRequired when using Chord CDP. The Chord CDP domain. To be provided by the Chord team.
cdpWriteKeyfalseRequired when using Chord CDP. The Chord CDP write key. To be provided by the Chord team.
debugfalseDefaults to false. When set to true, events are validated against Chord's tracking plan and errors are logged. Validation uses zod 4. We recommend enabling this for development and disabling for production.
enableLoggingfalseDefaults to true. When set to true, errors are logged using console.log.
formatterstrueFunctions that are used to construct tracking events. There are two types of formatters, objects and events. formatters.objects is required. See below for details.
metadatatrueEvent metadata. See below for details.
namespacefalseDefaults to chord. Changes where Chord is globally available (e.g. window.chord). Only applicable when using Chord CDP.
stripNullfalseDefaults to true. When set to true, event properties with a null value are removed. CDPs typically treat null and undefined as separate values, so be sure you intend to send null values before setting to false.

If cdp, cdpDomain, and cdpWriteKey are all omitted, no tracking events are sent.

Metadata

PropertyRequiredDescription
metadata.i18n.currencytrueThe order currency in ISO 4217 currency code, uppercase. For example, USD.
metadata.i18n.localetrueThe order locale. For example, en-US.
metadata.ownership.omsIdtrueA UUID assigned by Chord.
metadata.ownership.storeIdtrueA UUID assigned by Chord.
metadata.ownership.tenantIdtrueA UUID assigned by Chord.
metadata.platform.nametrueThe e-commerce platform used. For example, Shopify.
metadata.platform.typetrueThe type of platform where the event originated. Either web or pos.
metadata.store.domaintrueThe domain of the site where the event originated. For Shopify, this should be the store slug that comes before .myshopify.com.

Formatters

Formatters are Javascript functions that are used to construct tracking event properties. There are two types of formatters, objects and events. You must define object formatters. Event formatters are optional. See Chord’s documentation for more details and example formatters.

Object Formatters

A formatter must be provided for each of the four core data types that are used in Chord events. This formatter function transforms input data into the type Chord expects. See Chord’s documentation for more details on object formatters.

PropertyRequiredDescription
formatters.objects.carttrueA function that creates a cart object.
formatters.objects.checkouttrueA function that creates a checkout object.
formatters.objects.lineItemtrueA function that creates a line item object.
formatters.objects.producttrueA function that creates a product object.

Event Formatters

A formatter can be provided for each event. This formatter is used to transform the event properties of a specific event after Chord constructs the event, just before it's sent to the CDP. See Chord’s documentation for more details on event formatters.

Using with Typescript

Optionally, you can instantiate ChordAnalytics with a custom type argument describing your data to improve type safety for formatters and SDK functions.

For instance, if you're working with objects like cart, product, etc., from a Shopify storefront API query, you might already have types like StorefrontCart defined for the response. Instantiate ChordAnalytics with a type argument:

interface ObjectTypes {
  Cart: StorefrontCart
  Checkout: StorefrontCart
  LineItem: StorefrontLineItem
  Product: StorefrontProduct
}

const chord = new ChordAnalytics<ObjectTypes>({ options })

Now, when you use an SDK method like chord.trackCartViewed({ cart }), cart has the StorefrontCart type.

Formatter types also support an optional generic type parameter for the function argument:

import type { CartFormatter } from '@chordcommerce/analytics'

export const cartFormatter: CartFormatter<StorefrontCart> = (props) => {
  const { cart } = props // `cart` has type `StorefrontCart`
  return { ... }
}

addSourceMiddleware(func: AnalyticsMiddleware)

Registers a middleware function to modify event properties before they are sent to analytics providers. Middleware functions are invoked in the order they were added during event tracking, and each one's properties are merged into the event in that order.

A middleware may be synchronous or asynchronous. Synchronous middleware is never awaited, so it adds no delay to event delivery. Asynchronous middleware is awaited before the event is sent, capped at three seconds — a middleware that has not resolved by then is abandoned, a warning is logged, and the event is sent without its properties. A middleware that throws or rejects is logged and skipped. A middleware never prevents an event from being sent.

Parameters

  • func (AnalyticsMiddleware) - A middleware function that receives event data and can return additional properties to merge into the event payload.

Return Value

The middleware function can return:

  • Partial - Properties to merge into the event payload
  • void - No additional properties to add
  • A Promise of either of the above - Awaited before the event is sent

The payload argument carries payload.obj (the event's properties, name and page context) plus payload.userId and payload.anonymousId as the CDP currently knows them — either may be undefined.

Note that middleware contributes properties by returning them. Mutating the payload argument has no effect; next is accepted for signature compatibility and does nothing.

Useage Example

  analytics.addSourceMiddleware(({ payload }) => {
    const { searchParams } = payload.obj.context.page;

    return {
      utm_source: searchParams.utm_source,
      utm_medium: searchParams.utm_medium,
      utm_campaign: searchParams.utm_campaign
    };
  });

  analytics.addSourceMiddleware(({ payload }) => {
    return {
      session_id: getSessionId(),
      user_agent: navigator.userAgent,
      timestamp: Date.now()
    };
  });

  // Asynchronous middleware: the event waits for the lookup, up to three seconds.
  analytics.addSourceMiddleware(async ({ payload }) => {
    if (payload.obj.event !== 'Order Completed') return;

    const isNewCustomer = await fetchIsNewCustomer();

    return { is_new_customer: isNewCustomer ? 1 : 0 };
  });

API Reference

See Chord’s documentation for a full API reference.

Releasing

This package uses semantic-release to automate versioning and publishing. Releases are triggered automatically — no manual version bumps or publish steps are needed.

How it works

The repo has a single CI workflow (.github/workflows/ci.yml) with two jobs:

  1. test — Runs lint, prettier, build, and tests for all packages. Triggers on every push to main/beta and on every pull request.
  2. release — Runs only on main and beta branches, after test passes. Runs semantic-release to determine if a new version should be published.

The release flow:

  1. Merge a PR into main (stable) or beta (pre-release).
  2. The test job runs. If it passes, the release job starts.
  3. semantic-release analyzes commit messages since the last release tag.
  4. If releasable commits exist, the package is published to npm and GitHub Packages, CHANGELOG.md is updated, and a Git tag is created.
  5. If no releasable commits exist, semantic-release exits cleanly and nothing is published.

PR titles must follow conventional commits

When using GitHub's squash merge (the default), the PR title becomes the first line of the squash commit message. Semantic-release only parses the first line to determine the version bump, so the PR title must use a conventional commit prefix (e.g., fix: resolve consent race condition). Individual commit messages in the PR body are ignored.

If the PR title does not start with a releasable prefix, no release will be published even if the individual commits within the PR use fix: or feat:.

When a release happens (and when it doesn't)

A release is published only when all three conditions are met:

  1. A push lands on main or beta (via merged PR or direct push)
  2. Tests pass
  3. There are new commits since the last release tag with a releasable prefix (checked against the first line of each commit message)

Releasable commit prefixes (these trigger a version bump):

PrefixVersion BumpExample
fix:Patch (1.0.0 → 1.0.1)fix: resolve race condition in consent adapter
feat:Minor (1.0.0 → 1.1.0)feat: add trackOrderCompleted method
BREAKING CHANGE: in bodyMajor (1.0.0 → 2.0.0)Commit body contains BREAKING CHANGE: remove legacy API

Non-releasable prefixes (these do NOT trigger a release):

chore:, ci:, docs:, refactor:, test:, style:, build:, perf:

If a merge to main or beta contains only non-releasable commits, the release job runs but semantic-release determines no release is needed and exits without publishing.

Monorepo scoping

This repo uses semantic-release-monorepo to scope releases to individual packages. Only commits that touch files within a package's directory (e.g., packages/core/) are considered when determining the next version. A feat: commit that only modifies .github/workflows/ or another package's directory will not trigger a release for @chordcommerce/analytics.

Pre-releases

Merging to beta creates pre-release versions (e.g., 1.22.0-beta.1). Use this for testing before promoting to main. Only main and beta are currently configured for automatic releases in the CI workflow. Additional prerelease branches (e.g., alpha) can be enabled by adding them to both the workflow's branch filter in ci.yml and the semantic-release branch config.

Beta release workflow

  1. Create a feature branch off beta and do your work.
  2. Create a PR targeting the beta branch and merge it.
  3. The CI workflow runs tests, then semantic-release publishes a beta version (e.g., 1.22.0-beta.1).
  4. Install with: npm install @chordcommerce/analytics@beta

Promoting beta to production

  1. Create a PR from beta → main and merge it.
  2. The CI workflow runs tests, then semantic-release publishes a stable version on main.

Dry run

You can preview what a release would do without publishing by manually triggering the CI workflow in GitHub Actions with dryRun set to true.

Support

For support with setup and configuration, please contact Chord directly at [email protected].

版本与发布记录

@chordcommerce/analytics 共发布 47 个版本,首次发布于 2024/03/05;过去 12 个月发布了 25 个版本。

版本发布日期距今
1.24.5latest2026/10/319 天前
1.24.42026/10/2218 天前
1.24.32026/10/1030 天前
1.24.22026/09/301 个月前
1.24.12026/09/251 个月前
1.25.0-beta.2beta2026/09/251 个月前

关于 @chordcommerce/analytics 的常见问题

@chordcommerce/analytics 是什么?

Chord Commerce event tracking

如何安装 @chordcommerce/analytics?

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

@chordcommerce/analytics 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@chordcommerce/analytics 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@chordcommerce/analytics 可以商用吗?

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

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

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

@chordcommerce/analytics 还在维护吗?

最新版本 1.24.5 发布于 2026/10/31(9 天前);至今共发布 47 个版本,其中过去 12 个月发布了 25 个;首次发布于 2024/03/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。