3.7. Events and Subscribers

In this chapter, you’ll learn about Medusa's event system, and how to handle events with subscribers.

Handle Core Commerce Flows with Events#

When building commerce digital applications, you'll often need to perform an action after a commerce operation is performed. For example, sending an order confirmation email when the customer places an order, or syncing data that's updated in Medusa to a third-party system.

Medusa emits events when core commerce features are performed, and you can listen to and handle these events in asynchronous functions. You can think of Medusa's events like you'd think about webhooks in other commerce platforms, but instead of having to setup separate applications to handle webhooks, your efforts only go into writing the logic right in your Medusa codebase.

You listen to an event in a subscriber, which is an asynchronous function that's executed when its associated event is emitted.

A diagram showcasing an example of how an event is emitted when an order is placed.

Subscribers are useful to perform actions that aren't integral to the original flow. For example, you can handle the order.placed event in a subscriber that sends a confirmation email to the customer. The subscriber has no impact on the original order-placement flow, as it's executed outside of it.

NoteIf the action you're performing is integral to the main flow of the core commerce feature, use workflow hooks instead.

List of Emitted Events#

Find a list of all emitted events in this reference.


How to Create a Subscriber?#

You create a subscriber in a TypeScript or JavaScript file under the src/subscribers directory. The file exports the function to execute and the subscriber's configuration that indicate what event(s) it listens to.

For example, create the file src/subscribers/order-placed.ts with the following content:

Example of subscriber file in the application's directory structure

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

This subscriber file exports:

  • An asynchronous subscriber function that's executed whenever the associated event, which is order.placed is triggered.
  • A configuration object with an event property whose value is the event the subscriber is listening to. You can also pass an array of event names to listen to multiple events in the same subscriber.

The subscriber function receives an object as a parameter that has the following properties:

  • event: An object with the event's details. The data property contains the data payload of the event emitted, which is the order's ID in this case.
  • container: The Medusa container that you can use to resolve registered resources.

In the subscriber function, you use the container to resolve the Logger utility and log a message in the console. Also, assuming you have a workflow that sends an order confirmation email, you execute it in the subscriber.


Test the Subscriber#

To test the subscriber, start the Medusa application:

Then, try placing an order either using Medusa's API routes or the Next.js Storefront. You'll see the following message in the terminal:

Terminal
info:    Processing order.placed which has 1 subscribersSending confirmation email...

The first message indicates that the order.placed event was emitted, and the second one is the message logged from the subscriber.


Event Module#

The subscription and emitting of events is handled by an Event Module, an architectural module that implements the pub/sub functionalities of Medusa's event system.

Medusa provides two Event Modules out of the box:

  • Local Event Module, used by default. It's useful for development, as you don't need additional setup to use it.
  • Redis Event Module, which is useful in production. It uses Redis to implement Medusa's pub/sub events system.

Medusa's architecture also allows you to build a custom Event Module that uses a different service or logic to implement the pub/sub system. Learn how to build an Event Module in this guide.

Was this chapter helpful?
Edit this page