Send event to Google Analytics 4
This hook enables you to send event data from your Shopify store directly to Google Analytics 4 using the Measurement Protocol. Use it to track purchases and other customer interactions without additional client-side code.
Prerequisites
- Google Analytics 4 API Secret
- Google Analytics 4 Measurement ID
- A Shopify store with Cloudhooks installed
Configuration
1) Set up trigger
Create a new hook in the Cloudhooks dashboard with "An order is created" as your trigger event.
2) Configure authentication
Update these variables in the hook code with your Google Analytics credentials:
const API_SECRET = '[Your GA4 API secret]';
const MEASUREMENT_ID = '[Your GA4 measurement id]';
3) Implement the hook
Copy and paste this code into your hook editor:
You can send recommended events and custom events to Google Analytics via the Measurement Protocol .
The following example sends a purchase event to Google Analytics (the hook expects an order payload):
const API_SECRET = '[Your GA4 API secret]';
const MEASUREMENT_ID = '[Your GA4 measurement id]';
module.exports = async function(payload, actions, context) {
const gaUrl = 'https://www.google-analytics.com/mp/collect' +
`?api_secret=${API_SECRET}` +
`&measurement_id=${MEASUREMENT_ID}`;
const gaData = {
client_id: 'Cloudhooks',
user_id: payload.customer.id.toString(),
events: [
{
name: 'purchase',
params: {
transaction_id: payload.order_number.toString(),
currency: payload.currency,
value: parseFloat(payload.current_total_price),
items: payload.line_items.map( (item) => {
return {
item_name: item.name,
quantity: item.quantity,
price: parseFloat(item.price)
};
})
}
}
]
};
try {
// Google Analytics always returns HTTP 200
// No need to check return value
await actions.http.post(
gaUrl, gaData,
{headers: {'Content-Type': 'application/json'}}
);
} catch (err) {
console.log('GA error: ' + err);
}
};Testing
Test your hook using Cloudhooks' test payload feature before activating it in production. Use a sample order payload from your store.
Notes
- It typically takes 24-48 hours for events to appear in Google Analytics reports.
- This example demonstrates a purchase event, but you can modify it to send any recommended events or custom events.
Additional Resources
- Google Analytics 4 Measurement Protocol documentation
- More Cloudhooks examples on our GitHub Gist page
- For detailed setup instructions, visit our complete integration guide