What is an Event Subscriber?
An event subscriber:- Listens to one or more events from the event bus
- Executes asynchronously when events are triggered
- Has access to the dependency injection container
- Can trigger workflows, send notifications, or perform side effects
- Exports a configuration specifying which events to listen to
Creating a Basic Subscriber
Create the Subscriber File
Create a file in
src/subscribers/ with a default export function and configuration:src/subscribers/brand-created.ts
Subscriber Configuration
Single Event
Multiple Events
With Context
Add metadata to identify the subscriber:Real-World Examples
Payment Webhook Handler
This example shows processing payment webhooks and triggering workflows:src/subscribers/payment-webhook.ts
Send Notifications
Send notifications based on configurable events:src/subscribers/order-notifications.ts
Sync Data to External System
src/subscribers/brand-sync.ts
Event Data Types
Type your event data for type safety:Built-in Events
Medusa emits events for core entities:order.created,order.updated,order.canceledproduct.created,product.updated,product.deletedcustomer.created,customer.updatedpayment.created,payment.capturedfulfillment.created,fulfillment.shipped
Custom Events from Workflows
Emit custom events using workflow hooks:src/workflows/brand/create-brand.ts
src/subscribers/brand-created.ts
Error Handling
Handle errors gracefully to prevent subscriber failures from affecting the main flow:Best Practices
- Keep subscribers focused on a single responsibility
- Use workflows for complex business logic instead of putting it in subscribers
- Handle errors gracefully - don’t let subscriber failures break the main flow
- Use typed event data for type safety
- Add context with
subscriberIdfor easier debugging - Use the logger for debugging and error tracking
- Consider idempotency when handling events (events may be delivered multiple times)
- Don’t perform long-running operations synchronously - use workflows or background jobs
Next Steps
Create Workflows
Build workflows triggered by subscribers
Scheduled Jobs
Create time-based background tasks