Raw
1 import { Table, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `PostHog Analytics Module Provider`,
5 }
6
7 # {metadata.title}
8
9 The PostHog Analytics Module Provider allows you to integrate [PostHog](https://posthog.com/) with Medusa.
10
11 PostHog is an open-source product analytics platform that helps you track user interactions and analyze user behavior in your commerce application.
12
13 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.
14
15 <Note>
16
17 The Analytics Module and its providers are available starting [Medusa v2.8.3](https://github.com/medusajs/medusa/releases/tag/v2.8.3).
18
19 </Note>
20
21 ---
22
23 ## Register the PostHog Analytics Module
24
25 <Prerequisites
26 items={[
27 {
28 text: "PostHog account",
29 link: "https://app.posthog.com/signup",
30 },
31 {
32 text: "PostHog API Key",
33 link: "https://posthog.com/docs/api",
34 },
35 ]}
36 />
37
38 Add the module into the `provider` object of the Analytics Module:
39
40 <Note>
41
42 You can use only one provider in your Medusa application.
43
44 </Note>
45
46 ```ts title="medusa-config.ts"
47 module.exports = defineConfig({
48 // ...
49 modules: [
50 {
51 resolve: "@medusajs/medusa/analytics",
52 options: {
53 providers: [
54 {
55 resolve: "@medusajs/analytics-posthog",
56 id: "posthog",
57 options: {
58 posthogEventsKey: process.env.POSTHOG_EVENTS_API_KEY,
59 posthogHost: process.env.POSTHOG_HOST,
60 },
61 },
62 ],
63 },
64 },
65 ],
66 })
67 ```
68
69 ### Environment Variables
70
71 Make sure to add the following environment variables:
72
73 ```bash
74 POSTHOG_EVENTS_API_KEY=<YOUR_POSTHOG_EVENTS_API_KEY>
75 POSTHOG_HOST=<YOUR_POSTHOG_HOST>
76 ```
77
78 ### PostHog Analytics Module Options
79
80 <Table>
81 <Table.Header>
82 <Table.Row>
83 <Table.HeaderCell>
84 Option
85 </Table.HeaderCell>
86 <Table.HeaderCell>
87 Description
88 </Table.HeaderCell>
89 <Table.HeaderCell>
90 Default
91 </Table.HeaderCell>
92 </Table.Row>
93 </Table.Header>
94 <Table.Body>
95 <Table.Row>
96 <Table.Cell>
97 `eventsKey`
98 </Table.Cell>
99 <Table.Cell>
100 The PostHog API key for tracking events. This is required to authenticate your requests to the PostHog API.
101 </Table.Cell>
102 <Table.Cell>
103 \-
104 </Table.Cell>
105 </Table.Row>
106 <Table.Row>
107 <Table.Cell>
108 `posthogHost`
109 </Table.Cell>
110 <Table.Cell>
111 The PostHog API host URL.
112 </Table.Cell>
113 <Table.Cell>
114 `https://eu.i.posthog.com`
115 </Table.Cell>
116 </Table.Row>
117 </Table.Body>
118 </Table>
119
120 ---
121
122 ## Test out the Module
123
124 To test the module out, you'll track in PostHog when an order is placed.
125
126 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.
127
128 For example, create a workflow at `src/workflows/track-order-placed.ts` with the following content:
129
130 export const workflowHighlights = [
131 ["14", "resolve", "Resolve the Analytics Module's service"],
132 ["16", "track", "Track the event in the installed Analytics Module Provider"]
133 ]
134
135 ```ts title="src/workflows/track-order-placed.ts" highlights={workflowHighlights}
136 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
137 import { createStep } from "@medusajs/framework/workflows-sdk"
138 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
139 import { Modules } from "@medusajs/framework/utils"
140 import { OrderDTO } from "@medusajs/framework/types"
141
142 type StepInput = {
143 order: OrderDTO
144 }
145
146 const trackOrderPlacedStep = createStep(
147 "track-order-placed-step",
148 async ({ order }: StepInput, { container }) => {
149 const analyticsModuleService = container.resolve(Modules.ANALYTICS)
150
151 await analyticsModuleService.track({
152 event: "order_placed",
153 actor_id: order.customer_id,
154 properties: {
155 order_id: order.id,
156 total: order.total,
157 items: order.items?.map((item) => ({
158 variant_id: item.variant_id,
159 product_id: item.product_id,
160 quantity: item.quantity,
161 })),
162 customer_id: order.customer_id,
163 },
164 })
165 }
166 )
167
168 type WorkflowInput = {
169 order_id: string
170 }
171
172 export const trackOrderPlacedWorkflow = createWorkflow(
173 "track-order-placed-workflow",
174 ({ order_id }: WorkflowInput) => {
175 const { data: orders } = useQueryGraphStep({
176 entity: "order",
177 fields: [
178 "*",
179 "customer.*",
180 "items.*",
181 ],
182 filters: {
183 id: order_id,
184 },
185 })
186 trackOrderCreatedStep({
187 order: orders[0],
188 } as unknown as StepInput)
189 }
190 )
191 ```
192
193 This workflow retrieves the order details using the `useQueryGraphStep` and then tracks the order placement event using the `trackOrderPlacedStep`.
194
195 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.
196
197 Next, create a subscriber at `src/subscribers/order-placed.ts` with the following content:
198
199 ```ts title="src/subscribers/order-placed.ts"
200 import type {
201 SubscriberArgs,
202 SubscriberConfig,
203 } from "@medusajs/framework"
204 import { trackOrderPlacedWorkflow } from "../workflows/track-order-placed"
205
206 export default async function orderPlacedHandler({
207 event: { data },
208 container,
209 }: SubscriberArgs<{ id: string }>) {
210 await trackOrderPlacedWorkflow(container).run({
211 input: {
212 order_id: data.id,
213 },
214 })
215 }
216
217 export const config: SubscriberConfig = {
218 event: "order.placed",
219 }
220 ```
221
222 This subscriber listens to the `order.placed` event and executes the `trackOrderPlacedWorkflow` workflow, passing the order ID as input.
223
224 You'll now track the order placement 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.
225
226 ---
227
228 ## Additional Resources
229
230 - [How to Use the Analytics Module](/references/analytics/service)