@riculum/ga4-mp-client
v0.1.0
Published
A lightweight, type-safe Google Analytics 4 Measurement Protocol client for Node.js and Next.js server-side tracking.
Maintainers
Readme
@riculum/ga4-mp-client
A small, type-safe Google Analytics 4 (GA4) Measurement Protocol client for Node.js and Next.js server-side code.
This package lets you send GA4 events via the Measurement Protocol (/mp/collect) and optionally validate payloads via the Debug endpoint (/debug/mp/collect).
It is designed for:
- server-side tracking
- Next.js App Router / Server Actions
- clean, minimal APIs without unnecessary abstractions
Installation
npm install @riculum/ga4-mp-clientRequirements
You need a GA4 property with a Web data stream and the following credentials:
- Measurement ID (e.g.
G-XXXXXXXXXX) - API Secret (from Measurement Protocol settings)
Set them as environment variables:
GA4_MEASUREMENT_ID=G-XXXXXXXXXX
GA4_API_SECRET=xxxxxxxxxxxxxxxxRecommended Setup: Create a Global Client
Create the GA4 client once and reuse it everywhere.
For example in Next.js:
lib/ga.ts
import { createGa4MpClient } from '@riculum/ga4-mp-client'
export const ga = createGa4MpClient({
measurementId: process.env.GA4_MEASUREMENT_ID!,
apiSecret: process.env.GA4_API_SECRET!,
region: 'region1',
})Usage
Purchase Event
Important notes:
purchasemust includetransaction_id- GA4 calculates revenue from
value, not fromitems[].price
import { ga } from '@/lib/ga'
const res = await ga.send({
event: 'purchase',
body: { client_id: metadata.google.clientId },
params: {
transaction_id: order.id,
currency: 'CHF',
value: 20.90,
items: [
{
item_id: '1',
item_name: 'T-Shirt',
quantity: 1,
price: 20.90,
},
],
},
})
if (!res.ok) {
console.error('GA4 purchase failed', res.status, res.error)
}Add to Cart Event
const res = await ga.send({
event: 'add_to_cart',
body: { client_id: metadata.google.clientId },
params: {
currency: 'CHF',
value: 20.90,
items: [
{
item_id: '1',
item_name: 'T-Shirt',
quantity: 1,
price: 20.90,
},
],
},
})Custom Event
await ga.send({
event: 'trial_started',
body: { client_id: metadata.google.clientId },
params: {
plan: 'pro',
source: 'pricing_page',
},
})Debugging
Validate Payloads
await ga.send({
event: 'purchase',
body: { client_id: metadata.google.clientId },
debug: true,
params: {
transaction_id: `test-${Date.now()}`,
currency: 'CHF',
value: 20.90,
items: [{ item_id: '1', item_name: 'T-Shirt', quantity: 1, price: 20.90 }],
},
})GA4 DebugView
await ga.send({
event: 'purchase',
body: { client_id: metadata.google.clientId },
params: {
debug_mode: true,
transaction_id: `test-${Date.now()}`,
currency: 'USD',
value: 20.90,
items: [{ item_id: '1', item_name: 'T-Shirt', quantity: 1, price: 20.90 }],
},
})License
MIT
