npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@haensl/google-analytics

v1.2.2

Published

Google Analytics 4 service abstraction for gtag and measurement protocol.

Downloads

77

Readme

@haensl/google-analytics

Google Analytics 4 JavaScript abstraction for ga4 (gtag) and measurement protocol (API).

NPM

npm version

CircleCI

@haensl/google-analytics is build with different runtime platforms (browser vs. Node.js) in mind:

On the client:

Use window.gtag (default): @haensl/google-analytics

import { init, event } from '@haensl/google-analytics';

On the server:

Use measurement protocol: @haensl/google-analytics/measurement-protocol

import { init, event } from '@haensl/google-analytics/measurement-protocol';

Attention: The measurement protocol abstraction requires a fetch implementation to work, e.g. node-fetch, cross-fetch, or similar. See init(config).

Installation

Via npm

$ npm install -S @haensl/google-analytics

Via yarn

$ yarn add @haensl/google-analytics

Usage

Client/tag and measurement protocol offer similar methods, but differ in initialization and dependencies.

gtag (client)

@haensl/google-analytics

The tag implementation relies on the existence of window.gtag. Please ensure that your page loads the Google Analytics 4 tag, e.g. by including a <script src="..."> to fetch gtag.js or via a component like @haensl/next-google-analytics

init(config)

import { init } from '@haensl/google-analytics'

Initializes the tracking module. You only need to call this once, e.g. when your app boots. This also calls install().

Tracking consent is defaulted to false for EU region. See consent().

init({
  /**
   * Google measurement id.
   *
   * E.g. 'G-123ABC456D'
   */
  measurementId,

  /**
   * Run gtag in debug mode.
   */
  debug = false,

  /**
   * Anonymize IP setting.
   */
  anonymizeIp = true,

  /**
   * Automatically send page views.
   */
  sendPageViews = false,

  /**
   * Whether the user has given her consent to track.
   */
  trackingConsent = false
})

install()

import { install } from '@haensl/google-analytics'

Installs window.dataLayer and window.gtag stubs, i.e. Google Docs. Is called on init().

consent(granted = false)

import { consent } from '@haensl/google-analytics'

Grant or deny tracking consent.

Granting/Denying tracking consent toggles:

For more information on consent mode, see Google's docs.

consent(granted = false)

Example: User grants consent:

import { consent } from '@haensl/google-analytics';

// Consent button click handler.
const onConsentTap = () => {
  consent(true);
};

// Attach to consent button.
button.onClick = onConsentTap;

event({ name, params })

import { event } from '@haensl/google-analytics'

Track an event.

event({
  /**
   * Event name. String.
   */
  name,

  /**
   * Event parameters.
   *
   * An object mapping names to strings or numbers.
   */
  params
})

Example: Sign up event

import { event } from '@haensl/google-analytics';

// track a sign up from the footer form.
event({
  name: 'sign_up',
  params: {
    form: 'footer'
  }
});

exception({ description, fatal })

import { exception } from '@haensl/google-analytics'

Tracks an exception. Alias for event({ name: 'exception', ... }).

exception({
  /**
   * Error description. String.
   */
  description,

  /**
   * Whether or not the error is fatal. Boolean.
   */
  fatal = false
})

pageView({ location, title })

import { pageView } from '@haensl/google-analytics'

Tracks a page view. Alias for event({ name: 'page_view', ... }).

pageView({
  /**
   * Page title. String.
   */
  title,

  /**
   * Page location. String.
   */
  location
})

setUserId({ id })

import { setUserId } from '@haensl/google-analytics'

Set the user id.

setUserId({
  /**
   * A user id. String.
   */
  id
})

setUserProperty({ name, value })

import { setUserProperty } from '@haensl/google-analytics'

Set a user property (formerly known as dimension).

setUserProperty({
  /**
   * User property name. String.
   */
  name,

  /**
   * User property value. String or number.
   */
  value
})

Example: track the users color scheme:

