Google Analytics 4 JavaScript abstraction for ga4 (gtag) and measurement protocol (API).
@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).
$ npm install -S @haensl/google-analytics$ yarn add @haensl/google-analyticsClient/tag and measurement protocol offer similar methods, but differ in initialization and dependencies.
-
init(confg): Initialize the gtag module.install: Installs gtag stubs onwindow.consent(granted): Consent to tracking.event(data): Track an event.exception(data): Track an exception.pageView(data): Track a page view.setUserId({ id }): Set the user id.setUserProperty({ name, value })
-
init(confg): Initialize the measurement protocol module.clientId(cookies): Get a client id.async event(data): Track an event.async exception(data): Track an exception.async pageView(data): Track a page view.async setUserId({ id }): Set the user id.async setUserProperty({ name, value })
@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
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
})import { install } from '@haensl/google-analytics'
Installs window.dataLayer and window.gtag stubs, i.e. Google Docs. Is called on init().
import { consent } from '@haensl/google-analytics'
Grant or deny tracking consent.
Granting/Denying tracking consent toggles:
- Google signals
- Ad personalization signals
- Restricted data processing
- Ads data redaction
- Ad storage
- Analytics storage
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;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'
}
});
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
})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
})import { setUserId } from '@haensl/google-analytics'
Set the user id.
setUserId({
/**
* A user id. String.
*/
id
})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'
});@haensl/google-analytics/measurement-protocol
The measurement protocol implementation requires an API secret as well as a fetch implementation at initialization.
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'
});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 = {}) => StringExample: 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
});
};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
}) => PromiseExample: 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)
});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
}) => Promiseimport { 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
}) => Promiseimport { setUserId } from '@haensl/google-analytics/measurement-protocol'
Set the user id.
async setUserId({
/**
* A user id. String.
*/
id,
/**
* The client id. String.
*/
clientId
}) => Promiseimport { 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
}) => PromsieExample: 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)
});