docs: document analytics module (#12563)

This commit is contained in:
Shahed Nasser authored and GitHub committed 2025-05-22 15:05:04 +03:00
1 parent 5ad3615830
commit 04e0b43ed8
41 files changed
+76699 -69414

No files matched your search

@@ -20,6 +20,7 @@ There are different Infrastructure Module types including:
![Diagram illustrating how the modules connect to third-party services](https://res.cloudinary.com/dza7lstvk/image/upload/v1727095814/Medusa%20Book/architectural-modules_bj9bb9.jpg)
- Analytics Module: Integrates a third-party service to track and analyze user interactions and system events.
- Cache Module: Defines the caching mechanism or logic to cache computational results.
- Event Module: Integrates a pub/sub service to handle subscribing to and emitting events.
- Workflow Engine Module: Integrates a service to store and track workflow executions and steps.
@@ -71,6 +71,7 @@ You can replace any of the third-party services mentioned above to build your pr
[Infrastructure Modules](!resources!/infrastructure-modules) integrate third-party services and systems that customize Medusa's infrastructure. Medusa has the following Infrastructure Modules:
- [Analytics Module](!resources!/infrastructure-modules/analytics): Tracks and analyzes user interactions and system events with third-party analytic providers. You can integrate [PostHog](!resources!/infrastructure-modules/analytics/posthog) as the analytics provider.
- [Cache Module](!resources!/infrastructure-modules/cache): Caches data that require heavy computation. You can integrate a custom module to handle the caching with services like Memcached, or use the existing [Redis Cache Module](!resources!/infrastructure-modules/cache/redis).
- [Event Module](!resources!/infrastructure-modules/event): A pub/sub system that allows you to subscribe to events and trigger them. You can integrate [Redis](!resources!/infrastructure-modules/event/redis) as the pub/sub system.
- [File Module](!resources!/infrastructure-modules/file): Manages file uploads and storage, such as upload of product images. You can integrate [AWS S3](!resources!/infrastructure-modules/file/s3) for file storage.
+2 -2
View File
@@ -89,8 +89,8 @@ export const generatedEditDates = {
"app/learn/customization/integrate-systems/schedule-task/page.mdx": "2025-01-28T16:42:42.071Z",
"app/learn/customization/integrate-systems/service/page.mdx": "2024-12-09T11:02:39.594Z",
"app/learn/customization/next-steps/page.mdx": "2025-04-17T08:50:17.036Z",
"app/learn/fundamentals/modules/infrastructure-modules/page.mdx": "2025-05-05T07:54:33.931Z",
"app/learn/introduction/architecture/page.mdx": "2025-04-17T08:51:32.723Z",
"app/learn/fundamentals/modules/infrastructure-modules/page.mdx": "2025-05-21T14:31:51.644Z",
"app/learn/introduction/architecture/page.mdx": "2025-05-21T14:31:51.644Z",
"app/learn/fundamentals/data-models/infer-type/page.mdx": "2025-03-18T07:41:01.936Z",
"app/learn/fundamentals/custom-cli-scripts/seed-data/page.mdx": "2024-12-09T14:38:06.385Z",
"app/learn/fundamentals/environment-variables/page.mdx": "2025-03-11T08:55:03.343Z",
File diff suppressed because it is too large. Load diff
+9 -11
View File
@@ -69,6 +69,15 @@ async function main() {
/^(?!.*\/(workflows|js-sdk|extend|admin-widget-zones)\/).*$/,
],
},
{
dir: path.join(
process.cwd(),
"..",
"resources",
"app",
"infrastructure-modules"
),
},
{
dir: path.join(
process.cwd(),
@@ -192,17 +201,6 @@ async function main() {
},
},
},
{
dir: path.join(
process.cwd(),
"..",
"resources",
"references",
"medusa_config",
"interfaces",
"medusa_config.ConfigModule"
),
},
{
dir: path.join(
process.cwd(),
@@ -0,0 +1,155 @@
import { Table, Prerequisites } from "docs-ui"
export const metadata = {
title: `Local Analytics Module Provider`,
}
# {metadata.title}
The Local Analytics Module Provider is a simple analytics provider for Medusa that logs analytics events to the console. It's useful for development and debugging purposes.
<Note>
The Analytics Module and its providers are available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
</Note>
---
## Register the Local Analytics Module
Add the module into the `provider` object of the Analytics Module:
<Note>
You can use only one Analytics Module Provider in your Medusa application.
</Note>
```ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
provider: {
resolve: "@medusajs/analytics-local",
id: "local",
},
},
},
],
})
```
---
## Test out the Module
To test the module out, you'll track in the console when an order is placed.
You'll first create a [workflow](!docs!/learn/fundamentals/workflows) that tracks the order completion event. Then, you can execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event.
For example, create a workflow at `src/workflows/track-order-placed.ts` with the following content:
export const workflowHighlights = [
["13", "resolve", "Resolve the Analytics Module's service"],
["15", "track", "Track the event in the installed Analytics Module Provider"]
]
```ts title="src/workflows/track-order-created.ts" highlights={workflowHighlights}
import { createWorkflow } from "@medusajs/framework/workflows-sdk"
import { createStep } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"
import { OrderDTO } from "@medusajs/framework/types"
type StepInput = {
order: OrderDTO
}
const trackOrderCreatedStep = createStep(
"track-order-created-step",
async ({ order }: StepInput, { container }) => {
const analyticsModuleService = container.resolve(Modules.ANALYTICS)
await analyticsModuleService.track({
event: "order_created",
userId: order.customer_id,
properties: {
order_id: order.id,
total: order.total,
items: order.items.map((item) => ({
variant_id: item.variant_id,
product_id: item.product_id,
quantity: item.quantity,
})),
customer_id: order.customer_id,
},
})
}
)
type WorkflowInput = {
order_id: string
}
export const trackOrderCreatedWorkflow = createWorkflow(
"track-order-created-workflow",
({ order_id }: WorkflowInput) => {
const { data: orders } = useQueryGraphStep({
entity: "order",
fields: [
"*",
"customer.*",
"items.*"
],
filters: {
id: order_id,
},
})
trackOrderCreatedStep({
order: orders[0],
})
}
)
```
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](!docs!/learn/fundamentals/medusa-container) and use its `track` method to track the event. This method will use the underlying provider configured (which is the Local Analytics Module Provider, in this case) to track the event.
Next, create a subscriber at `src/subscribers/order-placed.ts` with the following content:
```ts title="src/subscribers/order-placed.ts"
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
import { trackOrderCreatedWorkflow } from "../workflows/track-order-created"
export default async function orderPlacedHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
await trackOrderCreatedWorkflow(container).run({
input: {
order_id: data.id,
},
})
}
export const config: SubscriberConfig = {
event: "order.placed",
}
```
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 console for the tracked event.
---
## Additional Resources
- [How to Use the Analytics Module](/references/analytics/service)
@@ -0,0 +1,189 @@
import { CardList } from "docs-ui"
export const metadata = {
title: `Analytics Module`,
}
# {metadata.title}
In this document, you'll learn about the Analytics Module and its providers.
<Note>
The Analytics Module is available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
</Note>
## 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](https://res.cloudinary.com/dza7lstvk/image/upload/v1747832107/Medusa%20Resources/analytics-module-overview_egz7xg.jpg)
---
## 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](/references/analytics/provider) that integrates with a third-party service, like Segment.
<CardList
items={[
{
title: "Local",
href: "/infrastructure-modules/analytics/local",
badge: {
variant: "neutral",
children: "For Development"
}
},
{
title: "PostHog",
href: "/infrastructure-modules/analytics/posthog",
badge: {
variant: "green",
children: "For Production"
}
}
]}
className='mb-1'
/>
To configure the Analytics Module and its provider, add it to the list of modules in your `medusa-config.ts` file. For example:
```ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
providers: [
{
resolve: "@medusajs/medusa/analytics-local",
id: "local",
},
],
},
},
],
})
```
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](!docs!/learn/fundamentals/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:
export const workflowHighlights = [
["13", "resolve", "Resolve the Analytics Module's service"],
["15", "track", "Track the event in the installed Analytics Module Provider"]
]
```ts title="src/workflows/track-order-created.ts" highlights={workflowHighlights}
import { createWorkflow } from "@medusajs/framework/workflows-sdk"
import { createStep } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"
import { OrderDTO } from "@medusajs/framework/types"
type StepInput = {
order: OrderDTO
}
const trackOrderCreatedStep = createStep(
"track-order-created-step",
async ({ order }: StepInput, { container }) => {
const analyticsModuleService = container.resolve(Modules.ANALYTICS)
await analyticsModuleService.track({
event: "order_created",
userId: order.customer_id,
properties: {
order_id: order.id,
total: order.total,
items: order.items.map((item) => ({
variant_id: item.variant_id,
product_id: item.product_id,
quantity: item.quantity,
})),
customer_id: order.customer_id,
},
})
}
)
type WorkflowInput = {
order_id: string
}
export const trackOrderCreatedWorkflow = createWorkflow(
"track-order-created-workflow",
({ order_id }: WorkflowInput) => {
const { data: orders } = useQueryGraphStep({
entity: "order",
fields: [
"*",
"customer.*",
"items.*"
],
filters: {
id: order_id,
},
})
trackOrderCreatedStep({
order: orders[0],
})
}
)
```
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](!docs!/learn/fundamentals/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:
```ts title="src/subscribers/order-placed.ts"
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
import { trackOrderCreatedWorkflow } from "../workflows/track-order-created"
export default async function orderPlacedHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
await trackOrderCreatedWorkflow(container).run({
input: {
order_id: data.id,
},
})
}
export const config: SubscriberConfig = {
event: "order.placed",
}
```
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.
@@ -0,0 +1,227 @@
import { Table, Prerequisites } from "docs-ui"
export const metadata = {
title: `PostHog Analytics Module Provider`,
}
# {metadata.title}
The PostHog Analytics Module Provider allows you to integrate [PostHog](https://posthog.com/) with Medusa.
PostHog is an open-source product analytics platform that helps you track user interactions and analyze user behavior in your commerce application.
By integrating PostHog with Medusa, you can track events such as cart additions, order completions, and user sign-ups, enabling you to gain insights into user behavior and optimize your application accordingly.
<Note>
The Analytics Module and its providers are available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
</Note>
---
## Register the PostHog Analytics Module
<Prerequisites
items={[
{
text: "PostHog account",
link: "https://app.posthog.com/signup",
},
{
text: "PostHog API Key",
link: "https://posthog.com/docs/getting-started/api-key",
},
]}
/>
Add the module into the `provider` object of the Analytics Module:
<Note>
You can use only one provider in your Medusa application.
</Note>
```ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
provider: {
resolve: "@medusajs/analytics-posthog",
id: "posthog",
options: {
posthogEventsKey: process.env.POSTHOG_EVENTS_API_KEY,
posthogHost: process.env.POSTHOG_HOST,
},
},
},
},
],
})
```
### Environment Variables
Make sure to add the following environment variables:
```bash
POSTHOG_EVENTS_API_KEY=<YOUR_POSTHOG_EVENTS_API_KEY>
POSTHOG_HOST=<YOUR_POSTHOG_HOST>
```
### PostHog Analytics Module Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>
Option
</Table.HeaderCell>
<Table.HeaderCell>
Description
</Table.HeaderCell>
<Table.HeaderCell>
Default
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`eventsKey`
</Table.Cell>
<Table.Cell>
The PostHog API key for tracking events. This is required to authenticate your requests to the PostHog API.
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`posthogHost`
</Table.Cell>
<Table.Cell>
The PostHog API host URL.
</Table.Cell>
<Table.Cell>
`https://eu.i.posthog.com`
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
---
## Test out the Module
To test the module out, you'll track in PostHog when an order is placed.
You'll first create a [workflow](!docs!/learn/fundamentals/workflows) that tracks the order completion event. Then, you can execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event.
For example, create a workflow at `src/workflows/track-order-placed.ts` with the following content:
export const workflowHighlights = [
["13", "resolve", "Resolve the Analytics Module's service"],
["15", "track", "Track the event in the installed Analytics Module Provider"]
]
```ts title="src/workflows/track-order-created.ts" highlights={workflowHighlights}
import { createWorkflow } from "@medusajs/framework/workflows-sdk"
import { createStep } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"
import { OrderDTO } from "@medusajs/framework/types"
type StepInput = {
order: OrderDTO
}
const trackOrderCreatedStep = createStep(
"track-order-created-step",
async ({ order }: StepInput, { container }) => {
const analyticsModuleService = container.resolve(Modules.ANALYTICS)
await analyticsModuleService.track({
event: "order_created",
userId: order.customer_id,
properties: {
order_id: order.id,
total: order.total,
items: order.items.map((item) => ({
variant_id: item.variant_id,
product_id: item.product_id,
quantity: item.quantity,
})),
customer_id: order.customer_id,
},
})
}
)
type WorkflowInput = {
order_id: string
}
export const trackOrderCreatedWorkflow = createWorkflow(
"track-order-created-workflow",
({ order_id }: WorkflowInput) => {
const { data: orders } = useQueryGraphStep({
entity: "order",
fields: [
"*",
"customer.*",
"items.*"
],
filters: {
id: order_id,
},
})
trackOrderCreatedStep({
order: orders[0],
})
}
)
```
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](!docs!/learn/fundamentals/medusa-container) and use its `track` method to track the event. This method will use the underlying provider configured (which is the PostHog Analytics Module Provider, in this case) to track the event.
Next, create a subscriber at `src/subscribers/order-placed.ts` with the following content:
```ts title="src/subscribers/order-placed.ts"
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
import { trackOrderCreatedWorkflow } from "../workflows/track-order-created"
export default async function orderPlacedHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
await trackOrderCreatedWorkflow(container).run({
input: {
order_id: data.id,
},
})
}
export const config: SubscriberConfig = {
event: "order.placed",
}
```
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 your PostHog dashboard for the tracked event.
---
## Additional Resources
- [How to Use the Analytics Module](/references/analytics/service)
@@ -12,6 +12,41 @@ For example, you can use our [Redis Event Module](./event/redis/page.mdx) to han
This section of the documentation showcases Medusa's Infrastructure Modules, how they work, and how to use them in your Medusa application.
## Analytics Module
<Note>
The Analytics Module is available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
</Note>
The Analytics Module exposes functionalities to track and analyze user interactions and system events. For example, tracking cart updates or completed orders. Learn more in the [Analytics Module documentation](./analytics/page.mdx).
{/* The Analytics Module has module providers that implement the underlying logic of integrating third-party services for tracking analytics. The following Analytics Module Providers are provided by Medusa. You can also create a custom provider as explained in the [Create Analytics Module Provider guide](/references/analytics/provider). */}
<CardList
items={[
{
title: "Local",
href: "/infrastructure-modules/analytics/local",
badge: {
variant: "neutral",
children: "For Development"
}
},
{
title: "PostHog",
href: "/infrastructure-modules/analytics/posthog",
badge: {
variant: "green",
children: "For Production"
}
}
]}
/>
## Cache Module
A Cache Module is used to cache the results of computations such as price selection or various tax calculations. Learn more in [this documentation](./cache/page.mdx).
+23 -5
View File
@@ -16,6 +16,24 @@ This section holds guides to help technical teams add integrations to a Medusa a
</Note>
## Analytics
An Analytics Module Provider tracks events and user behavior in your Medusa application using a third-party service.
<CardList
items={[
{
href: "/infrastructure-modules/analytics/posthog",
title: "PostHog"
}
]}
className="mb-1"
/>
Learn how to integrate a custom third-party analytics provider in the [Create Analytics Module Provider](/references/analytics/provider) documentation.
---
## Auth
An Auth Module Provider authenticates users with their account on a third-party service.
@@ -34,7 +52,7 @@ An Auth Module Provider authenticates users with their account on a third-party
className="mb-1"
/>
Learn how to integrate a custom third-party authentication provider in [this guide](/references/auth/provider).
Learn how to integrate a custom third-party authentication provider in the [Create Auth Module Provider](/references/auth/provider) documentation.
---
@@ -106,7 +124,7 @@ A File Module Provider uploads and manages assets, such as product images, on a
className="mb-1"
/>
Learn how to integrate a custom third-party file or storage provider in [this guide](/references/file-provider-module).
Learn how to integrate a custom third-party file or storage provider in the [Create File Module Provider](/references/file-provider-module) documentation.
---
@@ -128,7 +146,7 @@ A Fulfillment Module Provider provides fulfillment options during checkout, calc
className="mb-1"
/>
Learn how to create a Fulfillment Provider Module [this guide](/references/fulfillment/provider).
Learn how to integrate a third-party fulfillment provider in the [Create Fulfillment Module Provider](/references/fulfillment/provider) documentation.
---
@@ -154,7 +172,7 @@ A Notification Module Provider sends messages to users and customers in your Med
className="mb-1"
/>
Learn how to create a notification provider in [this guide](/references/notification-provider-module).
Learn how to integrate a third-party notification provider in the [Create Notification Module Provider](/references/notification-provider-module) documentation.
---
@@ -172,7 +190,7 @@ A Payment Module Provider processes payments made in your Medusa store using a t
className="mb-1"
/>
Learn how to create a payment provider in [this guide](/references/payment/provider).
Learn how to integrate a third-party payment provider in the [Create Payment Module Provider](/references/payment/provider) documentation.
---
+22 -4
View File
@@ -104,7 +104,7 @@ export const generatedEditDates = {
"app/deployment/medusa-application/railway/page.mdx": "2025-04-17T08:28:58.981Z",
"app/deployment/storefront/vercel/page.mdx": "2025-05-20T07:51:40.712Z",
"app/deployment/page.mdx": "2025-05-20T07:51:40.711Z",
"app/integrations/page.mdx": "2025-04-17T08:29:01.365Z",
"app/integrations/page.mdx": "2025-05-22T07:07:05.676Z",
"app/medusa-cli/page.mdx": "2024-08-28T11:25:32.382Z",
"app/medusa-container-resources/page.mdx": "2025-04-17T08:48:10.255Z",
"app/medusa-workflows-reference/page.mdx": "2025-01-20T08:21:29.962Z",
@@ -194,7 +194,7 @@ export const generatedEditDates = {
"app/commerce-modules/auth/auth-identity-and-actor-types/page.mdx": "2025-01-07T09:02:27.235Z",
"app/commerce-modules/api-key/page.mdx": "2025-04-17T08:48:16.605Z",
"app/commerce-modules/auth/create-actor-type/page.mdx": "2025-05-20T07:51:40.707Z",
"app/infrastructure-modules/page.mdx": "2025-04-17T08:29:00.388Z",
"app/infrastructure-modules/page.mdx": "2025-05-21T13:01:59.821Z",
"app/infrastructure-modules/workflow-engine/redis/page.mdx": "2024-11-19T16:37:47.262Z",
"app/infrastructure-modules/notification/sendgrid/page.mdx": "2025-05-20T07:51:40.715Z",
"app/commerce-modules/api-key/concepts/page.mdx": "2024-10-07T13:59:37.529Z",
@@ -5473,7 +5473,7 @@ export const generatedEditDates = {
"references/types/interfaces/types.ProductCategoryTransformOptions/page.mdx": "2024-12-09T13:21:35.493Z",
"references/types/interfaces/types.ReceiveReturnItem/page.mdx": "2024-12-09T13:21:35.857Z",
"references/types/interfaces/types.RefundReason/page.mdx": "2024-12-09T13:21:34.909Z",
"references/types/interfaces/types.RemoteJoinerOptions/page.mdx": "2025-02-11T11:36:50.670Z",
"references/types/interfaces/types.RemoteJoinerOptions/page.mdx": "2025-05-21T14:08:16.219Z",
"references/types/interfaces/types.RemoteJoinerQuery/page.mdx": "2024-12-09T13:21:35.197Z",
"references/types/interfaces/types.StoreCreateReturnItem/page.mdx": "2024-12-09T13:21:35.009Z",
"references/types/interfaces/types.StoreCreateReturnShipping/page.mdx": "2024-12-09T13:21:35.013Z",
@@ -6484,5 +6484,23 @@ export const generatedEditDates = {
"references/types/interfaces/types.WebhookActionData/page.mdx": "2025-05-20T07:51:41.086Z",
"app/commerce-modules/tax/tax-provider/page.mdx": "2025-05-20T07:51:40.711Z",
"app/recipes/bundled-products/examples/standard/page.mdx": "2025-05-20T07:51:40.718Z",
"app/recipes/bundled-products/page.mdx": "2025-05-20T07:51:40.718Z"
"app/recipes/bundled-products/page.mdx": "2025-05-20T07:51:40.718Z",
"app/infrastructure-modules/analytics/local/page.mdx": "2025-05-21T14:09:53.772Z",
"app/infrastructure-modules/analytics/page.mdx": "2025-05-21T13:34:40.515Z",
"app/infrastructure-modules/analytics/posthog/page.mdx": "2025-05-21T14:09:59.162Z",
"references/analytics/interfaces/analytics.IAnalyticsModuleService/page.mdx": "2025-05-21T14:21:59.325Z",
"references/analytics_provider/classes/analytics_provider.AbstractAnalyticsProviderService/page.mdx": "2025-05-21T14:22:04.267Z",
"references/modules/analytics/page.mdx": "2025-05-21T14:21:59.323Z",
"references/modules/analytics_provider/page.mdx": "2025-05-21T14:22:04.264Z",
"references/types/interfaces/types.IAnalyticsModuleService/page.mdx": "2025-05-21T14:22:00.510Z",
"references/types/interfaces/types.IAnalyticsProvider/page.mdx": "2025-05-21T14:22:00.507Z",
"references/types/interfaces/types.IdentifyActorDTO/page.mdx": "2025-05-21T14:22:00.502Z",
"references/types/interfaces/types.IdentifyGroupDTO/page.mdx": "2025-05-21T14:22:00.503Z",
"references/types/interfaces/types.LocalAnalyticsServiceOptions/page.mdx": "2025-05-21T14:22:00.508Z",
"references/types/interfaces/types.PosthogAnalyticsServiceOptions/page.mdx": "2025-05-21T14:22:00.508Z",
"references/types/interfaces/types.TrackAnalyticsEventDTO/page.mdx": "2025-05-21T14:22:00.501Z",
"references/types/types.AnalyticsTypes/page.mdx": "2025-05-21T14:22:00.501Z",
"references/types/types/types.IdentifyAnalyticsEventDTO/page.mdx": "2025-05-21T14:22:00.503Z",
"references/types/types/types.ProviderIdentifyAnalyticsEventDTO/page.mdx": "2025-05-21T14:22:00.504Z",
"references/types/types/types.ProviderTrackAnalyticsEventDTO/page.mdx": "2025-05-21T14:22:00.504Z"
}
@@ -755,6 +755,18 @@ export const filesMap = [
"filePath": "/www/apps/resources/app/how-to-tutorials/tutorials/saved-payment-methods/page.mdx",
"pathname": "/how-to-tutorials/tutorials/saved-payment-methods"
},
{
"filePath": "/www/apps/resources/app/infrastructure-modules/analytics/local/page.mdx",
"pathname": "/infrastructure-modules/analytics/local"
},
{
"filePath": "/www/apps/resources/app/infrastructure-modules/analytics/page.mdx",
"pathname": "/infrastructure-modules/analytics"
},
{
"filePath": "/www/apps/resources/app/infrastructure-modules/analytics/posthog/page.mdx",
"pathname": "/infrastructure-modules/analytics/posthog"
},
{
"filePath": "/www/apps/resources/app/infrastructure-modules/cache/create/page.mdx",
"pathname": "/infrastructure-modules/cache/create"
@@ -1399,6 +1411,14 @@ export const filesMap = [
"filePath": "/www/apps/resources/app/troubleshooting/workflow-errors/when-then/page.mdx",
"pathname": "/troubleshooting/workflow-errors/when-then"
},
{
"filePath": "/www/apps/resources/references/analytics/interfaces/analytics.IAnalyticsModuleService/page.mdx",
"pathname": "/references/analytics/interfaces/analytics.IAnalyticsModuleService"
},
{
"filePath": "/www/apps/resources/references/analytics_provider/classes/analytics_provider.AbstractAnalyticsProviderService/page.mdx",
"pathname": "/references/analytics_provider/classes/analytics_provider.AbstractAnalyticsProviderService"
},
{
"filePath": "/www/apps/resources/references/api_key/IApiKeyModuleService/methods/api_key.IApiKeyModuleService.authenticate/page.mdx",
"pathname": "/references/api_key/IApiKeyModuleService/methods/api_key.IApiKeyModuleService.authenticate"
@@ -13599,6 +13619,14 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/module_events/module_events.User/page.mdx",
"pathname": "/references/module_events/module_events.User"
},
{
"filePath": "/www/apps/resources/references/modules/analytics/page.mdx",
"pathname": "/references/modules/analytics"
},
{
"filePath": "/www/apps/resources/references/modules/analytics_provider/page.mdx",
"pathname": "/references/modules/analytics_provider"
},
{
"filePath": "/www/apps/resources/references/modules/api_key/page.mdx",
"pathname": "/references/modules/api_key"
@@ -23347,6 +23375,14 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/interfaces/types.GetUploadedFileType/page.mdx",
"pathname": "/references/types/interfaces/types.GetUploadedFileType"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.IAnalyticsModuleService/page.mdx",
"pathname": "/references/types/interfaces/types.IAnalyticsModuleService"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.IAnalyticsProvider/page.mdx",
"pathname": "/references/types/interfaces/types.IAnalyticsProvider"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.IAuthProvider/page.mdx",
"pathname": "/references/types/interfaces/types.IAuthProvider"
@@ -23387,6 +23423,14 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/interfaces/types.ITaxProvider/page.mdx",
"pathname": "/references/types/interfaces/types.ITaxProvider"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.IdentifyActorDTO/page.mdx",
"pathname": "/references/types/interfaces/types.IdentifyActorDTO"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.IdentifyGroupDTO/page.mdx",
"pathname": "/references/types/interfaces/types.IdentifyGroupDTO"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.InitiatePaymentInput/page.mdx",
"pathname": "/references/types/interfaces/types.InitiatePaymentInput"
@@ -23427,6 +23471,10 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/interfaces/types.ListShippingOptionsForCartWorkflowInputDTO/page.mdx",
"pathname": "/references/types/interfaces/types.ListShippingOptionsForCartWorkflowInputDTO"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.LocalAnalyticsServiceOptions/page.mdx",
"pathname": "/references/types/interfaces/types.LocalAnalyticsServiceOptions"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.MessageAggregatorFormat/page.mdx",
"pathname": "/references/types/interfaces/types.MessageAggregatorFormat"
@@ -23447,6 +23495,10 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/interfaces/types.PaymentProviderOutput/page.mdx",
"pathname": "/references/types/interfaces/types.PaymentProviderOutput"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.PosthogAnalyticsServiceOptions/page.mdx",
"pathname": "/references/types/interfaces/types.PosthogAnalyticsServiceOptions"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.PricedShippingOptionDTO/page.mdx",
"pathname": "/references/types/interfaces/types.PricedShippingOptionDTO"
@@ -23511,6 +23563,10 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/interfaces/types.StoreCreateReturnShipping/page.mdx",
"pathname": "/references/types/interfaces/types.StoreCreateReturnShipping"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.TrackAnalyticsEventDTO/page.mdx",
"pathname": "/references/types/interfaces/types.TrackAnalyticsEventDTO"
},
{
"filePath": "/www/apps/resources/references/types/interfaces/types.UpdateAccountHolderInput/page.mdx",
"pathname": "/references/types/interfaces/types.UpdateAccountHolderInput"
@@ -23731,6 +23787,10 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/types/types.FulfillmentStatus/page.mdx",
"pathname": "/references/types/types/types.FulfillmentStatus"
},
{
"filePath": "/www/apps/resources/references/types/types/types.IdentifyAnalyticsEventDTO/page.mdx",
"pathname": "/references/types/types/types.IdentifyAnalyticsEventDTO"
},
{
"filePath": "/www/apps/resources/references/types/types/types.IncludesSeparator/page.mdx",
"pathname": "/references/types/types/types.IncludesSeparator"
@@ -23947,6 +24007,14 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/types/types.ProductVariant/page.mdx",
"pathname": "/references/types/types/types.ProductVariant"
},
{
"filePath": "/www/apps/resources/references/types/types/types.ProviderIdentifyAnalyticsEventDTO/page.mdx",
"pathname": "/references/types/types/types.ProviderIdentifyAnalyticsEventDTO"
},
{
"filePath": "/www/apps/resources/references/types/types/types.ProviderTrackAnalyticsEventDTO/page.mdx",
"pathname": "/references/types/types/types.ProviderTrackAnalyticsEventDTO"
},
{
"filePath": "/www/apps/resources/references/types/types/types.Query/page.mdx",
"pathname": "/references/types/types/types.Query"
@@ -24039,6 +24107,10 @@ export const filesMap = [
"filePath": "/www/apps/resources/references/types/types.AdminTypes/page.mdx",
"pathname": "/references/types/types.AdminTypes"
},
{
"filePath": "/www/apps/resources/references/types/types.AnalyticsTypes/page.mdx",
"pathname": "/references/types/types.AnalyticsTypes"
},
{
"filePath": "/www/apps/resources/references/types/types.CacheTypes/page.mdx",
"pathname": "/references/types/types.CacheTypes"
@@ -13,6 +13,71 @@ const generatedgeneratedInfrastructureModulesSidebarSidebar = {
{
"type": "separator"
},
{
"loaded": true,
"isPathHref": true,
"type": "category",
"title": "Analytics Module",
"initialOpen": true,
"children": [
{
"loaded": true,
"isPathHref": true,
"type": "link",
"path": "/infrastructure-modules/analytics",
"title": "Overview",
"children": []
},
{
"loaded": true,
"isPathHref": true,
"type": "sub-category",
"title": "Modules",
"children": [
{
"loaded": true,
"isPathHref": true,
"type": "link",
"path": "/infrastructure-modules/analytics/local",
"title": "Local",
"children": []
},
{
"loaded": true,
"isPathHref": true,
"type": "link",
"path": "/infrastructure-modules/analytics/posthog",
"title": "PostHog",
"children": []
}
]
},
{
"loaded": true,
"isPathHref": true,
"type": "sub-category",
"title": "Guides",
"children": [
{
"loaded": true,
"isPathHref": true,
"type": "link",
"path": "/references/analytics/provider",
"title": "Create Analytics Module Provider",
"children": []
},
{
"loaded": true,
"isPathHref": true,
"type": "link",
"path": "/references/analytics/service",
"title": "Use Analytics Module",
"children": []
}
]
}
]
},
{
"loaded": true,
"isPathHref": true,
@@ -1,4 +1,14 @@
export const slugChanges = [
{
"origSlug": "/references/analytics/interfaces/analytics.IAnalyticsModuleService",
"newSlug": "/references/analytics/service",
"filePath": "/www/apps/resources/references/analytics/interfaces/analytics.IAnalyticsModuleService/page.mdx"
},
{
"origSlug": "/references/analytics_provider/classes/analytics_provider.AbstractAnalyticsProviderService",
"newSlug": "/references/analytics/provider",
"filePath": "/www/apps/resources/references/analytics_provider/classes/analytics_provider.AbstractAnalyticsProviderService/page.mdx"
},
{
"origSlug": "/references/api_key/IApiKeyModuleService/methods/api_key.IApiKeyModuleService.authenticate",
"newSlug": "/references/api-key/authenticate",
@@ -0,0 +1,147 @@
---
slug: /references/analytics/service
tags:
- analytics
- server
- how to
sidebar_label: Use Analytics Module
---
import { TypeList } from "docs-ui"
# How to Use Analytics Module
In this document, you’ll learn about the different methods in the Analytics Module's service and how to use them.
:::note
The Analytics Module is available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
:::
---
### Configure Analytics Module Provider
To use the Analytics Module, you need to configure it along with an Analytics Module Provider.
Medusa provides two Analytics Module Providers: [Local](/infrastructure-modules/analytics/local) and [PostHog](/infrastructure-modules/analytics/posthog) module providers.
To configure the Analytics Module and its provider, add it to the list of modules in your `medusa-config.ts` file. For example:
```ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
providers: [
{
resolve: "@medusajs/medusa/analytics-local",
id: "local",
},
],
},
},
],
})
```
Refer to the documentation of each provider for specific configuration options.
---
## Resolve Analytics Module's Service
In your workflow's step, you can resolve the Analytics Module's service from the Medusa container:
```ts
import { Modules } from "@medusajs/framework/utils"
import { createStep } from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
async ({}, { container }) => {
const analyticsModuleService = container.resolve(
Modules.Analytics
)
// TODO use analyticsModuleService
}
)
```
You can then use the Analytics Module's service's methods in the step, which would use the underlying provider's logic. The rest of this guide details these methods.
---
## getProvider
This method returns the service of the configured Analytics Module Provider in `medusa-config.ts`. This is useful
if you want to execute custom methods defined in the provider's service or you need direct access to it.
### Example
```ts
const postHogProviderService = analyticsModuleService.getProvider()
// TODO: perform custom actions with the provider
```
### Returns
<TypeList types={[{"name":"track","type":"(`data`: [TrackAnalyticsEventDTO](../../../types/interfaces/types.TrackAnalyticsEventDTO/page.mdx)) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"identify","type":"(`data`: [IdentifyAnalyticsEventDTO](../../../types/types/types.IdentifyAnalyticsEventDTO/page.mdx)) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"shutdown","type":"() => Promise&#60;void&#62;","description":"","optional":true,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="getProvider"/>
___
## identify
This method identifies an actor or group in the analytics provider. The Analytics Module
will use the `identify` method of the underlying provider configured in `medusa-config.ts` to identify the actor or group.
### Example
```ts
await analyticsModuleService.identify({
actor_id: "123",
properties: {
name: "John Doe"
}
})
```
### Parameters
<TypeList types={[{"name":"data","type":"[IdentifyAnalyticsEventDTO](../../../types/types/types.IdentifyAnalyticsEventDTO/page.mdx)","description":"The details of the actor or group.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the actor. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the actor or group is identified successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
___
## track
This method tracks an event in the analytics provider. The Analytics Module
will use the `track` method of the underlying provider configured in `medusa-config.ts` to track the event.
### Example
```ts
await analyticsModuleService.track({
event: "order_placed",
properties: {
order_id: "order_123",
customer_id: "customer_456",
total: 100,
}
})
```
### Parameters
<TypeList types={[{"name":"data","type":"[TrackAnalyticsEventDTO](../../../types/interfaces/types.TrackAnalyticsEventDTO/page.mdx)","description":"The event's details.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"event","type":"`string`","description":"The event name","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the event. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the event is tracked successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
@@ -0,0 +1,365 @@
---
slug: /references/analytics/provider
keywords:
- analytics
- provider
- integration
---
import { TypeList } from "docs-ui"
# How to Create an Analytics Module Provider
In this document, you’ll learn how to create an Analytics Module Provider and the methods you must implement in its main service.
---
## Implementation Example
As you implement your Analytics Module Provider, it can be useful to refer to an existing provider and how it's implemeted.
If you need to refer to an existing implementation as an example, check the [PostHog Analytics Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/analytics-posthog).
---
## Create Module Provider Directory
Start by creating a new directory for your module provider.
If you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-analytics`.
If you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-analytics`.
<Note>
The rest of this guide always uses the `src/modules/my-analytics` directory as an example.
</Note>
---
## 2. Create the Analytics Module Provider's Service
Create the file `src/modules/my-analytics/service.ts` that holds the implementation of the module provider's main service. It must extend the `AbstractAnalyticsProviderService` class imported from `@medusajs/framework/utils`:
```ts title="src/modules/my-analytics/service.ts"
import { AbstractAnalyticsProviderService } from "@medusajs/framework/utils"
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
// TODO implement methods
}
export default MyAnalyticsProviderService
```
### constructor
The constructor allows you to access resources from the module's container using the first parameter,
and the module's options using the second parameter.
If you're creating a client or establishing a connection with a third-party service, do it in the constructor.
#### Example
```ts
import { Logger } from "@medusajs/framework/types"
import { AbstractAnalyticsProviderService } from "@medusajs/framework/utils"
type InjectedDependencies = {
logger: Logger
}
type Options = {
apiKey: string
}
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
protected logger_: Logger
protected options_: Options
static identifier = "my-analytics"
// assuming you're initializing a client
protected client
constructor (
{ logger }: InjectedDependencies,
options: Options
) {
super()
this.logger_ = logger
this.options_ = options
// assuming you're initializing a client
this.client = new Client(options)
}
}
export default MyAnalyticsProviderService
```
### identifier
Each analytics provider has a unique ID used to identify it. The provider's ID
will be stored as `aly_{identifier}_{id}`, where `{id}` is the provider's `id`
property in the `medusa-config.ts`.
#### Example
```ts
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
static identifier = "my-analytics"
// ...
}
```
### identify
This method identifies an actor or group in the third-party analytics provider. The Analytics Module
will use this method in its `identify` method if your provider is configured in `medusa-config.ts`.
#### Example
```ts
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
// ...
async identify(
data: ProviderIdentifyAnalyticsEventDTO
): Promise<void> {
// identify actor or group in the analytics provider
// or using custom logic
// for example:
this.client.identify(data)
}
}
```
#### Parameters
<TypeList types={[{"name":"data","type":"[IdentifyAnalyticsEventDTO](../../../types/types/types.IdentifyAnalyticsEventDTO/page.mdx)","description":"The details of the actor or group.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the actor. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the actor or group is identified successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
### shutdown
<BadgesList badges={[
{
"variant": "neutral",
"children": "optional"
}
]} className="mb-1" />
This method is used to shutdown the analytics provider, and flush all data before shutting down.
This method is called by the Analytics Module when the Medusa application is shutting down.
#### Example
```ts
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
// ...
async shutdown(): Promise<void> {
// perform any cleanup or shutdown logic
// in the analytics provider or using custom logic
// for example:
await this.client.shutdown()
}
}
```
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the provider is shutdown successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="shutdown"/>
### track
This method tracks an event with the third-party analytics provider. The Analytics Module
will use this method in its `track` method if your provider is configured in `medusa-config.ts`.
You can send the event to the third-party provider based on its semantics.
#### Example
```ts
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
// ...
async track(
data: ProviderTrackAnalyticsEventDTO
): Promise<void> {
// track event to third-party provider
// or using custom logic
// for example:
this.client.track(data)
}
}
```
#### Parameters
<TypeList types={[{"name":"data","type":"[TrackAnalyticsEventDTO](../../../types/interfaces/types.TrackAnalyticsEventDTO/page.mdx)","description":"The event's details.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"event","type":"`string`","description":"The event name","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the event. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the event is tracked successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
---
## 3. Create Module Provider Definition File
Create the file `src/modules/my-analytics/index.ts` with the following content:
```ts title="src/modules/my-analytics/index.ts"
import MyAnalyticsProviderService from "./service"
import {
ModuleProvider,
Modules
} from "@medusajs/framework/utils"
export default ModuleProvider(Modules.ANALYTICS, {
services: [MyAnalyticsProviderService],
})
```
This exports the module provider's definition, indicating that the `MyAnalyticsProviderService` is the module provider's service.
---
## 4. Use Module Provider
To use your Analytics Module Provider, add it to the `providers` array of the Analytics Module in `medusa-config.ts`:
<Note>
The Analytics Module accepts one provider only.
</Note>
```ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
providers: [
{
// if module provider is in a plugin, use `plugin-name/providers/my-analytics`
resolve: "./src/modules/my-analytics",
id: "my-analytics",
options: {
// provider options...
},
},
],
},
},
]
})
```
---
## 5. Test it Out
To test the module out, you'll track in your third-party provider when an order is placed.
You'll first create a [workflow](!docs!/learn/fundamentals/workflows) that tracks the order completion event. Then, you can execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event.
For example, create a workflow at `src/workflows/track-order-placed.ts` with the following content:
```ts title="src/workflows/track-order-created.ts"
import { createWorkflow } from "@medusajs/framework/workflows-sdk"
import { createStep } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"
import { OrderDTO } from "@medusajs/framework/types"
type StepInput = {
order: OrderDTO
}
const trackOrderCreatedStep = createStep(
"track-order-created-step",
async ({ order }: StepInput, { container }) => {
const analyticsModuleService = container.resolve(Modules.ANALYTICS)
await analyticsModuleService.track({
event: "order_created",
userId: order.customer_id,
properties: {
order_id: order.id,
total: order.total,
items: order.items.map((item) => ({
variant_id: item.variant_id,
product_id: item.product_id,
quantity: item.quantity,
})),
customer_id: order.customer_id,
},
})
}
)
type WorkflowInput = {
order_id: string
}
export const trackOrderCreatedWorkflow = createWorkflow(
"track-order-created-workflow",
({ order_id }: WorkflowInput) => {
const { data: orders } = useQueryGraphStep({
entity: "order",
fields: [
"*",
"customer.*",
"items.*"
],
filters: {
id: order_id,
},
})
trackOrderCreatedStep({
order: orders[0],
})
}
)
```
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](!docs!/learn/fundamentals/medusa-container) and use its `track` method to track the event. This method will use the underlying provider configured (which is your provider, in this case) to track the event.
Next, create a subscriber at `src/subscribers/order-placed.ts` with the following content:
```ts title="src/subscribers/order-placed.ts"
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
import { trackOrderCreatedWorkflow } from "../workflows/track-order-created"
export default async function orderPlacedHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
await trackOrderCreatedWorkflow(container).run({
input: {
order_id: data.id,
},
})
}
export const config: SubscriberConfig = {
event: "order.placed",
}
```
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 in your third-party provider if the event was tracked successfully.
---
## Additional Resources
- [How to Use the Analytics Module](/references/analytics/service)
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# analytics
## Interfaces
- [IAnalyticsModuleService](../../analytics/interfaces/analytics.IAnalyticsModuleService/page.mdx)
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# analytics-provider
## Classes
- [AbstractAnalyticsProviderService](../../analytics_provider/classes/analytics_provider.AbstractAnalyticsProviderService/page.mdx)
@@ -0,0 +1,71 @@
import { TypeList } from "docs-ui"
# IAnalyticsModuleService
## Methods
### getProvider
This method returns the service of the configured Analytics Module Provider in `medusa-config.ts`. This is useful
if you want to execute custom methods defined in the provider's service or you need direct access to it.
#### Example
```ts
const postHogProviderService = analyticsModuleService.getProvider()
// TODO: perform custom actions with the provider
```
#### Returns
<TypeList types={[{"name":"track","type":"(`data`: [TrackAnalyticsEventDTO](../types.TrackAnalyticsEventDTO/page.mdx)) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"identify","type":"(`data`: [IdentifyAnalyticsEventDTO](../../types/types.IdentifyAnalyticsEventDTO/page.mdx)) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"shutdown","type":"() => Promise&#60;void&#62;","description":"","optional":true,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="getProvider"/>
### track
This method tracks an event in the analytics provider. The Analytics Module
will use the `track` method of the underlying provider configured in `medusa-config.ts` to track the event.
#### Example
```ts
await analyticsModuleService.track({
event: "order_placed",
properties: {
order_id: "order_123",
customer_id: "customer_456",
total: 100,
}
})
```
#### Parameters
<TypeList types={[{"name":"data","type":"[TrackAnalyticsEventDTO](../types.TrackAnalyticsEventDTO/page.mdx)","description":"The event's details.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"event","type":"`string`","description":"The event name","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the event. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the event is tracked successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
### identify
This method identifies an actor or group in the analytics provider. The Analytics Module
will use the `identify` method of the underlying provider configured in `medusa-config.ts` to identify the actor or group.
#### Example
```ts
await analyticsModuleService.identify({
actor_id: "123",
properties: {
name: "John Doe"
}
})
```
#### Parameters
<TypeList types={[{"name":"data","type":"[IdentifyAnalyticsEventDTO](../../types/types.IdentifyAnalyticsEventDTO/page.mdx)","description":"The details of the actor or group.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the actor. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the actor or group is identified successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
@@ -0,0 +1,60 @@
import { TypeList } from "docs-ui"
# IAnalyticsProvider
## Methods
### track
This method is used to track an event in the analytics provider
#### Parameters
<TypeList types={[{"name":"data","type":"[TrackAnalyticsEventDTO](../types.TrackAnalyticsEventDTO/page.mdx)","description":"The data for the event.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"event","type":"`string`","description":"The event name","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the event. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the event is tracked successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="track"/>
### identify
This method is used to identify an actor or group in the analytics provider
#### Parameters
<TypeList types={[{"name":"data","type":"[IdentifyAnalyticsEventDTO](../../types/types.IdentifyAnalyticsEventDTO/page.mdx)","description":"The data for the actor or group..","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the actor. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the event is tracked successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="identify"/>
### shutdown
<BadgesList badges={[
{
"variant": "neutral",
"children": "optional"
}
]} className="mb-1" />
This method is used to shutdown the analytics provider, and flush all data before shutting down.
This method is called by the Analytics Module when the Medusa application is shutting down.
#### Example
```ts
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
// ...
async shutdown(): Promise<void> {
// perform any cleanup or shutdown logic
// in the analytics provider or using custom logic
// for example:
await this.client.shutdown()
}
}
```
#### Returns
<TypeList types={[{"name":"Promise","type":"Promise&#60;void&#62;","optional":false,"defaultValue":"","description":"Resolves when the provider is shutdown successfully.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="shutdown"/>
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# IdentifyActorDTO
## Properties
<TypeList types={[{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the actor. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="IdentifyActorDTO"/>
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# IdentifyGroupDTO
## Properties
<TypeList types={[{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"actor_id","type":"`string`","description":"When identifying a group, the actor can potentially be passed as well as metadata.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the group. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="IdentifyGroupDTO"/>
@@ -0,0 +1,3 @@
import { TypeList } from "docs-ui"
# LocalAnalyticsServiceOptions
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# PosthogAnalyticsServiceOptions
## Properties
<TypeList types={[{"name":"posthogEventsKey","type":"`string`","description":"The key for the posthog events","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"posthogHost","type":"`string`","description":"The endpoint for the posthog server","optional":false,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="PosthogAnalyticsServiceOptions"/>
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# TrackAnalyticsEventDTO
## Properties
<TypeList types={[{"name":"event","type":"`string`","description":"The event name","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the event. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="TrackAnalyticsEventDTO"/>
@@ -0,0 +1,3 @@
import { TypeList } from "docs-ui"
# AnalyticsTypes
@@ -0,0 +1,7 @@
import { TypeList } from "docs-ui"
# IdentifyAnalyticsEventDTO
**IdentifyAnalyticsEventDTO**: [IdentifyActorDTO](../../interfaces/types.IdentifyActorDTO/page.mdx) \| [IdentifyGroupDTO](../../interfaces/types.IdentifyGroupDTO/page.mdx)
Either the `actor_id` or the `group` property must be set.
@@ -0,0 +1,5 @@
import { TypeList } from "docs-ui"
# ProviderIdentifyAnalyticsEventDTO
**ProviderIdentifyAnalyticsEventDTO**: [IdentifyAnalyticsEventDTO](../types.IdentifyAnalyticsEventDTO/page.mdx)
@@ -0,0 +1,5 @@
import { TypeList } from "docs-ui"
# ProviderTrackAnalyticsEventDTO
**ProviderTrackAnalyticsEventDTO**: [TrackAnalyticsEventDTO](../../interfaces/types.TrackAnalyticsEventDTO/page.mdx)
@@ -8,6 +8,50 @@ export const infrastructureModulesSidebar = [
{
type: "separator",
},
{
type: "category",
title: "Analytics Module",
initialOpen: true,
children: [
{
type: "link",
path: "/infrastructure-modules/analytics",
title: "Overview",
},
{
type: "sub-category",
title: "Modules",
children: [
{
type: "link",
path: "/infrastructure-modules/analytics/local",
title: "Local",
},
{
type: "link",
path: "/infrastructure-modules/analytics/posthog",
title: "PostHog",
},
],
},
{
type: "sub-category",
title: "Guides",
children: [
{
type: "link",
path: "/references/analytics/provider",
title: "Create Analytics Module Provider",
},
{
type: "link",
path: "/references/analytics/service",
title: "Use Analytics Module",
},
],
},
],
},
{
type: "category",
title: "Cache Module",
@@ -76,6 +76,7 @@ const sidebarMappings: {
"/references/event-service",
"/references/cache-service",
"/references/file-service",
"/references/analytics",
],
},
{
+5
View File
@@ -174,6 +174,11 @@ export const navDropdownItems: NavigationItem[] = [
title: "Infrastructure Modules",
link: "/resources/infrastructure-modules",
items: [
{
type: "link",
title: "Analytics",
link: "/resources/infrastructure-modules/analytics",
},
{
type: "link",
title: "Cache",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,473 @@
{
"id": 23,
"name": "analytics-provider",
"variant": "project",
"kind": 1,
"flags": {},
"children": [
{
"id": 24,
"name": "AbstractAnalyticsProviderService",
"variant": "declaration",
"kind": 128,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "### constructor\n\nThe constructor allows you to access resources from the module's container using the first parameter,\nand the module's options using the second parameter.\n\nIf you're creating a client or establishing a connection with a third-party service, do it in the constructor.\n\n#### Example\n\n"
},
{
"kind": "code",
"text": "```ts\nimport { Logger } from \"@medusajs/framework/types\"\nimport { AbstractAnalyticsProviderService } from \"@medusajs/framework/utils\"\n\ntype InjectedDependencies = {\n logger: Logger\n}\n\ntype Options = {\n apiKey: string\n}\n\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n protected logger_: Logger\n protected options_: Options\n static identifier = \"my-analytics\"\n // assuming you're initializing a client\n protected client\n\n constructor (\n { logger }: InjectedDependencies,\n options: Options\n ) {\n super()\n\n this.logger_ = logger\n this.options_ = options\n\n // assuming you're initializing a client\n this.client = new Client(options)\n }\n}\n\nexport default MyAnalyticsProviderService\n```"
}
]
},
"children": [
{
"id": 25,
"name": "identifier",
"variant": "declaration",
"kind": 1024,
"flags": {
"isStatic": true
},
"comment": {
"summary": [
{
"kind": "text",
"text": "Each analytics provider has a unique ID used to identify it. The provider's ID\nwill be stored as "
},
{
"kind": "code",
"text": "`aly_{identifier}_{id}`"
},
{
"kind": "text",
"text": ", where "
},
{
"kind": "code",
"text": "`{id}`"
},
{
"kind": "text",
"text": " is the provider's "
},
{
"kind": "code",
"text": "`id`"
},
{
"kind": "text",
"text": "\nproperty in the "
},
{
"kind": "code",
"text": "`medusa-config.ts`"
},
{
"kind": "text",
"text": "."
}
],
"blockTags": [
{
"tag": "@example",
"content": [
{
"kind": "code",
"text": "```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n static identifier = \"my-analytics\"\n // ...\n}\n```"
}
]
}
]
},
"sources": [
{
"fileName": "abstract-analytics-provider.ts",
"line": 65,
"character": 9,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/utils/src/analytics/abstract-analytics-provider.ts#L65"
}
],
"type": {
"type": "intrinsic",
"name": "string"
}
},
{
"id": 26,
"name": "constructor",
"variant": "declaration",
"kind": 512,
"flags": {},
"signatures": [
{
"id": 27,
"name": "AbstractAnalyticsProviderService",
"variant": "signature",
"kind": 16384,
"flags": {},
"type": {
"type": "reference",
"target": 24,
"name": "AbstractAnalyticsProviderService",
"package": "@medusajs/utils"
}
}
]
},
{
"id": 30,
"name": "track",
"variant": "declaration",
"kind": 2048,
"flags": {},
"sources": [
{
"fileName": "abstract-analytics-provider.ts",
"line": 96,
"character": 8,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/utils/src/analytics/abstract-analytics-provider.ts#L96"
}
],
"signatures": [
{
"id": 31,
"name": "track",
"variant": "signature",
"kind": 4096,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "This method tracks an event with the third-party analytics provider. The Analytics Module\nwill use this method in its "
},
{
"kind": "code",
"text": "`track`"
},
{
"kind": "text",
"text": " method if your provider is configured in "
},
{
"kind": "code",
"text": "`medusa-config.ts`"
},
{
"kind": "text",
"text": ".\n\nYou can send the event to the third-party provider based on its semantics."
}
],
"blockTags": [
{
"tag": "@returns",
"content": [
{
"kind": "text",
"text": "Resolves when the event is tracked successfully."
}
]
},
{
"tag": "@example",
"content": [
{
"kind": "code",
"text": "```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n // ...\n async track(\n data: ProviderTrackAnalyticsEventDTO\n ): Promise<void> {\n // track event to third-party provider\n // or using custom logic\n // for example:\n this.client.track(data)\n }\n}\n```"
}
]
}
]
},
"sources": [
{
"fileName": "abstract-analytics-provider.ts",
"line": 96,
"character": 8,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/utils/src/analytics/abstract-analytics-provider.ts#L96"
}
],
"parameters": [
{
"id": 32,
"name": "data",
"variant": "param",
"kind": 32768,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "The event's details."
}
]
},
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/analytics/mutations.ts",
"qualifiedName": "TrackAnalyticsEventDTO"
},
"name": "TrackAnalyticsEventDTO",
"package": "@medusajs/types"
}
}
],
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../node_modules/typescript/lib/lib.es5.d.ts",
"qualifiedName": "Promise"
},
"typeArguments": [
{
"type": "intrinsic",
"name": "void"
}
],
"name": "Promise",
"package": "typescript"
},
"implementationOf": {
"type": "reference",
"target": -1,
"name": "IAnalyticsProvider.track"
}
}
],
"implementationOf": {
"type": "reference",
"target": -1,
"name": "IAnalyticsProvider.track"
}
},
{
"id": 33,
"name": "identify",
"variant": "declaration",
"kind": 2048,
"flags": {},
"sources": [
{
"fileName": "abstract-analytics-provider.ts",
"line": 120,
"character": 8,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/utils/src/analytics/abstract-analytics-provider.ts#L120"
}
],
"signatures": [
{
"id": 34,
"name": "identify",
"variant": "signature",
"kind": 4096,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "This method identifies an actor or group in the third-party analytics provider. The Analytics Module\nwill use this method in its "
},
{
"kind": "code",
"text": "`identify`"
},
{
"kind": "text",
"text": " method if your provider is configured in "
},
{
"kind": "code",
"text": "`medusa-config.ts`"
},
{
"kind": "text",
"text": "."
}
],
"blockTags": [
{
"tag": "@returns",
"content": [
{
"kind": "text",
"text": "Resolves when the actor or group is identified successfully."
}
]
},
{
"tag": "@example",
"content": [
{
"kind": "code",
"text": "```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n // ...\n async identify(\n data: ProviderIdentifyAnalyticsEventDTO\n ): Promise<void> {\n // identify actor or group in the analytics provider\n // or using custom logic\n // for example:\n this.client.identify(data)\n }\n}\n```"
}
]
}
]
},
"sources": [
{
"fileName": "abstract-analytics-provider.ts",
"line": 120,
"character": 8,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/utils/src/analytics/abstract-analytics-provider.ts#L120"
}
],
"parameters": [
{
"id": 35,
"name": "data",
"variant": "param",
"kind": 32768,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "The details of the actor or group."
}
]
},
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/analytics/mutations.ts",
"qualifiedName": "IdentifyAnalyticsEventDTO"
},
"name": "IdentifyAnalyticsEventDTO",
"package": "@medusajs/types"
}
}
],
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../node_modules/typescript/lib/lib.es5.d.ts",
"qualifiedName": "Promise"
},
"typeArguments": [
{
"type": "intrinsic",
"name": "void"
}
],
"name": "Promise",
"package": "typescript"
},
"implementationOf": {
"type": "reference",
"target": -1,
"name": "IAnalyticsProvider.identify"
}
}
],
"implementationOf": {
"type": "reference",
"target": -1,
"name": "IAnalyticsProvider.identify"
}
}
],
"groups": [
{
"title": "Constructors",
"children": [
26
]
},
{
"title": "Properties",
"children": [
25
]
},
{
"title": "Methods",
"children": [
30,
33
]
}
],
"sources": [
{
"fileName": "abstract-analytics-provider.ts",
"line": 53,
"character": 13,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/utils/src/analytics/abstract-analytics-provider.ts#L53"
}
],
"implementedTypes": [
{
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/analytics/provider.ts",
"qualifiedName": "IAnalyticsProvider"
},
"name": "IAnalyticsProvider",
"package": "@medusajs/types"
}
]
}
],
"groups": [
{
"title": "Classes",
"children": [
24
]
}
],
"packageName": "@medusajs/utils",
"symbolIdMap": {
"23": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": ""
},
"24": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "AbstractAnalyticsProviderService"
},
"25": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "AbstractAnalyticsProviderService.identifier"
},
"30": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "AbstractAnalyticsProviderService.track"
},
"31": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "AbstractAnalyticsProviderService.track"
},
"32": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "data"
},
"33": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "AbstractAnalyticsProviderService.identify"
},
"34": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "AbstractAnalyticsProviderService.identify"
},
"35": {
"sourceFileName": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts",
"qualifiedName": "data"
}
},
"files": {
"entries": {
"1": "../../../../packages/core/utils/src/analytics/abstract-analytics-provider.ts"
},
"reflections": {
"1": 23
}
}
}
@@ -0,0 +1,417 @@
{
"id": 0,
"name": "analytics",
"variant": "project",
"kind": 1,
"flags": {},
"children": [
{
"id": 1,
"name": "IAnalyticsModuleService",
"variant": "declaration",
"kind": 256,
"flags": {},
"children": [
{
"id": 2,
"name": "getProvider",
"variant": "declaration",
"kind": 2048,
"flags": {},
"sources": [
{
"fileName": "analytics/service.ts",
"line": 16,
"character": 2,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L16"
}
],
"signatures": [
{
"id": 3,
"name": "getProvider",
"variant": "signature",
"kind": 4096,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "This method returns the service of the configured Analytics Module Provider in "
},
{
"kind": "code",
"text": "`medusa-config.ts`"
},
{
"kind": "text",
"text": ". This is useful\nif you want to execute custom methods defined in the provider's service or you need direct access to it."
}
],
"blockTags": [
{
"tag": "@returns",
"content": [
{
"kind": "text",
"text": "An instance of the Analytics Module Provider's service."
}
]
},
{
"tag": "@example",
"content": [
{
"kind": "code",
"text": "```ts\nconst postHogProviderService = analyticsModuleService.getProvider()\n// TODO: perform custom actions with the provider\n```"
}
]
}
]
},
"sources": [
{
"fileName": "analytics/service.ts",
"line": 16,
"character": 2,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L16"
}
],
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/analytics/provider.ts",
"qualifiedName": "IAnalyticsProvider"
},
"name": "IAnalyticsProvider",
"package": "@medusajs/types"
}
}
]
},
{
"id": 4,
"name": "track",
"variant": "declaration",
"kind": 2048,
"flags": {},
"sources": [
{
"fileName": "analytics/service.ts",
"line": 35,
"character": 2,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L35"
}
],
"signatures": [
{
"id": 5,
"name": "track",
"variant": "signature",
"kind": 4096,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "This method tracks an event in the analytics provider. The Analytics Module\nwill use the "
},
{
"kind": "code",
"text": "`track`"
},
{
"kind": "text",
"text": " method of the underlying provider configured in "
},
{
"kind": "code",
"text": "`medusa-config.ts`"
},
{
"kind": "text",
"text": " to track the event."
}
],
"blockTags": [
{
"tag": "@returns",
"content": [
{
"kind": "text",
"text": "Resolves when the event is tracked successfully."
}
]
},
{
"tag": "@example",
"content": [
{
"kind": "code",
"text": "```ts\nawait analyticsModuleService.track({\n event: \"order_placed\",\n properties: {\n order_id: \"order_123\",\n customer_id: \"customer_456\",\n total: 100,\n }\n})\n```"
}
]
}
]
},
"sources": [
{
"fileName": "analytics/service.ts",
"line": 35,
"character": 2,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L35"
}
],
"parameters": [
{
"id": 6,
"name": "data",
"variant": "param",
"kind": 32768,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "The event's details."
}
]
},
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/analytics/mutations.ts",
"qualifiedName": "TrackAnalyticsEventDTO"
},
"name": "TrackAnalyticsEventDTO",
"package": "@medusajs/types"
}
}
],
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../node_modules/typescript/lib/lib.es5.d.ts",
"qualifiedName": "Promise"
},
"typeArguments": [
{
"type": "intrinsic",
"name": "void"
}
],
"name": "Promise",
"package": "typescript"
}
}
]
},
{
"id": 7,
"name": "identify",
"variant": "declaration",
"kind": 2048,
"flags": {},
"sources": [
{
"fileName": "analytics/service.ts",
"line": 52,
"character": 2,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L52"
}
],
"signatures": [
{
"id": 8,
"name": "identify",
"variant": "signature",
"kind": 4096,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "This method identifies an actor or group in the analytics provider. The Analytics Module\nwill use the "
},
{
"kind": "code",
"text": "`identify`"
},
{
"kind": "text",
"text": " method of the underlying provider configured in "
},
{
"kind": "code",
"text": "`medusa-config.ts`"
},
{
"kind": "text",
"text": " to identify the actor or group."
}
],
"blockTags": [
{
"tag": "@returns",
"content": [
{
"kind": "text",
"text": "Resolves when the actor or group is identified successfully."
}
]
},
{
"tag": "@example",
"content": [
{
"kind": "code",
"text": "```ts\nawait analyticsModuleService.identify({\n actor_id: \"123\",\n properties: {\n name: \"John Doe\"\n }\n})\n```"
}
]
}
]
},
"sources": [
{
"fileName": "analytics/service.ts",
"line": 52,
"character": 2,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L52"
}
],
"parameters": [
{
"id": 9,
"name": "data",
"variant": "param",
"kind": 32768,
"flags": {},
"comment": {
"summary": [
{
"kind": "text",
"text": "The details of the actor or group."
}
]
},
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/analytics/mutations.ts",
"qualifiedName": "IdentifyAnalyticsEventDTO"
},
"name": "IdentifyAnalyticsEventDTO",
"package": "@medusajs/types"
}
}
],
"type": {
"type": "reference",
"target": {
"sourceFileName": "../../node_modules/typescript/lib/lib.es5.d.ts",
"qualifiedName": "Promise"
},
"typeArguments": [
{
"type": "intrinsic",
"name": "void"
}
],
"name": "Promise",
"package": "typescript"
}
}
]
}
],
"groups": [
{
"title": "Methods",
"children": [
2,
4,
7
]
}
],
"sources": [
{
"fileName": "analytics/service.ts",
"line": 5,
"character": 17,
"url": "https://github.com/medusajs/medusa/blob/db33616cf9ea3b8bd61d60a1e601d649bdea2bdf/packages/core/types/src/analytics/service.ts#L5"
}
],
"extendedTypes": [
{
"type": "reference",
"target": {
"sourceFileName": "../../../../packages/core/types/src/modules-sdk/index.ts",
"qualifiedName": "IModuleService"
},
"name": "IModuleService",
"package": "@medusajs/types"
}
]
}
],
"groups": [
{
"title": "Interfaces",
"children": [
1
]
}
],
"packageName": "@medusajs/types",
"symbolIdMap": {
"0": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": ""
},
"1": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService"
},
"2": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService.getProvider"
},
"3": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService.getProvider"
},
"4": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService.track"
},
"5": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService.track"
},
"6": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "data"
},
"7": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService.identify"
},
"8": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "IAnalyticsModuleService.identify"
},
"9": {
"sourceFileName": "../../../../packages/core/types/src/analytics/service.ts",
"qualifiedName": "data"
}
},
"files": {
"entries": {
"1": "../../../../packages/core/types/src/analytics/service.ts"
},
"reflections": {
"1": 0
}
}
}
@@ -71,6 +71,18 @@ const customOptions: Record<string, Partial<TypeDocOptions>> = {
tsConfigName: "types.json",
name: "file-service",
}),
analytics: getOptions({
entryPointPath: "packages/core/types/src/analytics/service.ts",
tsConfigName: "types.json",
name: "analytics",
parentIgnore: true,
}),
"analytics-provider": getOptions({
entryPointPath:
"packages/core/utils/src/analytics/abstract-analytics-provider.ts",
tsConfigName: "utils.json",
name: "analytics-provider",
}),
"fulfillment-provider": getOptions({
entryPointPath: "packages/core/utils/src/fulfillment/provider.ts",
tsConfigName: "utils.json",
@@ -185,6 +197,7 @@ const customOptions: Record<string, Partial<TypeDocOptions>> = {
exclude: [
...(baseOptions.exclude || []),
"**/dist/**",
"**/analytics/**",
"**/api-key/**",
"**/auth/**",
"**/bundles/**",
@@ -0,0 +1,216 @@
import { FormattingOptionsType } from "types"
import baseSectionsOptions from "../base-section-options.js"
const analyticsProviderOptions: FormattingOptionsType = {
"^analytics_provider/.*AbstractAnalyticsProviderService": {
reflectionGroups: {
Constructors: false,
},
reflectionDescription: `In this document, you’ll learn how to create an Analytics Module Provider and the methods you must implement in its main service.`,
frontmatterData: {
slug: "/references/analytics/provider",
keywords: ["analytics", "provider", "integration"],
},
reflectionTitle: {
fullReplacement: "How to Create an Analytics Module Provider",
},
shouldIncrementAfterStartSections: true,
expandMembers: true,
expandProperties: true,
sortMembers: true,
sections: {
...baseSectionsOptions,
member_declaration_title: false,
reflection_typeParameters: false,
},
startSections: [
`## Implementation Example
As you implement your Analytics Module Provider, it can be useful to refer to an existing provider and how it's implemeted.
If you need to refer to an existing implementation as an example, check the [PostHog Analytics Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/analytics-posthog).`,
`## Create Module Provider Directory
Start by creating a new directory for your module provider.
If you're creating the module provider in a Medusa application, create it under the \`src/modules\` directory. For example, \`src/modules/my-analytics\`.
If you're creating the module provider in a plugin, create it under the \`src/providers\` directory. For example, \`src/providers/my-analytics\`.
<Note>
The rest of this guide always uses the \`src/modules/my-analytics\` directory as an example.
</Note>`,
`## 2. Create the Analytics Module Provider's Service
Create the file \`src/modules/my-analytics/service.ts\` that holds the implementation of the module provider's main service. It must extend the \`AbstractAnalyticsProviderService\` class imported from \`@medusajs/framework/utils\`:
\`\`\`ts title="src/modules/my-analytics/service.ts"
import { AbstractAnalyticsProviderService } from "@medusajs/framework/utils"
class MyAnalyticsProviderService extends AbstractAnalyticsProviderService {
// TODO implement methods
}
export default MyAnalyticsProviderService
\`\`\``,
],
endSections: [
`## 3. Create Module Provider Definition File
Create the file \`src/modules/my-analytics/index.ts\` with the following content:
\`\`\`ts title="src/modules/my-analytics/index.ts"
import MyAnalyticsProviderService from "./service"
import {
ModuleProvider,
Modules
} from "@medusajs/framework/utils"
export default ModuleProvider(Modules.ANALYTICS, {
services: [MyAnalyticsProviderService],
})
\`\`\`
This exports the module provider's definition, indicating that the \`MyAnalyticsProviderService\` is the module provider's service.`,
`## 4. Use Module Provider
To use your Analytics Module Provider, add it to the \`providers\` array of the Analytics Module in \`medusa-config.ts\`:
<Note>
The Analytics Module accepts one provider only.
</Note>
\`\`\`ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
providers: [
{
// if module provider is in a plugin, use \`plugin-name/providers/my-analytics\`
resolve: "./src/modules/my-analytics",
id: "my-analytics",
options: {
// provider options...
},
},
],
},
},
]
})
\`\`\`
`,
`## 5. Test it Out
To test the module out, you'll track in your third-party provider when an order is placed.
You'll first create a [workflow](!docs!/learn/fundamentals/workflows) that tracks the order completion event. Then, you can execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the \`order.placed\` event.
For example, create a workflow at \`src/workflows/track-order-placed.ts\` with the following content:
\`\`\`ts title="src/workflows/track-order-created.ts"
import { createWorkflow } from "@medusajs/framework/workflows-sdk"
import { createStep } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"
import { OrderDTO } from "@medusajs/framework/types"
type StepInput = {
order: OrderDTO
}
const trackOrderCreatedStep = createStep(
"track-order-created-step",
async ({ order }: StepInput, { container }) => {
const analyticsModuleService = container.resolve(Modules.ANALYTICS)
await analyticsModuleService.track({
event: "order_created",
userId: order.customer_id,
properties: {
order_id: order.id,
total: order.total,
items: order.items.map((item) => ({
variant_id: item.variant_id,
product_id: item.product_id,
quantity: item.quantity,
})),
customer_id: order.customer_id,
},
})
}
)
type WorkflowInput = {
order_id: string
}
export const trackOrderCreatedWorkflow = createWorkflow(
"track-order-created-workflow",
({ order_id }: WorkflowInput) => {
const { data: orders } = useQueryGraphStep({
entity: "order",
fields: [
"*",
"customer.*",
"items.*"
],
filters: {
id: order_id,
},
})
trackOrderCreatedStep({
order: orders[0],
})
}
)
\`\`\`
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](!docs!/learn/fundamentals/medusa-container) and use its \`track\` method to track the event. This method will use the underlying provider configured (which is your provider, in this case) to track the event.
Next, create a subscriber at \`src/subscribers/order-placed.ts\` with the following content:
\`\`\`ts title="src/subscribers/order-placed.ts"
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
import { trackOrderCreatedWorkflow } from "../workflows/track-order-created"
export default async function orderPlacedHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
await trackOrderCreatedWorkflow(container).run({
input: {
order_id: data.id,
},
})
}
export const config: SubscriberConfig = {
event: "order.placed",
}
\`\`\`
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 in your third-party provider if the event was tracked successfully.
`,
`## Additional Resources
- [How to Use the Analytics Module](/references/analytics/service)
`,
],
},
}
export default analyticsProviderOptions
@@ -0,0 +1,83 @@
import { FormattingOptionsType } from "types"
const analyticsOptions: FormattingOptionsType = {
"^analytics/.*IAnalyticsModuleService": {
reflectionGroups: {
Constructors: false,
},
reflectionDescription: `In this document, you’ll learn about the different methods in the Analytics Module's service and how to use them.
:::note
The Analytics Module is available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
:::`,
frontmatterData: {
slug: "/references/analytics/service",
tags: ["analytics", "server", "how to"],
sidebar_label: "Use Analytics Module",
},
reflectionTitle: {
fullReplacement: "How to Use Analytics Module",
},
expandMembers: true,
sortMembers: true,
startSections: [
`### Configure Analytics Module Provider
To use the Analytics Module, you need to configure it along with an Analytics Module Provider.
Medusa provides two Analytics Module Providers: [Local](/infrastructure-modules/analytics/local) and [PostHog](/infrastructure-modules/analytics/posthog) module providers.
To configure the Analytics Module and its provider, add it to the list of modules in your \`medusa-config.ts\` file. For example:
\`\`\`ts title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "@medusajs/medusa/analytics",
options: {
providers: [
{
resolve: "@medusajs/medusa/analytics-local",
id: "local",
},
],
},
},
],
})
\`\`\`
Refer to the documentation of each provider for specific configuration options.
`,
`## Resolve Analytics Module's Service
In your workflow's step, you can resolve the Analytics Module's service from the Medusa container:
\`\`\`ts
import { Modules } from "@medusajs/framework/utils"
import { createStep } from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
async ({}, { container }) => {
const analyticsModuleService = container.resolve(
Modules.Analytics
)
// TODO use analyticsModuleService
}
)
\`\`\`
You can then use the Analytics Module's service's methods in the step, which would use the underlying provider's logic. The rest of this guide details these methods.
---
`,
],
},
}
export default analyticsOptions
@@ -17,8 +17,12 @@ import eventOptions from "./event.js"
import fileServiceOptions from "./file-service.js"
import notificationServiceOptions from "./notification-service.js"
import eventsOptions from "./events.js"
import analyticsOptions from "./analytics.js"
import analyticsProviderOptions from "./analytics-provider.js"
const mergerCustomOptions: FormattingOptionsType = {
...analyticsOptions,
...analyticsProviderOptions,
...authProviderOptions,
...cacheOptions,
...coreFlowsOptions,
@@ -43,6 +43,8 @@ const allReferences = [
"notification-service",
"events",
"module-events",
"analytics",
"analytics-provider",
]
export default allReferences