Analytics

Google Analytics 4

Google Analytics 4 provider for automatic commerce event tracking.

Google Analytics 4 provider for CommerceJS — automatically maps commerce events to GA4 recommended events.

Installation

pnpm add @commercejs/analytics-ga

No additional Google Analytics SDK is needed — the provider uses the browser's gtag() global that's loaded by the GA4 snippet.

Quick Start

import { createCommerce } from '@commercejs/core'
import { createGA4Provider } from '@commercejs/analytics-ga'

const ga4 = createGA4Provider({
  measurementId: 'G-XXXXXXXXXX',
})

const commerce = createCommerce({
  adapter,
  analytics: [ga4],
})

All commerce events are now automatically tracked in GA4.

Configuration

OptionTypeRequiredDescription
measurementIdstringGA4 Measurement ID (e.g. G-XXXXXXXXXX)
gtagGtagFunctionCustom gtag function (defaults to window.gtag)
debugbooleanEnable GA4 debug mode on all events

Event Mapping

The provider automatically maps CommerceJS events to GA4 recommended events:

CommerceJS EventGA4 Event
product.viewedview_item
cart.item.addedadd_to_cart
cart.item.removedremove_from_cart
cart.createdbegin_checkout
checkout.startedbegin_checkout
checkout.completedpurchase
order.createdpurchase
payment.createdadd_payment_info
payment.confirmedadd_payment_info
customer.registeredsign_up
customer.logged_inlogin

Unmapped events (e.g. wishlist.item.added) are sent as custom events with dots converted to underscores (wishlist_item_added).

Methods

track(event, properties?)

Sends a commerce or custom event. Properties are forwarded directly to GA4.

identify(userId, traits?)

Sets GA4 user properties via gtag('set', 'user_properties', ...).

page(name, properties?)

Sends a page_view event with page_title set to name.

SSR Safety

The provider is safe to use in SSR environments. If window.gtag is not available (e.g. during server-side rendering), all calls are silently no-ops — no errors thrown.

Debug Mode

Enable debug mode to see events in the GA4 DebugView:

const ga4 = createGA4Provider({
  measurementId: 'G-XXXXXXXXXX',
  debug: true,
})