import { setUserProperty } from '@haensl/google-analytics';

setUserProperty({
 name: 'appearance',
 value: 'dark'
});

Measurement protocol

@haensl/google-analytics/measurement-protocol

The measurement protocol implementation requires an API secret as well as a fetch implementation at initialization.

init(config)

import { init } from '@haensl/google-analytics/measurement-protocol'

Initialize the measurement protocol module.

init({
  /**
   * Fetch implementation. Function.
   */
  fetch,

  /**
   * Google measurement id. String.
   *
   * E.g. 'G-123ABC456D'
   */
  measurementId,

  /**
   * Google measurement API secret. String.
   */
  measurementSecret,

  /**
   * Measurement API URL. String.
   */
  measurementUrl = 'https://www.google-analytics.com/mp/collect'
})

Example

import fetch from 'node-fetch';
import { init } from '@haensl/google-analytics/measurement-protocol';

init({
  fetch,
  measurementId: 'G-123ABC456D',
  measurementSecret: 'super-secret'
});

clientId(cookies)

import { clientId } from '@haensl/google-analytics/measurement-protocol'

Tries to parse the Google Analytics client id from the given cookies object.

Generates a client id from timestamps if not found in cookies.

clientId(cookies = {}) => String

Example: Usage with next-cookies

import { cookies } from 'next-cookies';
import { clientId, pageView } from '@haensl/google-analytics/measurement-protocol';


export const getServerSideProps = async (ctx) => {
  const requestCookies = cookies(ctx);
  const requestClientId = clientId(requestCookies);

  pageView({
    title: 'my serverside page',
    clientId: requestClientId,
    location: ctx.req.url
  });
};

async event({ name, params, clientId })

import { event } from '@haensl/google-analytics/measurement-protocol'

Track an event.

async event({
  /**
   * Event name. String.
   */
  name,

  /**
   * Event parameters.
   *
   * An object mapping names to strings or numbers.
   */
  params,

  /**
   * The client id. String.
   */
  clientId
}) => Promise

Example: Sign up event

import { event, clientId } from '@haensl/google-analytics/measurement-protocol';

// track a sign up from the footer form.
await event({
  name: 'sign_up',
  params: {
    form: 'footer'
  },
  // Extract client id from context
  clientId: clientId(ctx.cookies)
});

async exception({ description, fatal clientId })

import { exception } from '@haensl/google-analytics/measurement-protocol'

Tracks an exception. Alias for event({ name: 'exception', ... }).

async exception({
  /**
   * Error description. String.
   */
  description,

  /**
   * Whether or not the error is fatal. Boolean.
   */
  fatal = false,

  /**
   * The client id. String.
   */
  clientId
}) => Promise

async pageView({ location, title, clientId })

import { pageView } from '@haensl/google-analytics/measurement-protocol'

Tracks a page view. Alias for event({ name: 'page_view', ... }).

async pageView({
  /**
   * Page title. String.
   */
  title,

  /**
   * Page location. String.
   */
  location,

  /**
   * The client id. String.
   */
  clientId
}) => Promise

async setUserId({ id, clientId })

import { setUserId } from '@haensl/google-analytics/measurement-protocol'

Set the user id.

async setUserId({
  /**
   * A user id. String.
   */
  id,

  /**
   * The client id. String.
   */
  clientId
}) => Promise

async setUserProperty({ name, value, clientId })

import { setUserProperty } from '@haensl/google-analytics/measurement-protocol'

Set a user property.

async setUserProperty({
  /**
   * User property name. String.
   */
  name,

  /**
   * User property value. String or number.
   */
  value,

  /**
   * The client id. String.
   */
  clientId
}) => Promsie

Example: track the users color scheme:

import { clientId, setUserProperty } from '@haensl/google-analytics/measurement-protocol';

await setUserProperty({
 name: 'appearance',
 value: 'dark',
 // Extract client id from context.
 clientId: clientId(ctx.cookies)
});

Changelog

License