Google Analytics 4
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
| Option | Type | Required | Description |
|---|---|---|---|
measurementId | string | ✅ | GA4 Measurement ID (e.g. G-XXXXXXXXXX) |
gtag | GtagFunction | — | Custom gtag function (defaults to window.gtag) |
debug | boolean | — | Enable GA4 debug mode on all events |
Event Mapping
The provider automatically maps CommerceJS events to GA4 recommended events:
| CommerceJS Event | GA4 Event |
|---|---|
product.viewed | view_item |
cart.item.added | add_to_cart |
cart.item.removed | remove_from_cart |
cart.created | begin_checkout |
checkout.started | begin_checkout |
checkout.completed | purchase |
order.created | purchase |
payment.created | add_payment_info |
payment.confirmed | add_payment_info |
customer.registered | sign_up |
customer.logged_in | login |
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,
})