- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
2.8. 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.
In other commerce platforms, it can be tricky to implement this when the commerce operation is performed in the platform's core. You resort to hacky workarounds or extend core services to perform your custom action, which becomes difficult to maintain in the long run and as your application grows.
Medusa's event system removes this complexity by emitting events when core commerce features are performed. Your efforts only go into handling these events in subscribers, which are functions executed asynchronously when an event is emitted.
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.
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:
1import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"2import { ContainerRegistrationKeys } from "@medusajs/framework/utils"3import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"4 5export default async function orderPlacedHandler({6 event: { data },7 container,8}: SubscriberArgs<{ id: string }>) {9 const logger = container.resolve(10 ContainerRegistrationKeys.LOGGER11 )12 13 logger.info("Sending confirmation email...")14 15 await sendOrderConfirmationWorkflow(container)16 .run({17 input: {18 id: data.id,19 },20 })21}22 23export const config: SubscriberConfig = {24 event: `order.placed`,25}
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. Thedata
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:
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.