ga4-node v1.0.1
GA-4 for Node
Report Google Analytics 4 events from a Node server.
Prerequisites
This library reads a _ga cookie from a network request, and relies on this
being available. This will typically involve adding Google Analytics to your
client-side, receiving network requests to endpoints from users with the cookie
embedded in them, and forwarding it to the await ga({ req, ... }) function.
If you're using Next,
nextjs-google-analytics
is recommended. User requests to your API routes will then contain the necessary
_ga cookie, and you can send server-side GA4 events.
Usage
Whenever you send an event, the following will be needed:
an API secret, provided via
ga({ apiSecret })arg orprocess.env.GA_API_SECRET.To create a new secret, navigate to: Admin > Data Streams > choose your stream > Measurement Protocol > Create.
a measurement ID associated with a data stream, provided via
ga({ measurementId })orprocess.env.GA_MEASUREMENT_IDenv var.Found in the Google Analytics UI under: Admin > Data Streams > choose your stream > Measurement ID.
a
reqobject containing a{ cookies: { ... } }property, from which the client ID will be extracted.an
eventsarray, of form{ name: ..., params: { ... } }.
E.g., the following Next API route handler:
import { ga } from "ga4-node"
/**
* GA_API_SECRET and GA_MEASUREMENT_ID provided via process.env.
*/
export default async function handler(req, res) {
/**
* Do something.
*/
await makeOfflinePurchase(/* ... */);
/**
* Send GA event.
*/
await ga({
req,
events: [
{
name: "offline_purchase",
params: {
engagement_time_msec: "100",
session_id: "123",
// ...
},
},
// ...,
]
});
}