### Project Setup and Initial Build Source: https://github.com/segmentio/analytics-next/blob/master/DEVELOPMENT.md Clone the repository, set up the correct Node.js version, install dependencies, and perform an initial build and lint/test cycle. ```sh git clone git@github.com:segmentio/analytics-next.git && cd analytics-next nvm use # install version of node defined in .nvmrc. yarn && yarn build yarn lint && yarn test ``` -------------------------------- ### Development Setup for Analytics-Next Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Clone the repository and set up the local development environment. This includes installing dependencies, building the project, and running tests. ```sh $ git clone git@github.com:segmentio/analytics-next.git $ cd analytics-next $ nvm use # installs correct version of node defined in .nvmrc. $ yarn && yarn build $ yarn test $ yarn dev # optional: runs analytics-next playground. ``` -------------------------------- ### Install and Build Project Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/e2e-cli/README.md Installs project dependencies and builds the project. Run this before using the CLI. ```bash npm install npm run build ``` -------------------------------- ### Install Segment Analytics Node.js SDK Source: https://github.com/segmentio/analytics-next/blob/master/packages/node/README.md Install the library using npm, yarn, or pnpm. ```bash # npm npm install @segment/analytics-node # yarn yarn add @segment/analytics-node # pnpm pnpm install @segment/analytics-node ``` -------------------------------- ### Install @segment/analytics-consent-wrapper-onetrust Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-wrapper-onetrust/README.md Install the package using npm, yarn, or pnpm. ```sh # npm npm install @segment/analytics-consent-wrapper-onetrust # yarn yarn add @segment/analytics-consent-wrapper-onetrust # pnpm pnpm add @segment/analytics-consent-wrapper-onetrust ``` -------------------------------- ### Run Development Server Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/next-playground/README.md Start the Next.js development server to view your application locally. ```bash yarn dev ``` -------------------------------- ### Start the Standalone Playground Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/README.md Run this command in your terminal to start the standalone playground for the snippet version of the app. ```bash yarn start ``` -------------------------------- ### Run Integration Tests Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-tools-integration-tests/README.md Builds the project, starts the test server, and runs integration tests, ensuring a graceful exit. ```bash yarn . test:int ``` -------------------------------- ### Install Analytics Next.js via npm Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Install the @segment/analytics-next package using npm, yarn, or pnpm. ```sh # npm npm install @segment/analytics-next # yarn yarn add @segment/analytics-next # pnpm pnpm add @segment/analytics-next ``` -------------------------------- ### Basic Usage with Segment Analytics Browser Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Import and load the AnalyticsBrowser with your write key, then start tracking events. ```ts import { AnalyticsBrowser } from '@segment/analytics-next' const analytics = AnalyticsBrowser.load({ writeKey: '' }) analytics.identify('hello world') document.body?.addEventListener('click', () => { analytics.track('document body clicked!') }) ``` -------------------------------- ### Track Event Example Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-consent-opt-out.html Sends a 'track' event to Segment. Requires the event name, properties, and optional settings. The event details are parsed from a JSON input. ```javascript const displayRegularLogs = (str) => document.querySelector('#logs').textContent = str; const logEvent = (promise) => { if (Array.isArray(promise)) { displayRegularLogs('Analytics is not initialized!'); setTimeout(() => displayRegularLogs(''), 5000); return; } if (promise) { promise.then((ctx) => { ctx.flush(); displayRegularLogs(JSON.stringify(ctx.event, null, 2)); }); } }; document.querySelector('#track').addEventListener('click', async (e) => { e.preventDefault(); const contents = document.querySelector('#event').value; const evt = JSON.parse(contents); const promise = window.analytics.track(evt.name ?? '', evt.properties ?? {}, evt.options ?? {}); logEvent(promise); }); ``` -------------------------------- ### Implement Destination Middleware for a Specific Destination Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/architecture/ARCHITECTURE.md Add destination middleware to affect events sent to a specific device-mode destination. This example targets the 'amplitude' destination and adds a custom property. ```typescript analytics.addDestinationMiddleware('amplitude', ({ next, payload }) => { payload.obj.properties!.hello = 'from the other side' next(payload) }) ``` -------------------------------- ### Identify Event Example Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-consent-opt-out.html Sends an 'identify' event to Segment, used for user identification. Requires user ID, traits, and optional settings. Event details are parsed from a JSON input. ```javascript const displayRegularLogs = (str) => document.querySelector('#logs').textContent = str; const logEvent = (promise) => { if (Array.isArray(promise)) { displayRegularLogs('Analytics is not initialized!'); setTimeout(() => displayRegularLogs(''), 5000); return; } if (promise) { promise.then((ctx) => { ctx.flush(); displayRegularLogs(JSON.stringify(ctx.event, null, 2)); }); } }; document.querySelector('#identify').addEventListener('click', async (e) => { e.preventDefault(); const contents = document.querySelector('#event').value; const evt = JSON.parse(contents); const promise = window.analytics.identify(evt.name ?? '', evt.properties ?? {}, evt.options ?? {}); logEvent(promise); }); ``` -------------------------------- ### Implement a 'Before' Plugin Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/architecture/ARCHITECTURE.md Register a custom 'before' plugin to modify events before they are processed by other plugins. This example demonstrates transforming event names to lowercase and dropping specific page events. ```typescript analytics.register({ name: 'My Plugin', type: 'before', isLoaded: () => true, load: () => Promise.resolve(), // lowercase all track event names track: (ctx) => { ctx.event.event = ctx.event.event.toLowerCase() return ctx }, // drop page events with a specific title page: (ctx) => { if (ctx.properties.title === 'some title') { return null } return ctx } }) ``` -------------------------------- ### Implement Source Middleware Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/architecture/ARCHITECTURE.md Add source middleware to intercept and modify events before they enter the pipeline. This example shows converting track event names to lowercase and conditionally dropping page events. ```typescript analytics.addSourceMiddleware(({ payload, next }) => { const { event } = payload.obj.context if (event.type === 'track') { // change the event name to lowercase event.event = event.event.toLowerCase() } else if (event.type === 'page') { // drop any page events with a specific title if (event.properties.title === 'some title') { return null } } next(payload) }) ``` -------------------------------- ### Analytics.js Initialization Flow Diagram Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/architecture/ARCHITECTURE.md Illustrates the bootstrapping and initialization process of Analytics.js, from web page load to event processing. ```mermaid graph TD subgraph Load Phase Start([Web Page Load]) --> LoadAJS[Fetch analytics.js
from CDN] LoadAJS --> InitAJS[analytics.load
with writeKey] InitAJS --> FetchSettings[Fetch settings
from cdn.segment.io] end subgraph Plugin Registration Phase FetchSettings --> RegisterCore[Register Core Plugins
and Middleware] RegisterCore --> ParseDest[Parse Device Mode
Destinations] end subgraph Destination Loading Phase ParseDest --> LoadDests{Load Device Mode
Destinations} LoadDests -->|Async| Dest1[Load Destination 1
+ Scripts] LoadDests -->|Async| Dest2[Load Destination 2
+ Scripts] LoadDests -->|Async| DestN[Load Destination N
+ Scripts] end subgraph Event Processing Phase Dest1 --> Ready1[Destination 1
Ready] Dest2 --> Ready2[Destination 2
Ready] DestN --> ReadyN[Destination N
Ready] Ready1 --> Flush1[Flush Events to
Destination 1] Ready2 --> Flush2[Flush Events to
Destination 2] ReadyN --> FlushN[Flush Events to
Destination N] end RegisterCore -.->|Events Blocked
Until Complete| ParseDest LoadDests -.->|Critical Plugins
Block Events| EventReady[Event Pipeline Ready] class Dest1,Dest2,DestN,Flush1,Flush2,FlushN async ``` -------------------------------- ### Watch Consent Packages and Dependencies Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/README.md Use this command from the repository root to continuously build all consent packages and their dependencies as changes are made. ```sh yarn turbo run watch --filter './packages/consent/*...' ``` -------------------------------- ### Add TypeScript Support for Analytics.js Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Configure your TypeScript project to recognize the Segment Analytics.js types. This involves installing the necessary npm package and updating your tsconfig.json. ```typescript // ./typings/analytics.d.ts import type { AnalyticsSnippet } from "@segment/analytics-next"; declare global { interface Window { analytics: AnalyticsSnippet; } } ``` ```json // tsconfig.json { ... "compilerOptions": { .... "typeRoots": [ "./node_modules/@types", "./typings" ] } .... } ``` -------------------------------- ### Test Changelog Locally Source: https://github.com/segmentio/analytics-next/blob/master/RELEASING.md Use this command to preview the changelog locally before merging. Ensure your GITHUB_TOKEN is exported. ```bash export GITHUB_TOKEN="???" yarn changeset version ``` -------------------------------- ### View Next Release Changes Source: https://github.com/segmentio/analytics-next/blob/master/RELEASING.md Run this command to see what changes are included in the upcoming release. ```bash yarn changeset info ``` -------------------------------- ### Initialize Segment with OneTrust Wrapper (npm) Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-wrapper-onetrust/README.md Import `withOneTrust` and `AnalyticsBrowser`, then initialize Segment using the wrapper function before loading. ```ts import { withOneTrust } from '@segment/analytics-consent-wrapper-onetrust' import { AnalyticsBrowser } from '@segment/analytics-next' export const analytics = new AnalyticsBrowser() withOneTrust(analytics).load({ writeKey: '' }) ``` -------------------------------- ### Manually Create a Release Source: https://github.com/segmentio/analytics-next/blob/master/RELEASING.md This command sequence allows for manual creation of a release, including updating versions, generating changelogs, committing artifacts, and publishing. Ensure your GITHUB_TOKEN is exported for changelog generation. ```bash export GITHUB_TOKEN="???" ## changelog generator requirement (https://github.com/settings/tokens) yarn update-versions-and-changelogs && ## bump + generate changelog + delete old changesets git add . && # add generated artifacts git commit -m "v1.X.X" && yarn release ``` -------------------------------- ### Run QA Tests Against All Destinations Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/qa/README.md Initiate QA tests to verify compatibility with all supported destinations. This command ensures broad coverage. ```sh make test-qa-destinations ``` -------------------------------- ### Build Package and Run Tests Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-tools/README.md Commands to build the consent-tools package and run its tests using yarn. ```sh yarn . build ``` ```sh yarn test ``` -------------------------------- ### Track Event with Segment Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local-csp.html This snippet listens for a click event on a 'track' button. It parses JSON input from a text area to get event details and then calls the `analytics.track` method. Use this to send custom events to Segment. ```javascript if (window.analytics) { window.analytics.ready(function onReady() { console.profileEnd('snippet') console.timeEnd('snippet') document.querySelector('#ready-logs').textContent = 'ready!' }) document.querySelector('#track').addEventListener('click', function (e) { e.preventDefault() var contents = document.querySelector('#event').value var evt = JSON.parse(contents) var promise = window.analytics.track( evt.name || '', evt.properties || {}, evt.options || {} ) promise && promise.then && promise.then(function (ctx) { ctx.flush() document.querySelector('#logs').textContent = JSON.stringify( ctx.event, null, ' ' ) }) }) } ``` -------------------------------- ### Run Node Integration Tests Source: https://github.com/segmentio/analytics-next/blob/master/packages/node-integration-tests/README.md Build dependencies and run the integration tests for the node-integration-tests package. This command should be executed from the repository root. ```sh yarn turbo run --filter=node-integration-tests test ``` -------------------------------- ### Identify User with Segment Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local-csp.html This snippet listens for a click event on an 'identify' button. It parses JSON input from a text area to get user details and then calls the `analytics.identify` method. Use this to send user profile information to Segment. ```javascript if (window.analytics) { window.analytics.ready(function onReady() { console.profileEnd('snippet') console.timeEnd('snippet') document.querySelector('#ready-logs').textContent = 'ready!' }) document.querySelector('#identify') .addEventListener('click', function (e) { e.preventDefault() var contents = document.querySelector('#event').value var evt = JSON.parse(contents) var promise = window.analytics.identify( evt.name || '', evt.properties || {}, evt.options || {} ) promise && promise.then && promise.then(function (ctx) { ctx.flush() document.querySelector('#logs').textContent = JSON.stringify( ctx.event, null, ' ' ) }) }) } ``` -------------------------------- ### Set Up QA Test Environment Variables Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/qa/README.md Export environment variables for QA samples and sources using aws-okta. These variables are necessary for running the QA tests. ```sh export QA_SAMPLES=$(aws-okta exec dev-write -- chamber read analytics-next QA_SAMPLES -q) export QA_SOURCES=$(aws-okta exec dev-write -- chamber read analytics-next QA_SOURCES -q) ``` -------------------------------- ### Load Segment Analytics with Consent Wrapper (npm) Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-tools/README.md Initializes Segment Analytics Browser and loads it using the `withCMP` wrapper. This is for projects using npm and ES6 imports. ```javascript import { withCMP } from './wrapper' import { AnalyticsBrowser } from '@segment/analytics-next' export const analytics = new AnalyticsBrowser() withCMP(analytics).load({ writeKey: ' }) ``` -------------------------------- ### Run All QA Tests Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/qa/README.md Execute all QA tests in a single run. This command is comprehensive but generally slower than running individual tests. ```sh $ make test-qa ## if you'd like to run all tests in one go (generally slower) ``` -------------------------------- ### Handle Segment.io Ready State Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local.html This snippet registers a callback to be executed when the Segment.io analytics library is ready. It logs a message to the console and updates the UI to indicate readiness. This ensures that subsequent analytics calls are made only after initialization is complete. ```javascript if (window.analytics) { window.analytics.ready(function onReady() { console.profileEnd('snippet') console.timeEnd('snippet') document.querySelector('#ready-logs').textContent = 'ready!' }) } ``` -------------------------------- ### Configure NPM Token Locally Source: https://github.com/segmentio/analytics-next/blob/master/RELEASING.md Add your NPM token to the ~/.npmrc file for local testing and authentication. This allows npm commands to use your token. ```bash # Add token to your ~/.npmrc echo "//registry.npmjs.org/:_authToken=YOUR_NEW_TOKEN" > ~/.npmrc # Verify authentication npm whoami # Build packages yarn build # Test dry-run publish (doesn't actually publish) cd packages/core && npm publish --dry-run cd ../browser && npm publish --dry-run cd ../node && npm publish --dry-run ``` -------------------------------- ### Build Packages Matching a Pattern with Turborepo Source: https://github.com/segmentio/analytics-next/blob/master/DEVELOPMENT.md Use Turborepo to build packages that match a file path pattern, including all their dependencies. ```sh yarn run -T turbo run build --filter='./packages/node*' ``` -------------------------------- ### Run Individual QA Tests Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/qa/README.md Execute specific QA tests by providing a test path. This method is significantly faster for targeted testing. ```sh $ yarn jest --runTestsByPath qa/__tests__/ ``` -------------------------------- ### Compile Analytics-Next (Browser) Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/qa/README.md Compile the Analytics-Next package for browser usage. This is the first step before running QA tests. ```sh $ yarn build ``` -------------------------------- ### Load Segment Analytics with OneTrust Consent (Opt-Out) Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-consent-opt-out.html Initializes Segment Analytics Next using the standalone build, integrating with OneTrust for consent management in an opt-out model. It loads the script and sets up basic event listeners. ```javascript const { searchParams } = new URL(document.location); const writeKey = searchParams.get("writeKey"); document.querySelector("input").value = writeKey; // Clear OneTrust Cookies & Reload document.getElementById('clear-ot-cookies').addEventListener('click', () => { ['OptanonConsent', 'OptanonAlertBoxClosed'].forEach((name) => { document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; }); window.location.reload(); console.log("OneTrust Cookies cleared."); }); (function loadOt() { const otKey = new URL(document.location).searchParams.get("otKey"); var t = document.createElement('script'); t.type = 'text/javascript'; t.src = 'https://cdn.cookielaw.org/scripttemplates/otSDKStub.js'; t.setAttribute('data-domain-script', otKey || '09b87b90-1b30-4d68-9610-9d2fe11234f3-test'); var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(t, n); })(); if (writeKey) { !(function () { var analytics = (window.analytics = window.analytics || []); if (!analytics.initialize) { if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.'); else { analytics.invoked = !0; analytics.methods = [ 'screen', 'register', 'deregister', 'trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'once', 'off', 'on', 'addSourceMiddleware', 'addIntegrationMiddleware', 'setAnonymousId', 'addDestinationMiddleware', 'emit' ]; analytics.factory = function (e) { return function () { if (window.analytics.initialized) { // Sometimes users assigned analytics to a variable before analytics is done loading, resulting in a stale reference. // If so, proxy any calls to the 'real' analytics instance. return window.analytics[e].apply(window.analytics, arguments); } var t = Array.prototype.slice.call(arguments); t.unshift(e); analytics.push(t); return analytics; }; }; for (var e = 0; e < analytics.methods.length; e++) { var key = analytics.methods[e]; analytics[key] = analytics.factory(key); } analytics.load = function (key, e) { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = !0; t.src = '/node_modules/@segment/analytics-next/dist/umd/standalone.js'; var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(t, n); analytics._loadOptions = e; }; analytics.SNIPPET_VERSION = '4.13.1'; analytics._writeKey = writeKey; withOneTrust(analytics, { consentModel: () => 'opt-out', enableDebugLogging: true }).load(); analytics.page(); } } })(); } ``` -------------------------------- ### Run E2E Test CLI Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/e2e-cli/README.md Executes the E2E test CLI with JSON input. Replace '...' with your actual JSON input. ```bash node dist/cli.js --input '{"writeKey":"...", ...}' ``` -------------------------------- ### Build Specific Package with Turborepo Source: https://github.com/segmentio/analytics-next/blob/master/DEVELOPMENT.md Use Turborepo to build a specific package and all its dependencies, identified by its full name. ```sh yarn run -T turbo run build --filter=@segment/analytics-next ``` -------------------------------- ### Run E2E Test CLI with Batching Enabled Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/e2e-cli/README.md Enables batching mode for the E2E test CLI using an environment variable. Replace '...' with your actual JSON input. ```bash BROWSER_BATCHING=true node dist/cli.js --input '...' ``` -------------------------------- ### Handling Initialization Errors Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Catch initialization errors from .load() to handle them explicitly. Errors are logged by default. ```ts export const analytics = new AnalyticsBrowser(); analytics .load({ writeKey: "MY_WRITE_KEY" }) .catch((err) => ...); ``` -------------------------------- ### Load Segment Analytics with Consent Wrapper (Snippet Users) Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-tools/README.md Adapts the `withCMP` wrapper for snippet users (window.analytics). It requires removing the default `analytics.load()` from the snippet and then using the wrapper to load analytics. ```javascript import { withCMP } from './wrapper' withCMP(window.analytics).load('' with your actual Segment write key. ```typescript import { Analytics } from '@segment/analytics-node' // or, if you use require: const { Analytics } = require('@segment/analytics-node') // instantiation const analytics = new Analytics({ writeKey: '' }) app.post('/login', (req, res) => { analytics.identify({ userId: req.body.userId, previousId: req.body.previousId }) res.sendStatus(200) }) app.post('/cart', (req, res) => { analytics.track({ userId: req.body.userId, event: 'Add to cart', properties: { productId: '123456' } }) res.sendStatus(201) }); ``` -------------------------------- ### Implement Destination Middleware for All Destinations Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/architecture/ARCHITECTURE.md Apply destination middleware to all device-mode destinations by using a wildcard. This allows for broad interception and modification of events before they are sent. ```typescript analytics.addDestinationMiddleware('*', ({ next, payload }) => { ... }) ``` -------------------------------- ### Load Segment Standalone Snippet Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local-csp.html This snippet initializes and loads the Segment standalone snippet. It retrieves the write key from the URL and injects the script asynchronously. Use this to set up Segment on your website. ```javascript const { searchParams } = new URL(document.location); const writeKey = searchParams.get("writeKey"); document.querySelector("input").value = writeKey; if (writeKey) { console.profile('snippet') console.time('snippet') !(function () { var analytics = (window.analytics = window.analytics || []); if (!analytics.initialize) if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.'); else { analytics.invoked = !0; analytics.methods = [ 'screen', 'register', 'deregister', 'trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'once', 'off', 'on', 'addSourceMiddleware', 'addIntegrationMiddleware', 'setAnonymousId', 'addDestinationMiddleware', ]; analytics.factory = function (e) { return function () { var t = Array.prototype.slice.call(arguments); t.unshift(e); analytics.push(t); return analytics; }; }; for (var e = 0; e < analytics.methods.length; e++) { var key = analytics.methods[e]; analytics[key] = analytics.factory(key); } analytics.load = function (key, e) { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = !0; t.src = '/node_modules/@segment/analytics-next/dist/umd/standalone.js'; var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(t, n); analytics._loadOptions = e; }; analytics.SNIPPET_VERSION = '4.13.1'; analytics._writeKey = writeKey; analytics.load(); analytics.page(); } })(); } ``` -------------------------------- ### Load Segment Snippet Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local-track-link.html This code initializes the Segment snippet, loads the standalone bundle, and sets the write key from the URL. It's designed to be included in an HTML page. ```javascript const { searchParams } = new URL(document.location); const writeKey = searchParams.get("writeKey"); document.querySelector("input").value = writeKey; if (writeKey) { console.profile('snippet') console.time('snippet') !(function () { var analytics = (window.analytics = window.analytics || []); if (!analytics.initialize) if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.'); else { analytics.invoked = !0; analytics.methods = [ 'screen', 'register', 'deregister', 'trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'once', 'off', 'on', 'addSourceMiddleware', 'addIntegrationMiddleware', 'setAnonymousId', 'addDestinationMiddleware' ]; analytics.factory = function (e) { return function () { var t = Array.prototype.slice.call(arguments); t.unshift(e); analytics.push(t); return analytics; }; }; for (var e = 0; e < analytics.methods.length; e++) { var key = analytics.methods[e]; analytics[key] = analytics.factory(key); } analytics.load = function (key, e) { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = !0; t.src = '/node_modules/@segment/analytics-next/dist/umd/standalone.js'; var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(t, n); analytics._loadOptions = e; }; analytics.SNIPPET_VERSION = '4.13.1'; analytics._writeKey = writeKey; analytics.load(); analytics.page(); } })(); } ``` -------------------------------- ### Run Tests for Consent Packages Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/README.md Execute tests for all consent packages from the repository root. This command utilizes ts-jest for in-memory TypeScript compilation and does not require an active watch process. ```sh yarn turbo run test --filter './packages/consent/*' ``` -------------------------------- ### Load Segment Analytics.js Snippet Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-remote.html This snippet dynamically loads the Segment Analytics.js library. It retrieves the write key from the URL and initializes Segment if the key is present. It also includes basic error handling for duplicate snippet inclusion. ```javascript const { searchParams } = new URL(document.location); const writeKey = searchParams.get("writeKey"); document.querySelector("input").value = writeKey; if (writeKey) { !(function () { var analytics = (window.analytics = window.analytics || []); if (!analytics.initialize) { if (analytics.invoked) { window.console && console.error && console.error('Segment snippet included twice.'); } else { analytics.invoked = !0; analytics.methods = [ 'screen', 'register', 'deregister', 'trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'once', 'off', 'on', 'addSourceMiddleware', 'addIntegrationMiddleware', 'setAnonymousId', 'addDestinationMiddleware', ]; analytics.factory = function (e) { return function () { var t = Array.prototype.slice.call(arguments); t.unshift(e); analytics.push(t); return analytics; }; }; for (var e = 0; e < analytics.methods.length; e++) { var key = analytics.methods[e]; analytics[key] = analytics.factory(key); } analytics.load = function (key, e) { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = !0; t.src = 'https://cdn.segment.com/analytics.js/v1/' + writeKey + '/analytics.min.js'; var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(t, n); analytics._loadOptions = e; }; analytics.SNIPPET_VERSION = '4.13.1'; analytics._writeKey = writeKey; analytics.load(); analytics.page(); } } })(); } ``` -------------------------------- ### Delayed Loading with Asynchronous Write Key Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Load the AnalyticsBrowser after fetching the write key asynchronously. This allows for dynamic configuration. ```ts const analytics = new AnalyticsBrowser() fetchWriteKey().then(writeKey => analytics.load({ writeKey })) analytics.identify("hello world") ``` -------------------------------- ### Create Consent Wrapper with CMP Integration Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-tools/README.md Defines a wrapper function `withCMP` that integrates with a Consent Management Platform (CMP). It handles waiting for the CMP to be ready, deciding when to load Segment based on consent, retrieving consent categories, and registering callbacks for consent changes. ```typescript import { createWrapper, resolveWhen } from '@segment/analytics-consent-tools' export const withCMP = createWrapper({ // Wait to load wrapper or call "shouldLoadSegment" until window.CMP exists. shouldLoadWrapper: async () => { await resolveWhen(() => window.CMP !== undefined, 500) }, // Allow for control over wrapper + analytics initialization. // Delay any calls to analytics.load() until this function returns / resolves. shouldLoadSegment: async (ctx) => { /* // Optional -- for granular control of initialization if (noConsentNeeded) { ctx.abort({ loadSegmentNormally: true }) } else if (allTrackingDisabled) { ctx.abort({ loadSegmentNormally: false }) } */ if (window.CMP.ConsentModel === 'opt-out') { return ctx.load({ consentModel: 'opt-out' }) } else { await resolveWhen( () => !window.CMP.popUpVisible() && window.CMP.categories.length, 500 ) return ctx.load({ consentModel: 'opt-in' }) } }, getCategories: () => { return normalizeCategories(window.CMP.consentedCategories()) // Expected format: { foo: true, bar: false } }, registerOnConsentChanged: (setCategories) => { window.CMP.onConsentChanged((event) => { setCategories(normalizeCategories(event.detail)) }) }, }) ``` -------------------------------- ### Add OneTrust Snippet and Segment Wrapper to HTML Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-wrapper-onetrust/README.md Include the OneTrust SDK stub and the Segment OneTrust wrapper script in your HTML head. Modify the Segment analytics snippet to use the `withOneTrust` function for loading. ```html ``` -------------------------------- ### Vanilla React Integration Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/README.md Integrate AnalyticsBrowser into a Vanilla React application. Export the analytics instance for shared access. ```tsx import { AnalyticsBrowser } from '@segment/analytics-next' // We can export this instance to share with rest of our codebase. export const analytics = AnalyticsBrowser.load({ writeKey: '' }) const App = () => (
) ``` -------------------------------- ### Initialize Segment Analytics Snippet Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser-integration-tests/standalone.html This snippet initializes the Segment analytics object in the browser. It ensures the snippet is only included once and defines all available analytics methods, making them available for use. ```javascript (function () { var analytics = (window.analytics = window.analytics || []); if (!analytics.initialize) { if (analytics.invoked) { window.console && console.error && console.error('Segment snippet included twice.'); } else { analytics.invoked = !0; analytics.methods = [ 'trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'once', 'off', 'on', 'addSourceMiddleware', 'addIntegrationMiddleware', 'setAnonymousId', 'addDestinationMiddleware' ]; analytics.factory = function (e) { return function () { var t = Array.prototype.slice.call(arguments); t.unshift(e); analytics.push(t); return analytics; }; }; for (var e = 0; e < analytics.methods.length; e++) { var key = analytics.methods[e]; analytics[key] = analytics.factory(key); } analytics.load = function (key, e) { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = !0; t.src = 'https://cdn.segment.com/analytics.js/v1/' + key + '/analytics.min.js'; var n = document.getElementsByTagName('script')[0]; n.parentNode.insertBefore(t, n); analytics._loadOptions = e; analytics._writeKey = key; }; analytics.SNIPPET_VERSION = '4.15.3'; } } })(); ``` -------------------------------- ### E2E Test CLI Successful Output Format Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/e2e-cli/README.md The JSON output format indicating a successful test run. ```json { "success": true, "sentBatches": 1 } ``` -------------------------------- ### Track Event with Batching Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local-batched.html This code snippet attaches an event listener to a button to track a 'track' event. It parses event data from a textarea, sends it using `analytics.track()`, and logs the flushed event context. This demonstrates sending events when batching is enabled. ```javascript if (window.analytics) { window.analytics.ready(function onReady() { console.profileEnd('snippet') console.timeEnd('snippet') document.querySelector('#ready-logs').textContent = 'ready!' }) document.querySelector('#track').addEventListener('click', function (e) { e.preventDefault() var contents = document.querySelector('#event').value var evt = JSON.parse(contents) var promise = window.analytics.track( evt.name || '', evt.properties || {}, evt.options || {} ) promise && promise.then && promise.then(function (ctx) { ctx.flush() document.querySelector('#logs').textContent = JSON.stringify( ctx.event, null, ' ' ) }) }) ``` -------------------------------- ### Track Event with Buffered Page Context Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-buffered-page-ctx.html This snippet demonstrates how to track an event using the Segment analytics.track method. It parses event details from a textarea and logs the context. ```javascript if (window.analytics) { // misc analytics.on('page', (...args) => console.log('analytics.on("page"', ...args)) window.analytics.ready(function onReady() { console.profileEnd('snippet') console.timeEnd('snippet') document.querySelector('#ready-logs').textContent = 'ready!' }) document.querySelector('#track').addEventListener('click', function (e) { e.preventDefault() var contents = document.querySelector('#event').value var evt = JSON.parse(contents) console.profile('track') console.time('track') var promise = window.analytics.track( evt.name || '', evt.properties || {}, evt.options || {} ) promise && promise.then && promise.then(function (ctx) { console.timeEnd('track') console.profileEnd('track') ctx.flush() document.querySelector('#logs').textContent = JSON.stringify( ctx.event, null, ' ' ) }) }) } ``` -------------------------------- ### E2E Test CLI Input Format Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser/e2e-cli/README.md Defines the structure of the JSON input required by the CLI for configuring events and SDK settings. ```jsonc { "writeKey": "your-write-key", // required "apiHost": "https://...", // optional — SDK default if omitted "cdnHost": "https://...", // optional — SDK default if omitted "sequences": [ // required — event sequences to send { "delayMs": 0, "events": [ { "type": "track", "event": "Test", "userId": "user-1" } ] } ], "config": { // optional "flushAt": 1, "flushInterval": 1000, "maxRetries": 3, "timeout": 15 } } ``` -------------------------------- ### Add Polyfills for IE11 Support Source: https://github.com/segmentio/analytics-next/blob/master/packages/consent/consent-wrapper-onetrust/README.md If targeting IE11, include a polyfill script before the main analytics scripts to ensure compatibility. ```html ``` -------------------------------- ### Track Event with Segment.io Source: https://github.com/segmentio/analytics-next/blob/master/playgrounds/standalone-playground/pages/index-local.html This snippet attaches a click listener to a button to send a 'track' event to Segment.io. It parses event data from a textarea and logs the event context upon successful tracking. Ensure the Segment.io library is loaded before executing this. ```javascript if (window.analytics) { document.querySelector('#track').addEventListener('click', function (e) { e.preventDefault(); var contents = document.querySelector('#event').value; var evt = JSON.parse(contents); console.profile('track') console.time('track') var promise = window.analytics.track( evt.name || '', evt.properties || {}, evt.options || {} ); promise && promise.then && promise.then(function (ctx) { console.timeEnd('track') console.profileEnd('track') ctx.flush(); document.querySelector('#logs').textContent = JSON.stringify( ctx.event, null, ' ' ); }) }) } ``` -------------------------------- ### Segment Analytics Snippet Initialization Source: https://github.com/segmentio/analytics-next/blob/master/packages/browser-integration-tests/standalone-custom-key.html This JavaScript code initializes the Segment analytics object on the window. It ensures that the analytics object exists and defines its methods, preparing it for later loading of the main analytics library. This is the core snippet executed when Segment is integrated. ```javascript (function () { var i = 'segment_analytics', analytics = (window[i] = window[i] || []); if (!analytics.initialize) { if (analytics.invoked) { window.console && console.error && console.error('Segment snippet included twice.'); } else { analytics.invoked = !0; analytics.methods = [ 'trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'screen', 'once', 'off', 'on', 'addSourceMiddleware', 'addIntegrationMiddleware', 'setAnonymousId', 'addDestinationMiddleware', 'register' ]; analytics.factory = function (e) { return function () { if (window[i].initialized) return window[i][e].apply(window[i], arguments); var n = Array.prototype.slice.call(arguments); if (['track', 'screen', 'alias', 'group', 'page', 'identify'].indexOf(e) > -1) { var c = document.querySelector("link[rel='canonical']"); n.push({ __t: 'bpc', c: (c && c.getAttribute('href')) || void 0, p: location.pathname, u: location.href, s: location.search, t: document.title, r: document.referrer }); } n.unshift(e); analytics.push(n); return analytics; }; }; for (var n = 0; n < analytics.methods.length; n++) { var key = analytics.methods[n]; analytics[key] = analytics.factory(key); } analytics.load = function (key, n) { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = !0; t.setAttribute('data-global-segment-analytics-key', i); t.src = 'https://cdn.segment.com/analytics.js/v1/' + key + '/analytics.min.js'; var r = document.getElementsByTagName('script')[0]; r.parentNode.insertBefore(t, r); analytics._loadOptions = n; analytics._writeKey = key; }; analytics.SNIPPET_VERSION = '5.2.0'; } } })(); ```