Segment Analytics-Next

repository·master·Indexed 19 days ago

https://github.com/segmentio/analytics-next

A monorepo containing Segment's flagship JavaScript and TypeScript SDKs, providing modern implementations of the Analytics.js protocol for browser and Node.js environments. Includes the @segment/analytics-next library for manual instrumentation and @segment/analytics-consent-tools for managing Consent Management Platform (CMP) interactions and consent models (opt-in/opt-out).

Tokens
60.4K
Snippets
202
Records
256
Agent score
61%

What's inside analytics-next

  1. Overview of @segment/analytics-generic-utils

    master

    The @segment/analytics-generic-utils package is a collection of shared, generic utility functions used across the Segment Analytics ecosystem. It is designed to function similarly to lodash, providing common helper functions.

    To maintain its role as a pure utility library, it adheres to two strict constraints:

    1. It has no external dependencies.
    2. It contains no references to the Analytics domain (e.g., no Segment-specific types or logic).
  2. Overview of analytics.js (analytics-next)

    master
    The analytics-next monorepo contains Segment's latest JavaScript and TypeScript SDKs. It provides modern, high-performance implementations of the Analytics.js protocol for different environments, specifically targeting web browsers and Node.js.
  3. Overview of Consent Management for Analytics.js

    master

    The Consent Management packages provide tools for integrating Analytics.js with various Consent Management Platforms (CMPs). This allows you to manage user privacy preferences and ensure analytics tracking respects user consent settings.

    Available packages include:

    • @segment/analytics-consent-tools: A general-purpose library for integrating analytics with consent management platforms.
    • @segment/analytics-consent-wrapper-onetrust: A specialized library specifically for using the OneTrust consent management platform with Analytics.js.
  4. Overview of @segment/analytics-node integration tests

    master

    The @segment/analytics-node integration test suite covers three primary areas of concern:

    • Durability Tests (./src/durability-tests): Verifies that all events created by the Analytics SDK are successfully converted into HTTP requests and ensures that graceful shutdowns do not result in event loss.
    • Performance Tests (./src/perf-tests): Confirms that performance remains stable relative to the previous SDK version and the baseline (a handler without analytics).
    • Cloudflare Workers Tests (./src/cloudflare-tests/): Validates that the SDK operates correctly within the Cloudflare Workers environment.
  5. Understand the @internal/consent-tools-integration-tests project structure

    master

    The integration test suite is organized into the following directory structure:

    • /public: The root directory for the test server.
      • /dist: Contains the Webpacked page-bundles that are injected into each HTML page.
    • /src: Contains the test suite source files.
      • /page-bundles: Used for testing libraries that do not provide a UMD bundle (e.g., analytics-consent-tools).
      • /page-objects: Contains Page Object models used by the test suite.
      • /page-tests: Contains the actual test files that are executed on the page.
  6. How the Analytics.js event pipeline works

    master

    When an event is triggered (e.g., via analytics.track(), analytics.page(), or analytics.identify()), it moves through a structured pipeline:

    1. Event Creation: The Event Factory creates the event object.
    2. Queueing: The event enters the internal Event Queue.
    3. Before Plugins: These run first in order of registration. They are Critical and can block the pipeline (e.g., for validation).
    4. Enrichment Plugins: These run after 'Before' plugins. They are also Critical and can modify events (e.g., adding user agent info).
    5. Destination Plugins: These run in parallel. They cannot modify the event and are Non-Critical (failures do not stop the pipeline).
    6. After Plugins: These run after all other plugins have completed, typically used for observability or metrics.
  7. Configure Consent Models

    master

    The wrapper supports different consent models which determine how and when Segment loads destinations. The wrapper uses the OneTrust.getDomainData() API to detect the model for a given geolocation.

    Supported Models

    • opt-in (Strict/GDPR): Waits for explicit consent (e.g., the user closes the alert box) before loading device mode destinations and initializing Segment. If no mapped categories are consented to, Segment is not loaded.
    • opt-out: Loads Segment immediately and all destinations based on default categories. For device mode destinations, analytics.js-originated events (like analytics.track) are filtered based on current consent.
    • default/other: Defaults to opt-out behavior.

    You can manually override the detected model by providing a function to the consentModel option in the withOneTrust constructor:

    withOneTrust(analytics, { 
      consentModel: () => 'opt-in' // or 'opt-out'
    }).load({ writeKey: '<MY_WRITE_KEY>' })
    withOneTrust(analytics, { consentModel: () => 'opt-in' | 'opt-out' })
      .load({ writeKey: '<MY_WRITE_KEY>' })
  8. Implement Lazy / Delayed Loading with AnalyticsBrowser

    master

    If you need to wait for user consent or fetch configuration asynchronously before starting tracking, use the buffered approach.

    1. Instantiate new AnalyticsBrowser() without calling .load() immediately. This buffers events.
    2. Call .load({ writeKey: '...' }) exactly once when you are ready. This fetches destinations and flushes all buffered events.

    Note: .load should only be called once.

    export const analytics = new AnalyticsBrowser()
    
    // Events called before .load() are buffered
    analytics.identify("hello world")
    
    if (userConsentsToBeingTracked) {
        // This triggers destination loading and flushes buffered events
        analytics.load({ writeKey: '<YOUR_WRITE_KEY>' }) 
    }
  9. Understand the Changeset workflow

    master

    This repository uses changesets to manage versioning, changelogs, and publishing.

    A changeset is a text file in .changesets/* that represents an intent to release specific packages with a particular semver bump type and a summary of changes.

    To inspect upcoming changes before a release, use:

    yarn changeset info

    To preview the generated changelog locally, you must provide a GITHUB_TOKEN:

    export GITHUB_TOKEN="???"
    yarn changeset version