Analytics Module

In this document, you'll learn about the Analytics Module and its providers.

Note: The Analytics Module is available starting Medusa v2.8.3.

What is the Analytics Module?#

The Analytics Module exposes functionalities to track and analyze user interactions and system events with third-party services. For example, you can track cart updates or completed orders.

In your Medusa application, you can use the Analytics Module to send data to third-party analytics services like PostHog or Segment, enabling you to gain insights into user behavior and system performance.

Diagram showcasing the flow of tracking an event like order.placed


How to Use the Analytics Module?#

Configure Analytics Module Provider#

To use the Analytics Module, you need to configure it along with an Analytics Module Provider.

An Analytics Module Provider implements the underlying logic of sending analytics data. It integrates with a third-party analytics service to send the data collected through the Analytics Module.

Medusa provides two Analytics Module Providers: Local and PostHog module providers.

You can also create a custom Analytics Module Provider that integrates with a third-party service, like Segment.

Local
For Development
PostHog
For Production

To configure the Analytics Module and its provider, add it to the list of modules in your medusa-config.ts file. For example:

medusa-config.ts
1module.exports = defineConfig({2  // ...3  modules: [4    {5      resolve: "@medusajs/medusa/analytics",6      options: {7        providers: [8          {9            resolve: "@medusajs/medusa/analytics-local",10            id: "local",11          },12        ],13      },14    },15  ],16})

Refer to the documentation of each provider for specific configuration options.

Track Events#

To track an event, you can use the Analytics Module as part of the workflows you build for your custom features. A workflow is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.

In a step of your workflow, you can resolve the Analytics Module's service and use its methods to track events or identify users.

For example, create a workflow at src/workflows/track-order-placed.ts with the following content:

src/workflows/track-order-created.ts
1import { createWorkflow } from "@medusajs/framework/workflows-sdk"2import { createStep } from "@medusajs/framework/workflows-sdk"3import { Modules } from "@medusajs/framework/utils"4import { OrderDTO } from "@medusajs/framework/types"5
6type StepInput = {7  order: OrderDTO8}9
10const trackOrderCreatedStep = createStep(11  "track-order-created-step",12  async ({ order }: StepInput, { container }) => {13    const analyticsModuleService = container.resolve(Modules.ANALYTICS)14
15    await analyticsModuleService.track({16      event: "order_created",17      userId: order.customer_id,18      properties: {19        order_id: order.id,20        total: order.total,21        items: order.items.map((item) => ({22          variant_id: item.variant_id,23          product_id: item.product_id,24          quantity: item.quantity,25        })),26        customer_id: order.customer_id,27      },28    })29  }30)31
32type WorkflowInput = {33  order_id: string34}35
36export const trackOrderCreatedWorkflow = createWorkflow(37  "track-order-created-workflow",38  ({ order_id }: WorkflowInput) => {39    const { data: orders } = useQueryGraphStep({40      entity: "order",41      fields: [42        "*",43        "customer.*",44        "items.*"45      ],46      filters: {47        id: order_id,48      },49    })50    trackOrderCreatedStep({51      order: orders[0],52    })53  }54)

This workflow retrieves the order details using the useQueryGraphStep and then tracks the order creation event using the trackOrderCreatedStep.

In the step, you resolve the service of the Analytics Module from the Medusa container and use its track method to track the event. This method will use the underlying provider configured in medusa-config.ts to track the event.

Execute Analytics Workflow#

After that, you can execute this workflow in a subscriber that runs when a product is created.

create a subscriber at src/subscribers/order-placed.ts with the following content:

src/subscribers/order-placed.ts
1import type {2  SubscriberArgs,3  SubscriberConfig,4} from "@medusajs/framework"5import { trackOrderCreatedWorkflow } from "../workflows/track-order-created"6
7export default async function orderPlacedHandler({8  event: { data },9  container,10}: SubscriberArgs<{ id: string }>) {11  await trackOrderCreatedWorkflow(container).run({12    input: {13      order_id: data.id,14    },15  })16}17
18export const config: SubscriberConfig = {19  event: "order.placed",20}

This subscriber listens to the order.placed event and executes the trackOrderCreatedWorkflow workflow, passing the order ID as input.

You'll now track the order creation event whenever an order is placed in your Medusa application. You can test this out by placing an order and checking the provider you integrated with (for example, PostHog) for the tracked event.

Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break