Track ecommerce events related to orders and cart
A Google Analytics 4 plugin for Medusa that automatically tracks ecommerce events on your backend using Measurement Protocol. This plugin implements server-side tracking for key ecommerce events in your Medusa store.
The plugin automatically tracks the following GA4 ecommerce events:
yarn add @variablevic/google-analytics-medusaAdd the plugin to your :
1import { defineConfig } from "@medusajs/utils";2
3// ... other imports and environment variables4
5export default defineConfig({6 // ... other configurations7 plugins: [8 // ... other plugins9 {10 resolve: "@variablevic/google-analytics-medusa",11 options: {12 measurementId: "G-XXXXXXXX", // Your GA4 Measurement ID13 apiSecret: "XXXXXXXXXX", // Your GA4 API Secret14 debug: false, // Optional, enables debug mode - no events will be sent to your property when debug is active!15 },16 },17 ],18});This plugin handles server-side events, but some GA4 ecommerce events need to be implemented on the client side due to their nature:
Additionally, to properly associate events with users, you need to set the GA client ID as metadata when creating a cart. Here's how to do it in the Next.js Starter:
1export const getGaClientId = async (): Promise<string | null> => {2 const cookies = await nextCookies();3 const gaClientIdCookie = cookies.get("_ga")?.value;4
5 const gaClientId = (gaClientIdCookie as string)6 .split(".")7 .slice(-2)8 .join(".");9
10 return gaClientId;11};1const gaClientId = await getGaClientId();2
3const body = {4 region_id: region.id,5} as Record<string, any>;6
7if (gaClientId) {8 body.metadata = {9 ga_client_id: gaClientId,10 };11}12
13const cartResp = await sdk.store.cart.create(body, {}, headers);The plugin automatically formats cart and order data according to GA4's ecommerce event specifications. Each event includes:
For local development and testing:
npx medusa plugin:developContributions are welcome! Please read our contributing guidelines before submitting a pull request.
MIT