A Medusa plugin for sending ecommerce spec events to Google Analytics using the Measurement Protocol.
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-medusa
Add the plugin to your :
import { defineConfig } from "@medusajs/utils";// ... other imports and environment variablesexport default defineConfig({// ... other configurationsplugins: [// ... other plugins{resolve: "@variablevic/google-analytics-medusa",options: {measurementId: "G-XXXXXXXX", // Your GA4 Measurement IDapiSecret: "XXXXXXXXXX", // Your GA4 API Secretdebug: false, // Optional, enables debug mode - no events will be sent to your property when debug is active!},},],});
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:
export const getGaClientId = async (): Promise<string | null> => {const cookies = await nextCookies();const gaClientIdCookie = cookies.get("_ga")?.value;const gaClientId = (gaClientIdCookie as string).split(".").slice(-2).join(".");return gaClientId;};
const gaClientId = await getGaClientId();const body = {region_id: region.id,} as Record<string, any>;if (gaClientId) {body.metadata = {ga_client_id: gaClientId,};}const 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:develop
Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
MIT