Sub topic 15
Sending Events from a Server with the Measurement Protocol
This chapter assumes you can already send recommended and custom events with gtag.js, and that you know what event parameters are. You should also know the difference between recommended and custom events, and you should have a GA4 property with a web data stream.
The Measurement Protocol (MP) is an HTTP interface for sending events to GA4 from places where gtag.js or Google Tag Manager cannot run. Typical examples are a backend that confirms a payment, a CRM that records a closed deal, or a point-of-sale system. MP supplements client-side tagging. It does not replace it.
What the Measurement Protocol is for
Use MP when the event happens outside the browser, or when the browser cannot be trusted to report it.
- A purchase is confirmed by a payment provider's webhook after the user has left your site.
- A user signs up through a mobile app or API and your server is the only system that sees it.
- An offline action, such as a refund or a subscription renewal, needs to be tied to an existing user.
MP is a poor fit for replacing standard page tracking. It has no automatic collection. It does not capture page views, sessions, device details, or the enhanced measurement events. You must send everything you want to record.
The request
An MP call is an HTTP POST with a JSON body. Two values go in the query string, and the identifiers go in the body.
POST https://www.google-analytics.com/mp/collect?measurement_id=G-XXXXXXXXXX&api_secret=API_SECRET
Content-Type: application/json
{
"client_id": "CLIENT_ID",
"events": [
{
"name": "sign_up",
"params": {
"method": "email"
}
}
]
}This sends the recommended sign_up event with its recommended method parameter.
| Piece | Where it goes | What it is |
|---|---|---|
| `measurement_id` | Query string | The `G-` ID of the web data stream. |
| `api_secret` | Query string | A secret you create for the stream. |
| `client_id` | Body | Identifies the browser or device instance. |
| `events` | Body | An array of event objects, each with a `name` and optional `params`. |
You create the API secret in the GA4 Admin area, in the data stream's details under Measurement Protocol API secrets. Treat it as a credential. Keep it on the server, load it from an environment variable or a secrets manager, and never put it in front-end code or a public repository. If it leaks, delete it and create a new one.
Linking server events to browser users
The client_id is the most common source of mistakes. GA4 uses it to decide which user an event belongs to. If you invent a new value, GA4 creates a new user with no history. The event will not join the session that came from the browser.
To attach a server event to a browser user, read the real client ID in the browser and pass it to your server. With gtag.js you can retrieve it using the get command:
gtag('get', 'G-XXXXXXXXXX', 'client_id', (clientId) => {
// Send clientId to your server with the checkout request,
// for example in a hidden form field or a JSON payload.
console.log(clientId);
});Your server stores this value with the order. When the payment webhook arrives later, the server includes the same client_id in the MP request.
If you also send a user_id in the body, GA4 can connect events across devices for signed-in users. user_id is optional. Never use an email address or other personal data as the value. Use an internal identifier.
Sending a purchase from the server
Here is a complete Node.js example that sends the recommended purchase event after a payment is confirmed. It uses the fetch function built into Node 18 and later.
const MEASUREMENT_ID = process.env.GA4_MEASUREMENT_ID;
const API_SECRET = process.env.GA4_API_SECRET;
async function sendPurchase(clientId, order) {
const url =
'https://www.google-analytics.com/mp/collect' +
`?measurement_id=${encodeURIComponent(MEASUREMENT_ID)}` +
`&api_secret=${encodeURIComponent(API_SECRET)}`;
const body = {
client_id: clientId,
events: [
{
name: 'purchase',
params: {
transaction_id: order.id,
value: order.total,
currency: 'USD',
items: order.items.map((item) => ({
item_id: item.sku,
item_name: item.name,
price: item.price,
quantity: item.quantity
}))
}
}
]
};
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
return response.status;
}
sendPurchase('CLIENT_ID', {
id: 'T_12345',
total: 59.98,
items: [{ sku: 'SKU_123', name: 'Trail Shoes', price: 29.99, quantity: 2 }]
}).then((status) => console.log('MP status:', status));The parameter names match the ones you used with gtag.js. A recommended event sent through MP follows the same naming and parameter rules as one sent from the browser. The same applies to custom events: the name must still be snake_case and within GA4's limits.
Sessions and engagement
GA4 reports are built around sessions, and MP events do not start a session on their own. Events with no session information can show up in reports as part of the "(not set)" or unattributed traffic, or they may not appear in session-based reports at all. To attach an event to an existing session, include session_id and engagement_time_msec in params. The session ID can be read in the browser in the same way as the client ID, using the session_id field. Without these values, the event still counts in event reports, but attribution is weaker.
Events also carry a timestamp. By default GA4 uses the time it receives the request. If you send events later than they happened, set timestamp_micros at the top level of the body. GA4 accepts only a limited backdating window, so do not use MP to load old history.
Validating requests
The collection endpoint returns a success status even when the payload is malformed. A 204 response tells you the request was received. It does not tell you the event was valid. Do not use the live endpoint to debug.
MP provides a validation endpoint that returns messages describing problems. Send the same body to this URL:
POST https://www.google-analytics.com/debug/mp/collect?measurement_id=G-XXXXXXXXXX&api_secret=API_SECRET
Content-Type: application/json
{
"client_id": "CLIENT_ID",
"events": [
{
"name": "sign_up",
"params": {
"method": "email"
}
}
]
}An empty validationMessages array in the response means the request is well formed. Events sent to the validation endpoint are not recorded in your reports.
DebugView, covered in an earlier chapter, can show MP events only if you include debug_mode in the event parameters. Set "debug_mode": 1 in params while testing, and remove it before release.
Limits and gotchas
- A request can hold up to 25 events, and each event can have up to 25 parameters. Check the current Google documentation for the exact limits, because they change.
- Event names, parameter names, and reserved names follow the same rules as in the browser.
- MP events do not populate automatic dimensions such as device category, browser, or geography from the visitor. Location and device data are inferred from the server request unless you supply them. This can distort those reports.
- A custom parameter is still not usable in reports until you register it as a custom dimension or metric.
- MP events can be marked as key events like any others.
- Avoid duplicate counts. If both the browser and the server send
purchasefor one order, you will count the revenue twice. Pick one source for each event, or keep the sametransaction_idso GA4 can deduplicate purchases.
Choosing between client-side and server-side sending
Prefer client-side tagging when the browser sees the event, because it collects session, device, and traffic source data for you. Add MP for the cases the browser cannot see, and record those events in your tracking plan with a note about their source.
Exercise
A payment webhook reaches your server after the customer has left your site. You send a purchase event through the Measurement Protocol with a freshly generated random client_id. The purchase appears in GA4, but it is not connected to the campaign that brought the customer. What went wrong, and how do you fix it?
Show answer
The random clientid made GA4 treat the purchase as a new, unrelated user, so it had no session or traffic source history. Read the real client ID in the browser with gtag('get', measurementId, 'clientid', callback), store it with the order, and send that same clientid (and, if available, the sessionid) in the Measurement Protocol request. Test the body at the /debug/mp/collect endpoint first.
Exercise
Your server sends a request to /mp/collect and gets a 204 response, but the event never appears in DebugView or reports. Give two likely causes and one way to find the problem.
Show answer
Likely causes include a malformed payload (for example an invalid event name or parameter), a wrong measurement ID or API secret, or a missing debug_mode parameter, which DebugView needs to display the event. The /mp/collect endpoint returns 204 even for invalid payloads. Send the same body to /debug/mp/collect and read the validationMessages in the response.