1 ---
2 sidebar_label: "Integrate Segment"
3 tags:
4 - server
5 - tutorial
6 - analytics
7 products:
8 - order
9 ---
10
11 import { Card, Prerequisites, Details, WorkflowDiagram } from "docs-ui"
12 import { Github, PlaySolid } from "@medusajs/icons"
13
14 export const metadata = {
15 title: `Integrate Segment (Analytics) with Medusa`,
16 }
17
18 # {metadata.title}
19
20 In this tutorial, you'll learn how to integrate Segment with Medusa to track events and analytics.
21
22 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa's architecture facilitates integrating third-party services to customize Medusa's infrastructure for your business needs.
23
24 To track analytics in your Medusa application, you can integrate [Segment](https://segment.com/), a service that collects analytics from multiple sources and sends them to various destinations. This tutorial will help you set up Segment in your Medusa application and track common events.
25
26 ## Summary
27
28 By following this tutorial, you'll learn how to:
29
30 - Install and set up Medusa.
31 - Integrate Segment with your Medusa application.
32 - Handle Medusa's `order.placed` event to track order placements.
33 - Track custom events in your Medusa application with Segment.
34
35 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
36
37 ![Diagram showcasing the integration of Segment with Medusa](https://res.cloudinary.com/dza7lstvk/image/upload/v1748264333/Medusa%20Book/segment-overview_apkrtp.jpg)
38
39 <Card
40 title="Example Repository"
41 text="Find the full code of the guide in this repository."
42 href="https://github.com/medusajs/examples/tree/main/segment-integration"
43 icon={Github}
44 />
45
46 ---
47
48 ## Step 1: Install a Medusa Application
49
50 <Prerequisites items={[
51 {
52 text: "Node.js v20.19.0+ or v22.12.0+",
53 link: "https://nodejs.org/en/download"
54 },
55 {
56 text: "Git CLI tool",
57 link: "https://git-scm.com/downloads"
58 },
59 {
60 text: "PostgreSQL",
61 link: "https://www.postgresql.org/download/"
62 }
63 ]} />
64
65 Start by installing the Medusa application on your machine with the following command:
66
67 ```bash
68 npx create-medusa-app@latest
69 ```
70
71 First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
72
73 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
74
75 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
76
77 <Note title="Ran into Errors?">
78
79 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
80
81 </Note>
82
83 <Note>
84
85 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
86
87 </Note>
88
89 ---
90
91 ## Step 2: Create Segment Module Provider
92
93 To integrate third-party services into Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain.
94
95 Medusa's [Analytics Module](../../../infrastructure-modules/analytics/page.mdx) provides an interface to track events in your Medusa application. It delegates the actual tracking to the configured Analytics Module Provider.
96
97 In this step, you'll integrate Segment as an Analytics Module Provider. Later, you'll use it to track events in your Medusa application.
98
99 <Note>
100
101 Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules in Medusa.
102
103 </Note>
104
105 ### a. Install Segment Node SDK
106
107 Before you create the Segment Module Provider, you'll install the Segment Node SDK to interact with Segment's API.
108
109 Run the following command in your `apps/backend` directory:
110
111 ```bash npm2yarn
112 npm install @segment/analytics-node
113 ```
114
115 You'll use the SDK in the next steps.
116
117 ### b. Create Module Directory
118
119 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/segment`.
120
121 ### c. Create Segment Module's Service
122
123 A module has a service that contains its logic. For Analytics Module Providers, the service implements the logic to track events in the third-party service.
124
125 To create the service of the Segment Analytics Module Provider, create the file `src/modules/segment/service.ts` with the following content:
126
127 export const serviceHighlights = [
128 ["7", "Options", "Options passed to the module provider."],
129 ["13", "AbstractAnalyticsProviderService", "Analytics Module Provider must extend this class."],
130 ["15", "identifier", "Unique identifier of the module provider."],
131 ["25", "client", "Initialize Segment client with the write key."]
132 ]
133
134 ```ts title="src/modules/segment/service.ts" highlights={serviceHighlights}
135 import {
136 AbstractAnalyticsProviderService,
137 MedusaError,
138 } from "@medusajs/framework/utils"
139 import { Analytics } from "@segment/analytics-node"
140
141 type Options = {
142 writeKey: string
143 }
144
145 type InjectedDependencies = {}
146
147 class SegmentAnalyticsProviderService extends AbstractAnalyticsProviderService {
148 private client: Analytics
149 static identifier = "segment"
150
151 constructor(container: InjectedDependencies, options: Options) {
152 super()
153 if (!options.writeKey) {
154 throw new MedusaError(
155 MedusaError.Types.INVALID_DATA,
156 "Segment write key is required"
157 )
158 }
159 this.client = new Analytics({ writeKey: options.writeKey })
160 }
161 }
162
163 export default SegmentAnalyticsProviderService
164 ```
165
166 An Analytics Module Provider's service must extend the `AbstractAnalyticsProviderService` class. It must also have an `identifier` static property with the unique identifier of the provider.
167
168 A module provider's constructor receives two parameters:
169
170 - `container`: The [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module. In this tutorial, you don't need to resolve any resources.
171 - `options`: Options that are passed to the module provider when it's registered in Medusa's configurations. You define the following option:
172 - `writeKey`: The Segment write key. You'll learn how to retrieve and set this option in the [Add Module Provider to Medusa's Configurations](#h-add-module-provider-to-medusas-configurations) section.
173
174 In the constructor, you create a Segment client using the Segment Node SDK. You pass the `writeKey` option to the client.
175
176 You'll use this client to implement the service's methods in the next sections.
177
178 <Note>
179
180 Refer to the [Create Analytics Module Provider](/references/analytics/provider) guide for detailed information about the methods.
181
182 </Note>
183
184 ### d. Implement identify Method
185
186 The `identify` method is used to identify a user in Segment. It associates the user's ID with their profile information, such as name and email.
187
188 Add the `identify` method to the `SegmentAnalyticsProviderService` class:
189
190 ```ts title="src/modules/segment/service.ts"
191 // other imports...
192 import {
193 ProviderIdentifyAnalyticsEventDTO,
194 } from "@medusajs/framework/types"
195
196 class SegmentAnalyticsProviderService extends AbstractAnalyticsProviderService {
197 // ...
198 async identify(data: ProviderIdentifyAnalyticsEventDTO): Promise<void> {
199 const anonymousId = data.properties && "anonymousId" in data.properties ?
200 data.properties.anonymousId : undefined
201 const traits = data.properties && "traits" in data.properties ?
202 data.properties.traits : undefined
203
204 if ("group" in data) {
205 this.client.group({
206 groupId: data.group.id,
207 userId: data.actor_id,
208 anonymousId,
209 traits,
210 context: data.properties,
211 })
212 } else {
213 this.client.identify({
214 userId: data.actor_id,
215 anonymousId,
216 traits,
217 context: data.properties,
218 })
219 }
220 }
221 }
222 ```
223
224 #### Parameters
225
226 The `identify` method receives an object with the following properties:
227
228 - `actor_id`: The ID of the user being identified.
229 - `group`: Alternatively, the group being identified. If this property is present, the `actor_id` is ignored.
230 - `properties`: Additional properties to associate with the user or group. This can include traits like name, email, and so on.
231
232 <Note>
233
234 The method receives other parameters, which you can find in the [Create Analytics Module Provider](/references/analytics/provider#identify) guide.
235
236 </Note>
237
238 #### Method Logic
239
240 In the method, if the `group` property is present, you call the `group` method of the Segment client to identify a group. Otherwise, you call the `identify` method to identify a user.
241
242 For both methods, you extract the `anonymousId` and `traits` from the `properties` object if they are present. You also pass the `actor_id` as the `userId`, and `group.id` for groups.
243
244 ### e. Implement track Method
245
246 The `track` method is used to track events in Segment. It can track events like order placements, cart updates, and more.
247
248 Add the `track` method to the `SegmentAnalyticsProviderService` class:
249
250 ```ts title="src/modules/segment/service.ts"
251 // other imports...
252 import {
253 ProviderTrackAnalyticsEventDTO,
254 } from "@medusajs/framework/types"
255
256 class SegmentAnalyticsProviderService extends AbstractAnalyticsProviderService {
257 // ...
258 async track(data: ProviderTrackAnalyticsEventDTO): Promise<void> {
259 const userId = "group" in data ?
260 data.actor_id || data.group?.id : data.actor_id
261 const anonymousId = data.properties && "anonymousId" in data.properties ?
262 data.properties.anonymousId : undefined
263
264 if (!userId && !anonymousId) {
265 throw new MedusaError(
266 MedusaError.Types.INVALID_DATA,
267 `Actor or group ID is required for event ${data.event}`
268 )
269 }
270
271 this.client.track({
272 userId,
273 anonymousId,
274 event: data.event,
275 properties: data.properties,
276 timestamp: data.properties && "timestamp" in data.properties ?
277 new Date(data.properties.timestamp) : undefined,
278 })
279 }
280 }
281 ```
282
283 #### Parameters
284
285 The `track` method receives an object with the following properties:
286
287 - `actor_id`: The ID of the user performing the event.
288 - `group`: Alternatively, the group performing the event. If this property is present, the `actor_id` is ignored.
289 - `event`: The name of the event being tracked.
290 - `properties`: Additional properties associated with the event. This can include details like product ID, order ID, and so on.
291
292 <Note>
293
294 The method receives other parameters, which you can find in the [Create Analytics Module Provider](/references/analytics/provider#track) guide.
295
296 </Note>
297
298 #### Method Logic
299
300 In the method, you set the user ID either to the actor or group ID. You also check if the anonymous ID is present in the properties to use it.
301
302 Next, you call the `track` method of the Segment client, passing it the user ID, anonymous ID, event name, properties, and timestamp (if present in the properties).
303
304 ### f. Implement shutdown Method
305
306 The `shutdown` method is used to gracefully shut down the Segment client when the Medusa application is stopped. It allows you to send all pending events to Segment before the application exits.
307
308 Add the following method to the `SegmentAnalyticsProviderService` class:
309
310 ```ts title="src/modules/segment/service.ts"
311 class SegmentAnalyticsProviderService extends AbstractAnalyticsProviderService {
312 // ...
313 async shutdown(): Promise<void> {
314 await this.client.flush({
315 close: true,
316 })
317 }
318 }
319 ```
320
321 #### Method Logic
322
323 In the method, you call the `flush` method of the Segment client with the `close` option set to `true`. This method will send all pending events to Segment and close the client connection.
324
325 ### g. Export Module Definition
326
327 You've now finished implementing the necessary methods for the Segment Analytics Module Provider.
328
329 The final piece to a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the module's details, including its service.
330
331 To create the module's definition, create the file `src/modules/segment/index.ts` with the following content:
332
333 ```ts title="src/modules/segment/index.ts"
334 import SegmentAnalyticsProviderService from "./service"
335 import {
336 ModuleProvider,
337 Modules,
338 } from "@medusajs/framework/utils"
339
340 export default ModuleProvider(Modules.ANALYTICS, {
341 services: [SegmentAnalyticsProviderService],
342 })
343 ```
344
345 You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters:
346
347 1. The name of the module that this provider belongs to, which is `Modules.ANALYTICS` in this case.
348 2. An object with a required property `services` indicating the Module Provider's services.
349
350 ### h. Add Module Provider to Medusa's Configurations
351
352 Once you finish building the module, add it to Medusa's configurations to start using it.
353
354 In `medusa-config.ts`, add a `modules` property:
355
356 ```ts title="medusa-config.ts"
357 module.exports = defineConfig({
358 // ...
359 modules: [
360 {
361 resolve: "@medusajs/medusa/analytics",
362 options: {
363 providers: [
364 {
365 resolve: "./src/modules/segment",
366 id: "segment",
367 options: {
368 writeKey: process.env.SEGMENT_WRITE_KEY || "",
369 },
370 },
371 ],
372 },
373 },
374 ],
375 })
376 ```
377
378 To pass an Analytics Module Provider to the Analytics Module, you add the `modules` property to the Medusa configuration and pass the Analytics Module in its value.
379
380 The Analytics Module accepts a `providers` option, which is an array of Analytics Module Providers to register. However, you can only register one analytics provider in your Medusa application.
381
382 To register the Segment Analytics Module Provider, you add an object to the `providers` array with the following properties:
383
384 - `resolve`: The NPM package or path to the module provider. In this case, it's the path to the `src/modules/segment` directory.
385 - `id`: The ID of the module provider. The Analytics Module Provider is then registered with the ID `aly_{identifier}_{id}`, where:
386 - `{identifier}`: The identifier static property defined in the Module Provider's service, which is `segment` in this case.
387 - `{id}`: The ID set in this configuration, which is also `segment` in this case.
388 - `options`: The options to pass to the module provider. These are the options you defined in the `Options` interface of the module provider's service.
389
390 ### i. Set Option as Environment Variable
391
392 Next, you'll set the Segment write key as an environment variable.
393
394 To retrieve the Segment write key:
395
396 1. Log into your [Segment](https://app.segment.com) account.
397 2. Go to the Connections page and click the "Add More" button next to the "Sources" section.
398
399 ![Add more button in the Connections page](https://res.cloudinary.com/dza7lstvk/image/upload/v1748254988/Medusa%20Book/CleanShot_2025-05-26_at_10.47.24_2x_qqlkwk.png)
400
401 3. In the "Choose a Source" step, select "Node.js" and click the "Next" button.
402
403 ![Select Node.js as the Source](https://res.cloudinary.com/dza7lstvk/image/upload/v1748255028/Medusa%20Book/CleanShot_2025-05-26_at_10.47.57_2x_zy9g8k.png)
404
405 4. In the "Connect your Node.js Source" step, enter a name for the source and click the "Create Source" button. This will show you the write key to copy.
406
407 ![Copy the write key](https://res.cloudinary.com/dza7lstvk/image/upload/v1748255065/Medusa%20Book/CleanShot_2025-05-26_at_10.48.41_2x_lpgsbb.png)
408
409 You can skip the next step of testing out the source for now.
410
411 Then, add the following environment variable to your `.env` file:
412
413 ```shell
414 SEGMENT_WRITE_KEY=123...
415 ```
416
417 Replace `123...` with the write key you copied from Segment.
418
419 You'll test out the integration as you set up event tracking in the next steps.
420
421 ---
422
423 ## Step 3: Track Order Placement Event
424
425 You'll first track the order-placement event, which is triggered natively in the Medusa application.
426
427 Medusa's events system allows you to listen to events triggered by the Medusa application and execute custom logic asynchronously in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers).
428
429 In the subscriber, you execute functionalities created in [workflows](!docs!/learn/fundamentals/workflows). A workflow is a series of actions, called steps, that complete a task.
430
431 In this step, you'll create a workflow that tracks the `order.placed` event in Segment. Then, you'll create a subscriber that listens to this event and executes the workflow.
432
433 ### a. Create Track Event Step
434
435 Before you create the workflow, you'll create a step that tracks an event in Segment. Later, you'll use this step in the workflows that track events, such as the order-placement event.
436
437 To create a step, create the file `src/workflows/steps/track-event.ts` with the following content:
438
439 export const stepHighlights = [
440 ["5", "event", "The name of the event to track."],
441 ["6", "userId", "The ID of the user performing the event."],
442 ["7", "properties", "Additional properties associated with the event."],
443 ["8", "timestamp", "The timestamp of the event."],
444 ["14", "analyticsModuleService", "Resolve the Analytics Module's service from the Medusa container."],
445 ["22", "anonymousId", "Set a random ID if no user ID is passed."],
446 ["27", "track", "Track the event in Segment."]
447 ]
448
449 ```ts title="src/workflows/steps/track-event.ts" highlights={stepHighlights}
450 import { createStep } from "@medusajs/framework/workflows-sdk"
451 import { Modules } from "@medusajs/framework/utils"
452
453 type TrackEventStepInput = {
454 event: string
455 userId?: string
456 properties?: Record<string, unknown>
457 timestamp?: Date
458 }
459
460 export const trackEventStep = createStep(
461 "track-event",
462 async (input: TrackEventStepInput, { container }) => {
463 const analyticsModuleService = container.resolve(
464 Modules.ANALYTICS
465 )
466
467 if (!input.userId) {
468 // generate a random user id
469 input.properties = {
470 ...input.properties,
471 anonymousId: Math.random().toString(36).substring(2, 15) +
472 Math.random().toString(36).substring(2, 15),
473 }
474 }
475
476 await analyticsModuleService.track({
477 event: input.event,
478 actor_id: input.userId,
479 properties: input.properties,
480 })
481 }
482 )
483 ```
484
485 You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
486
487 1. The step's unique name, which is `track-event`.
488 2. An async function that receives two parameters:
489 - The step's input, which is in this case an object with the following properties:
490 - `event`: The name of the event to track.
491 - `userId`: The ID of the user performing the event.
492 - `properties`: Additional properties associated with the event.
493 - `timestamp`: The timestamp of the event (optional).
494 - An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools that you can access in the step.
495
496 <Note>
497
498 The Medusa container is different from the module's container. Since modules are isolated, they each have a container with their resources. Refer to the [Module Container](!docs!/learn/fundamentals/modules/container) documentation for more information.
499
500 </Note>
501
502 In the step function, you resolve the Analytics Module's service from the Medusa container. This service is the interface to track events with the configured Analytics Module Provider, which is Segment in this case.
503
504 If the `userId` is not provided, you generate a random anonymous ID and add it to the properties. This is useful for tracking events from users who are not logged in.
505
506 Finally, you call the `track` method of the Analytics Module's service, passing it the event name, user ID, and properties.
507
508 ### b. Create Track Order Placed Workflow
509
510 Next, you'll create the workflow that tracks the order placement event.
511
512 To create the workflow, create the file `src/workflows/track-order-placed.ts` with the following content:
513
514 export const workflowHighlights = [
515 ["15", "useQueryGraphStep", "Retrieve the order's details."],
516 ["34", "transform", "Prepare data for tracking."],
517 ["57", "trackEventStep", "Track the order placement event in Segment."]
518 ]
519
520 ```ts title="src/workflows/track-order-placed.ts" highlights={workflowHighlights}
521 import {
522 createWorkflow,
523 transform,
524 } from "@medusajs/framework/workflows-sdk"
525 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
526 import { trackEventStep } from "./steps/track-event"
527
528 type WorkflowInput = {
529 id: string
530 }
531
532 export const trackOrderPlacedWorkflow = createWorkflow(
533 "track-order-placed",
534 ({ id }: WorkflowInput) => {
535 const { data: orders } = useQueryGraphStep({
536 entity: "order",
537 fields: [
538 "id",
539 "email",
540 "total",
541 "currency_code",
542 "items.*",
543 "customer.id",
544 "customer.email",
545 "customer.first_name",
546 "customer.last_name",
547 "created_at",
548 ],
549 filters: {
550 id,
551 },
552 })
553
554 const order = transform({
555 order: orders[0],
556 }, ({ order }) => ({
557 orderId: order.id,
558 email: order.email,
559 total: order.total,
560 currency: order.currency_code,
561 items: order.items?.map((item) => ({
562 id: item?.id,
563 title: item?.title,
564 quantity: item?.quantity,
565 variant: item?.variant,
566 unit_price: item?.unit_price,
567 })),
568 customer: {
569 id: order.customer?.id,
570 email: order.customer?.email,
571 firstName: order.customer?.first_name,
572 lastName: order.customer?.last_name,
573 },
574 timestamp: order.created_at,
575 }))
576
577 trackEventStep({
578 event: "order.placed",
579 userId: order.customer.id,
580 properties: order,
581 })
582 }
583 )
584 ```
585
586 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
587
588 It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case an object holding the ID of the order placed.
589
590 In the workflow's constructor function, you:
591
592 1. Retrieve the Medusa order using the `useQueryGraphStep` helper step. This step uses Medusa's [Query](!docs!/learn/fundamentals/query) tool to retrieve data across modules. You pass it the order ID to retrieve.
593 2. Use [transform](!docs!/learn/fundamentals/workflows/variable-manipulation) to prepare the tracking data, as direct data and variable manipulation isn't allowed in workflows. Learn more in the [Data Manipulation](!docs!/learn/fundamentals/workflows/variable-manipulation) documentation.
594 3. Send the tracking event to Segment using the `trackEventStep` you created in the previous step.
595
596 You now have the workflow that tracks the order placement event.
597
598 <Note>
599
600 Refer to the [Workflows](!docs!/learn/fundamentals/workflows) documentation to learn more about workflows and steps.
601
602 </Note>
603
604 ### c. Handle order.placed Event
605
606 Next, you'll create a subscriber that listens to the `order.placed` event and executes the workflow you created in the previous step.
607
608 To create the subscriber, create the file `src/subscribers/order-placed.ts` with the following content:
609
610 export const subscriberHighlights = [
611 ["8", "trackOrderPlacedWorkflow", "Execute the workflow to track the order placement event."],
612 ["17", "event", "Execute subscriber when an order is placed."]
613 ]
614
615 ```ts title="src/subscribers/order-placed.ts" highlights={subscriberHighlights}
616 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
617 import { trackOrderPlacedWorkflow } from "../workflows/track-order-placed"
618
619 export default async function orderPlacedHandler({
620 event: { data },
621 container,
622 }: SubscriberArgs<{ id: string }>) {
623 await trackOrderPlacedWorkflow(container)
624 .run({
625 input: {
626 id: data.id,
627 },
628 })
629 }
630
631 export const config: SubscriberConfig = {
632 event: "order.placed",
633 }
634 ```
635
636 A subscriber file must export:
637
638 1. An asynchronous function, which is the subscriber that is executed when the event is emitted.
639 2. A configuration object that holds the name of the event that the subscriber listens to, which is `order.placed` in this case.
640
641 The subscriber function receives an object as a parameter that has the following properties:
642
643 - `event`: An object that holds the event's data payload. The payload of the `order.placed` event is the ID of the order placed.
644 - `container`: The Medusa container to access the Framework and commerce tools.
645
646 In the subscriber function, you execute the `trackOrderPlacedWorkflow` by invoking it, passing the Medusa container as a parameter. Then, you chain a `run` method, passing it the order ID from the event's data payload as input.
647
648 <Note>
649
650 Refer to the [Events and Subscribers](!docs!/learn/fundamentals/events-and-subscribers) documentation to learn more about creating subscribers.
651
652 </Note>
653
654 ### Test it Out
655
656 You'll now test out the segment integration by placing an order using the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx).
657
658 <Note title="Reminder" forceMultiline>
659
660 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
661
662 ```bash
663 cd apps/storefront
664 ```
665
666 </Note>
667
668 First, run the following command in your `apps/backend` directory to start the Medusa server:
669
670 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
671 npm run dev
672 ```
673
674 Then, run the following command in your Next.js Starter Storefront's directory to start the storefront:
675
676 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
677 npm run dev
678 ```
679
680 In the storefront, add a product to the cart and proceed to checkout. Once you place the order, open the Segment dashboard to view the order event:
681
682 1. Go to Connections > Sources.
683 2. Click on the Node.js source you created earlier.
684 3. Click on the "Debugger" tab at the top of the page.
685 4. You should see the `order.placed` event with the order details.
686
687 <Note>
688
689 The event may take a few seconds to appear in the debugger.
690
691 </Note>
692
693 ![Order Placed Event in Segment Debugger](https://res.cloudinary.com/dza7lstvk/image/upload/v1748259137/Medusa%20Book/CleanShot_2025-05-26_at_14.31.25_2x_xi5p9h.png)
694
695 ---
696
697 ## Track Custom Event
698
699 In your Medusa application, you often need to track custom events that are relevant to your business use case. For example, a B2B business may want to track whenever a user requests a quote.
700
701 In Medusa, you can emit custom events in your workflows when an action occurs. Then, you can create a subscriber that listens to the custom event and executes a workflow to track it in Segment.
702
703 For example, if you have a `createQuoteWorkflow`, you can use Medusa's [emitEventStep](!docs!/learn/fundamentals/events-and-subscribers/emit-event#emit-event-in-a-workflow) to emit a custom event after the quote is created:
704
705 ```ts title="src/workflows/create-quote.ts"
706 import {
707 createWorkflow,
708 } from "@medusajs/framework/workflows-sdk"
709 import {
710 emitEventStep,
711 } from "@medusajs/medusa/core-flows"
712
713 const createQuoteWorkflow = createWorkflow(
714 "create-quote",
715 () => {
716 // ...
717
718 emitEventStep({
719 eventName: "quote.created",
720 data: {
721 id: "123",
722 // other data payload
723 },
724 })
725 }
726 )
727 ```
728
729 You can then create a subscriber that listens to the `quote.created` event and executes a workflow to track it in Segment:
730
731 ```ts title="src/subscribers/quote-created.ts"
732 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
733 import { trackQuoteWorkflow } from "../workflows/track-order-placed"
734
735 export default async function orderPlacedHandler({
736 event: { data },
737 container,
738 }: SubscriberArgs<{ id: string }>) {
739 await trackQuoteWorkflow(container)
740 .run({
741 input: {
742 id: data.id,
743 },
744 })
745 }
746
747 export const config: SubscriberConfig = {
748 event: "quote.created",
749 }
750 ```
751
752 The above example assumes you have a `trackQuoteWorkflow` that tracks the quote creation event in Segment, similar to the [trackOrderPlacedWorkflow](#b-create-track-order-placed-workflow) you created earlier.
753
754 ---
755
756 ## Next Steps
757
758 You've now integrated Segment with your Medusa application and tracked common events like order placement. You can expand on the features in this tutorial to:
759
760 - Track more events in your Medusa application, such as user sign-ups, cart additions, and more. You can refer to the [Events Reference](/references/events) for a full list of events emitted by Medusa.
761 - Emit custom events that are relevant for your business use case, and track them in Segment.
762 - Add destinations to Segment to benefit from the data collected. Segment supports various destinations, such as Google Analytics, Metabase, and more.
763
764 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
765
766 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
767
768 ### Troubleshooting
769
770 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
771
772 ### Getting Help
773
774 If you encounter issues not covered in the troubleshooting guides:
775
776 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
777 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.
778 3. Contact the [sales team](https://medusajs.com/contact/) to get help from the Medusa team.