Analytics
/

Segment

Using the segment plugin


Integration with segment for analytics

Click to expand

Installation

npm install analytics
npm install @analytics/segment

How to use

The @analytics/segment 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 segmentPlugin from '@analytics/segment'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    })
  ]
})

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

/* Track a custom event */
analytics.track('cartCheckout', {
  item: 'pink socks',
  price: 20
})

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

After initializing analytics with the segmentPlugin plugin, data will be sent into Segment 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/segment package works in the browser and server-side in Node.js

Browser usage

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

Browser API

import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    })
  ]
})

Configuration options for browser

Optiondescription
writeKey
required - string
Your segment writeKey
disableAnonymousTraffic
optional - boolean
Disable loading segment for anonymous visitors
customScriptSrc
optional - boolean
Override the Segment snippet url, for loading via custom CDN proxy
integrations
optional - object
Enable/disable segment destinations https://bit.ly/38nRBj3

Server-side usage

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

Server-side API

import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    })
  ]
})

Configuration options for server-side

Optiondescription
writeKey
required - string
Key that corresponds to your Segment.io project
disableAnonymousTraffic
optional - boolean
Disable loading segment for anonymous visitors
host
optional - string
The base URL of the API. Default: "https://api.segment.io"
path
optional - string
The API path route. Default: "/v1/batch"
maxRetries
optional - number
The number of times to retry flushing a batch. Default: 3
maxEventsInBatch
optional - number
The number of messages to enqueue before flushing. Default: 15
flushInterval
optional - number
The number of milliseconds to wait before flushing the queue automatically. Default: 10000
httpRequestTimeout
optional - number
The maximum number of milliseconds to wait for an http request. Default: 10000
disable
optional - boolean
Disable the analytics library. All calls will be a noop. Default: false.
httpClient
optional - HTTPFetchFn
Supply a default http client implementation

Additional examples

Below are additional implementation examples.

Server-side ES6
import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    })
    // ...other plugins
  ]
})

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

/* Track a custom event */
analytics.track('cartCheckout', {
  item: 'pink socks',
  price: 20
})

/* 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 segmentPlugin = require('@analytics/segment').default

const analytics = analyticsLib({
  app: 'my-app-name',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    })
  ]
})

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

/* Track a custom event */
analytics.track('cartCheckout', {
  item: 'pink socks',
  price: 20
})

/* 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/segment in HTML</title>
    <script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>
    <script src="https://unpkg.com/@analytics/segment/dist/@analytics/segment.min.js"></script>
    <script type="text/javascript">
      /* Initialize analytics */
      var Analytics = _analytics.init({
        app: 'my-app-name',
        plugins: [
          analyticsSegment({
            writeKey: '123-xyz'
          })
        ]
      })

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

      /* Track a custom event */
      analytics.track('cartCheckout', {
        item: 'pink socks',
        price: 20
      })

      /* Identify a visitor */
      analytics.identify('user-id-xyz', {
        firstName: 'bill',
        lastName: 'murray'
      })
    </script>
  </head>
  <body>
    ....
  </body>
</html>
Using in HTML via ES Modules

Using @analytics/segment in ESM modules.

<!DOCTYPE html>
<html>
  <head>
    <title>Using @analytics/segment 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 analyticsSegment from 'https://unpkg.com/@analytics/segment/lib/analytics-plugin-segment.browser.es.js?module'
      /* Initialize analytics */
      const Analytics = analytics({
        app: 'analytics-html-demo',
        debug: true,
        plugins: [
          analyticsSegment({
            writeKey: '123-xyz'
          })
          // ... add any other third party analytics plugins
        ]
      })

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

      /* Track a custom event */
      analytics.track('cartCheckout', {
        item: 'pink socks',
        price: 20
      })

      /* Identify a visitor */
      analytics.identify('user-id-xyz', {
        firstName: 'bill',
        lastName: 'murray'
      })
    </script>
  </head>
  <body>
    ....
  </body>
</html>

Customing the page name field

By default the page name is the document.title value.

To have shorter names call page like so:

analytics.page({
  name: 'HomePage'
})

This can quickly become tricky to manage and we'd advise against this approach.

Loading script from custom proxy

In specific scenarios, you might want to load your own version of segment's analytics from a different URL.

To do this, you can add the customScriptSrc option pointing to your custom segment script.

import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz',
      // Load segment's analytics.js from somewhere else
      customScriptSrc: 'https://yoursite.com/my-custom-loader.js'
    })
  ]
})

Making group calls

The .group call is specific to Segment and the analytics lib doesn't expose this by default. But you are in luck 😃 thanks to custom methods on plugins!

To send a group call to Segment run the analytics.plugins.segment.group() custom method.

The analytics.plugins.segment.group function has the following signature:

analytics.group(groupId, [traits], [options], [callback]);

Browser Example

import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'

// Initialize analytics instance with plugins
const analytics = Analytics({
  app: 'your-app-name',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    }),
  ]
})

// Usage:
// Now you can call segment.group in your app like so
analytics.plugins.segment.group('Group ID XYZ', {
  principles: ['Bill', 'Bob'],
  site: 'Apple co',
  statedGoals: 'Do awesome stuff',
  industry: 'Technology'
})

Server side Example

const analyticsLib = require('analytics').default
const segmentPlugin = require('@analytics/segment')

// Initialize analytics instance with plugins
const analytics = Analytics({
  app: 'your-app-name',
  plugins: [
    segmentPlugin({
      writeKey: '123-xyz'
    }),
  ]
})

analytics.plugins.segment.group('Group ID XYZ', {
  principles: ['Bill', 'Bob'],
  site: 'Apple co',
  statedGoals: 'Do awesome stuff',
  industry: 'Technology'
})