Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@analytics/google-analytics

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@analytics/google-analytics

Google analytics plugin for 'analytics' module

  • 0.4.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
37K
decreased by-16.09%
Maintainers
1
Weekly downloads
 
Created
Source

Google Analytics

This library exports the google-analytics plugin for the analytics package & standalone methods for any project to use to make it easier to interact with Google Analytics.

This analytics plugin will load google analytics into your application.

For more information see the docs.

Click to expand

Installation

npm install analytics
npm install @analytics/google-analytics

How to use

The @analytics/google-analytics 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 googleAnalytics from '@analytics/google-analytics'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1234567'
    })
  ]
})

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

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

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

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

Browser usage

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

Browser API

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1234567'
    })
  ]
})

Configuration options for browser

Optiondescription
trackingId
required - string
Google Analytics site tracking Id
debug
optional - boolean
Enable Google Analytics debug mode
anonymizeIp
optional - boolean
Enable Anonymizing IP addresses sent to Google Analytics. See details below
customDimensions
optional - object
Map Custom dimensions to send extra information to Google Analytics. See details below
resetCustomDimensionsOnPage
optional - object
Reset custom dimensions by key on analytics.page() calls. Useful for single page apps.
setCustomDimensionsToPage
optional - boolean
Mapped dimensions will be set to the page & sent as properties of all subsequent events on that page. If false, analytics will only pass custom dimensions as part of individual events
instanceName
optional - string
Custom tracker name for google analytics. Use this if you need multiple googleAnalytics scripts loaded
customScriptSrc
optional - string
Custom URL for google analytics script, if proxying calls

Server-side usage

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

Server-side API

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

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

Configuration options for server-side

Optiondescription
trackingId
required - string
Google Analytics site tracking Id

Additional examples

Below are additional implementation examples.

Server-side ES6
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: '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 googleAnalytics = require('@analytics/google-analytics').default

const analytics = analyticsLib({
  app: 'my-app-name',
  plugins: [
    googleAnalytics({
      trackingId: '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/google-analytics in HTML</title>
    <script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>
    <script src="https://unpkg.com/@analytics/google-analytics/dist/@analytics/google-analytics.min.js"></script>
    <script type="text/javascript">
      /* Initialize analytics */
      var Analytics = _analytics.init({
        app: 'my-app-name',
        plugins: [
          analyticsGA.init({
            trackingId: 'UA-1234567'
          })
        ]
      })

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

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

      /* 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/google-analytics in ESM modules.

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

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

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

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

Anonymize Visitor IPs

Google analytics allows you to anonymize visitor IP addresses.

To anonymize the IP addresses of your visitors set the anonymizeIp configuration option.

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

/* initialize analytics */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1223141231',
      /* Anonymize the IP addresses */
      anonymizeIp: true
    }),
  ]
})

Customizing event payloads

To send tracking custom events to Google Analytics with eventLabel, eventCategory, and eventValue fields, add the label, category, and value keys to the event properties.

analytics.track('play', {
  category: 'Videos',
  label: 'Fall Campaign',
  value: 42
})

Using GA Custom Dimensions

To use Google Analytics custom dimensions, use the customDimensions configuration option and map the values to the custom dimension slots.

Set the "customDimensions" option

When initializing analytics, make sure you set customDimensions and map your values.

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

/* initialize analytics */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1223141231',
      /* Map your Google Analytics custom dimensions here */
      customDimensions: {
        baz: 'dimension1',
        foo: 'dimension2',
        flam: 'dimension3',
      },
    }),
  ]
})

The above config will map baz to dimension1, foo to dimension2, and flam to dimension3

When track, page, or identify calls are made the mapped values will automatically set to Google Analytics custom dimensions.

/* Tracking example */
analytics.track('buttonClicked', {
   baz: 'hello', // baz is mapped to GA custom dimension "dimension1"
   foo: 'cool'   // foo is mapped to GA custom dimension "dimension2"
})

Under the hood, analytics automatically sets the custom dimensions in Google Analytics like so:

window.ga('set', {dimension1: 'hello', dimension2: 'cool'})

This also works with page & identify calls.

/* Identify example */
analytics.identify('user123', {
   flam: 'wow' // flam is mapped to GA custom dimension "dimension3"
})

// This is mapped to window.ga('set', {  dimension3: 'wow' })

Using multiple instances

While not advised, it's possible to use multiple Google Analytics instances on a single site.

To use more than one google analytics instance in an app use the instanceName config field and make sure to override the default plugin name.

Here is an example of using 2 Google Analytics instances in an app.

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

// Normal google analytics instance
const instanceOne = googleAnalytics({
  trackingId: '123-xyz',
})

// Second google analytics instance with override for 'name' field of the plugin
const instanceTwo = {
  // initialize the 2nd instance with 'instanceName' field set
  ...googleAnalytics({
    trackingId: '567-abc',
    instanceName: 'two'
  }),
  // change 'name' plugin to avoid namespace collisions
  ...{
    name: 'google-analytics-two'
  }
}

/* Object.assign example
const instanceTwo = Object.assign({}, googleAnalytics({
    trackingId: '567-abc',
    instanceName: 'two'
  }), {
    name: 'google-analytics-two'
  }
}) */

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    // Instance 1 of Google Analytics
    instanceOne,
    // Instance 2 of Google Analytics
    instanceTwo
  ]
})

Using the above configuration all tracking, page views, and identify calls will flow into both Google Analytics accounts.

Custom Proxy Endpoint

In certain scenarios, you might want to load your own version of google analytics to send requests to a proxy.

To do this, you can add the customScriptSrc option pointing to your custom Google Analytics script

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: '123-xyz',
      customScriptSrc: 'https://my-url.com/to-custom-ga.js'
    })
  ]
})

If using a proxied endpoint, it is recommended to combine this technique to with the do-not-track plugin to ensure website visitors privacy.

Keywords

FAQs

Package last updated on 12 May 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc