MedusaJS Tutorial: Build Your First Ecommerce Store

Okay, here’s a comprehensive article (approximately 5000 words) covering the MedusaJS tutorial and building a basic e-commerce store. I’ve broken it down into sections for clarity and readability, simulating a full, in-depth tutorial.

MedusaJS Tutorial: Build Your First Ecommerce Store (A Comprehensive Guide)

This tutorial will guide you through the process of building a functional e-commerce store using MedusaJS, a powerful open-source headless commerce platform. We’ll cover everything from initial setup to deploying a basic storefront. By the end, you’ll have a working e-commerce backend, understand the core concepts of MedusaJS, and be ready to build a custom frontend.

Table of Contents

  1. Introduction to MedusaJS

    • What is MedusaJS?
    • Why Choose MedusaJS? (Benefits and Features)
    • Headless Commerce Explained
    • MedusaJS Architecture Overview
  2. Prerequisites and Setup

    • Node.js and npm/Yarn Installation
    • PostgreSQL Installation and Setup
    • Redis Installation and Setup
    • Medusa CLI Installation
    • Creating a New Medusa Project
  3. Project Structure and Core Concepts

    • Exploring the Project Directory
    • Understanding Modules (Products, Orders, Customers, etc.)
    • Services, Repositories, and Models
    • The medusa-config.js File
    • Environment Variables
  4. Creating Your First Product

    • Understanding Product Structure in Medusa
    • Using the Admin Dashboard
    • Adding Product Details (Title, Description, Images, etc.)
    • Managing Product Variants (Size, Color, etc.)
    • Setting Prices and Inventory
  5. Setting Up Regions and Shipping

    • Defining Regions (Countries/Areas you ship to)
    • Configuring Shipping Options (Flat Rate, Free Shipping, etc.)
    • Connecting Shipping Providers (Optional – for later expansion)
  6. Managing Orders and Customers

    • Order Lifecycle in Medusa
    • Viewing and Managing Orders in the Admin
    • Customer Accounts and Management
    • Handling Payments (Conceptual – integration later)
  7. Customizing Your Backend (Extending Functionality)

    • Creating Custom Services
    • Adding Custom Endpoints (API Routes)
    • Working with Subscribers (Event Handling)
    • Extending Existing Modules
  8. Building a Basic Storefront (Next.js Example)

    • Introduction to Next.js
    • Setting up a Next.js Project
    • Connecting to the Medusa API
    • Fetching and Displaying Products
    • Creating a Product Details Page
    • Implementing a Simple Cart (Local Storage)
  9. Deployment (Conceptual Overview)

    • Preparing for Deployment
    • Deploying the Medusa Backend (Heroku, DigitalOcean, etc.)
    • Deploying the Next.js Frontend (Vercel, Netlify, etc.)
  10. Further Steps and Advanced Topics

    • Payment Integrations (Stripe, PayPal, etc.)
    • Advanced Shipping Options
    • Customizing the Admin Dashboard
    • Implementing a Search Functionality
    • Using Webhooks
    • Scaling Your Medusa Store

1. Introduction to MedusaJS

What is MedusaJS?

MedusaJS is an open-source, headless commerce engine built on Node.js. It provides a powerful and flexible set of APIs that allow developers to build custom e-commerce experiences. Unlike traditional monolithic e-commerce platforms (like Shopify or Magento), MedusaJS focuses solely on the backend logic, giving you complete control over the frontend and user experience.

Why Choose MedusaJS? (Benefits and Features)

  • Flexibility and Customization: Because it’s headless, you have complete freedom to design your storefront using any technology you prefer (React, Vue, Angular, Svelte, etc.). You’re not locked into a specific template or design system.
  • Developer-Friendly: MedusaJS is built with developers in mind. It has a clean and intuitive API, excellent documentation, and a strong community.
  • Extensible: The modular architecture makes it easy to add new features and integrations. You can create custom plugins or use existing ones from the community.
  • Scalable: MedusaJS is designed to handle high traffic and large product catalogs. Its architecture allows for horizontal scaling.
  • Open-Source: Being open-source means you have transparency, community support, and the ability to contribute to the project.
  • API-First Approach: Everything in MedusaJS is accessible through its API, making it easy to integrate with other systems and services.
  • Built-in Features: MedusaJS comes with a rich set of core features out-of-the-box, including:
    • Product Management
    • Order Management
    • Customer Management
    • Shipping and Fulfillment
    • Payment Integrations (requires additional setup)
    • Discounts and Promotions
    • Admin Dashboard

Headless Commerce Explained

Traditional e-commerce platforms combine the frontend (what the customer sees) and the backend (the logic that powers the store) into a single, tightly coupled system. Headless commerce separates these two concerns.

  • Headless Backend: The backend, like MedusaJS, handles all the business logic: managing products, processing orders, handling payments, etc. It exposes this functionality through APIs.
  • Frontend Freedom: The frontend is a separate application that consumes the backend APIs to display data and interact with the store. This can be a website, a mobile app, or even a smart TV app.

The benefits of headless commerce include:

  • Faster Development: Frontend and backend teams can work independently.
  • Improved Performance: Frontend applications can be optimized for speed without being constrained by the backend.
  • Greater Flexibility: Easily switch frontend technologies or create multiple frontends for different channels.
  • Enhanced Customization: Tailor the user experience to your exact needs.

MedusaJS Architecture Overview

MedusaJS is built on a modular architecture, with core functionalities separated into distinct modules. This makes the codebase easier to understand and maintain, and it allows for easy extension. Key components include:

  • Modules: These are self-contained units of functionality (e.g., Products, Orders, Customers, Shipping).
  • Services: Services contain the business logic for each module. They handle tasks like creating products, processing orders, and managing customers.
  • Repositories: Repositories interact with the database. They provide an abstraction layer for data access.
  • Models: Models define the structure of your data (e.g., the fields of a Product).
  • API Routes: These are the endpoints that your frontend will use to interact with the backend.
  • Subscribers: Subscribers listen for events that occur within MedusaJS (e.g., an order being placed) and can trigger custom actions.
  • Migrations: Database migrations are used to manage changes to the database schema.

2. Prerequisites and Setup

Before we start, you need to have the following installed and configured on your system:

Node.js and npm/Yarn Installation

  • Node.js: MedusaJS requires Node.js version 16 or later. Download the latest LTS (Long Term Support) version from the official Node.js website (https://nodejs.org/).
  • npm (Node Package Manager): npm is usually included with Node.js. You can verify the installation by running npm -v in your terminal.
  • Yarn (Optional): Yarn is an alternative package manager. If you prefer to use Yarn, install it by following the instructions on the official Yarn website (https://yarnpkg.com/).

PostgreSQL Installation and Setup

MedusaJS uses PostgreSQL as its database.

  • Download and Install: Download the appropriate PostgreSQL installer for your operating system from the official PostgreSQL website (https://www.postgresql.org/download/).
  • Installation Steps (General):
    1. Run the installer.
    2. Choose an installation directory.
    3. Set a password for the postgres superuser (remember this password!).
    4. Choose a port (the default is 5432).
    5. Select a locale (optional).
    6. Complete the installation.
  • Create a Database:
    1. Open a terminal or command prompt.
    2. Connect to PostgreSQL using the psql command-line tool (you may need to add the PostgreSQL bin directory to your system’s PATH environment variable):
      bash
      psql -U postgres
    3. Enter the password you set during installation.
    4. Create a new database for your Medusa project:
      sql
      CREATE DATABASE medusa_store;
    5. (Optional, but recommended) Create a dedicated user for your Medusa project:
      sql
      CREATE USER medusa_user WITH PASSWORD 'your_strong_password';
      GRANT ALL PRIVILEGES ON DATABASE medusa_store TO medusa_user;
    6. Exit psql:
      sql
      \q

Redis Installation and Setup

Redis is an in-memory data store used by MedusaJS for caching and job queuing.

  • Download and Install:
    • Windows: You can use the MSOpenTech Redis on Windows release (https://github.com/microsoftarchive/redis/releases) or run Redis within WSL (Windows Subsystem for Linux).
    • macOS: Use Homebrew: brew install redis.
    • Linux: Use your distribution’s package manager (e.g., apt-get install redis-server on Debian/Ubuntu, yum install redis on CentOS/Fedora).
  • Start the Redis Server:
    • Windows: Find the redis-server.exe file in your Redis installation directory and run it.
    • macOS/Linux: The Redis server should start automatically after installation. You can usually manage it with systemctl (e.g., systemctl start redis, systemctl status redis).
  • Verify installation
    bash
    redis-cli ping

    You should see PONG returned.

Medusa CLI Installation

The Medusa CLI (Command-Line Interface) provides tools for creating and managing Medusa projects.

  • Install Globally:
    bash
    npm install -g @medusajs/medusa-cli

    or
    bash
    yarn global add @medusajs/medusa-cli

Creating a New Medusa Project

Now you can create your Medusa project!

  1. Choose a Project Directory: Navigate to the directory where you want to create your project.

  2. Run the medusa new Command:
    bash
    medusa new my-medusa-store --seed

    • my-medusa-store: This is the name of your project directory. You can choose any name you like.
    • --seed: This option seeds the database with some sample data (products, regions, etc.). This is highly recommended for your first project.
  3. Navigate to the Project Directory:
    bash
    cd my-medusa-store

  4. Start the Development Server:
    bash
    medusa develop

This command starts the Medusa development server. It will automatically watch for changes in your code and reload the server when necessary. You should see output in your terminal indicating that the server is running, typically on http://localhost:9000.

The --seed option will populate the database, and you will be prompted to create an admin user during this process. Create a user, and you will be able to access the admin panel.

  1. Access the Admin Panel: Medusa comes with a built-in admin dashboard. You can access it by visiting http://localhost:9000/app in your browser and log in with your credentials. This is where you’ll manage products, orders, customers, and other aspects of your store.

3. Project Structure and Core Concepts

Let’s take a look at the structure of your newly created Medusa project.

Exploring the Project Directory

The my-medusa-store directory contains the following key files and folders:

  • src/: This is where most of your custom code will reside.
    • api/: Contains your API routes (endpoints).
    • models/: Defines the data models for your project.
    • repositories/: Handles database interactions.
    • services/: Contains the business logic.
    • subscribers/: Handles event subscriptions.
    • loaders/: Custom loaders to extend Medusa’s startup process.
    • migrations/: Database migrations.
  • data/:
    • seed.json: Contains sample data that is preloaded into the database for easy testing.
  • medusa-config.js: The main configuration file for your Medusa project.
  • package.json: Defines your project’s dependencies and scripts.
  • .env: Stores environment variables.

Understanding Modules (Products, Orders, Customers, etc.)

MedusaJS is organized into modules, each representing a core e-commerce function. You’ll interact with these modules through their services and API routes. Some of the key modules include:

  • Product: Manages products, variants, options, and images.
  • Order: Handles order creation, fulfillment, and management.
  • Customer: Manages customer accounts and information.
  • Region: Defines shipping regions and their associated settings.
  • ShippingOption: Configures shipping options (e.g., flat rate, free shipping).
  • Cart: Manages shopping carts.
  • PaymentProvider: Handles payment processing (requires integration with a payment provider like Stripe or PayPal).
  • Discount: Manages discounts and promotions.

Services, Repositories, and Models

  • Services: Services are the heart of each module. They contain the business logic and orchestrate interactions between repositories and models. For example, the ProductService handles creating, updating, deleting, and retrieving products. You’ll often extend or override default services to add custom functionality.

  • Repositories: Repositories provide an abstraction layer for interacting with the database. They use TypeORM, an Object-Relational Mapper (ORM), to map your models to database tables. You generally don’t interact directly with repositories; instead, you use services, which in turn use repositories.

  • Models: Models define the structure of your data. They are TypeScript classes that represent the entities in your e-commerce store (e.g., Product, Order, Customer). Models are annotated with TypeORM decorators to define their properties and relationships.

The medusa-config.js File

This file is the central configuration point for your Medusa project. It contains settings for:

  • Database Connection: Specifies the database URL, type, and other connection options.
  • Redis Connection: Specifies the Redis connection URL.
  • Modules: Enables or disables modules.
  • Plugins: Configures installed plugins.
  • API Configuration: Sets the API base URL, CORS settings, and other API-related options.
  • Admin Configuration: Configures the admin dashboard.
  • JWT Secret: Sets the secret key used for JSON Web Token (JWT) authentication.
  • Cookie Secret: Set the secret key used for cookie-based authentication.

Environment Variables

Environment variables are used to store sensitive information (like API keys and database credentials) outside of your codebase. MedusaJS uses the .env file to load environment variables.

  • Create a .env file: If one doesn’t exist, create a .env file in the root of your project.
  • Define Variables: Add your environment variables to the .env file in the following format:
    DATABASE_URL=postgres://medusa_user:your_strong_password@localhost:5432/medusa_store
    REDIS_URL=redis://localhost:6379
    JWT_SECRET=your_super_secret_jwt_key
    COOKIE_SECRET=your_super_secret_cookie_key

    • DATABASE_URL: The connection URL for your PostgreSQL database. Make sure to replace your_strong_password with the actual password you set for the medusa_user.
    • REDIS_URL: The connection URL for your Redis server.
    • JWT_SECRET: A strong, randomly generated secret key for JWT authentication.
    • COOKIE_SECRET: A strong, randomly generated secret key for cookie-based authentication.
  • Access Variables in medusa-config.js: You can access environment variables in your medusa-config.js file using process.env. For example:

    javascript
    module.exports = {
    projectConfig: {
    // ... other configurations
    database_url: process.env.DATABASE_URL,
    redis_url: process.env.REDIS_URL,
    jwt_secret: process.env.JWT_SECRET,
    cookie_secret: process.env.COOKIE_SECRET
    },
    // ... other configurations
    };

Important: Never commit your .env file to version control (e.g., Git). Add it to your .gitignore file. This prevents sensitive information from being exposed.


4. Creating Your First Product

Now that you have your project set up and understand the basic structure, let’s create your first product.

Understanding Product Structure in Medusa

A product in MedusaJS has the following key components:

  • Title: The name of the product.
  • Handle: A unique, URL-friendly identifier for the product (e.g., “my-awesome-tshirt”). This is automatically generated from the title, but you can customize it.
  • Description: A detailed description of the product.
  • Images: A list of images associated with the product.
  • Variants: Different variations of the product (e.g., sizes, colors). Each variant has its own:
    • Title: The title of the variant (e.g., “Small, Red”).
    • SKU (Stock Keeping Unit): A unique identifier for the variant.
    • Prices: Prices for the variant in different currencies.
    • Inventory: The quantity of the variant in stock.
  • Options: The attributes that define the variants (e.g., “Size”, “Color”).
  • Tags: Keywords associated with the product for categorization and search.
  • Type: A way of grouping the product.
  • Collection: Products can be grouped into Collections.
  • Sales Channels: Determine which sales channel the product will be available.

Using the Admin Dashboard

The easiest way to create your first product is through the Medusa admin dashboard.

  1. Access the Admin: Open your browser and go to http://localhost:9000/app.
  2. Log In: Log in with the admin credentials you created during the setup.
  3. Navigate to Products: Click on the “Products” link in the sidebar.
  4. Create a New Product: Click the “New Product” button.

Adding Product Details (Title, Description, Images, etc.)

You’ll now see a form where you can enter the product details:

  • Title: Enter the name of your product (e.g., “Awesome T-Shirt”).
  • Handle: This will be automatically generated, but you can edit it.
  • Subtitle: Enter subtitle of your product.
  • Description: Write a compelling description of your product. You can use Markdown formatting.
  • Images: Click the “Upload Images” button to add images. You can drag and drop images or select them from your file system.
  • Tags: Add relevant tags.
  • Type: Set a type for the product.
  • Collection: Assign the product to a collection.

Managing Product Variants (Size, Color, etc.)

  1. Add Options:

    • Click the “Add Option” button.
    • Enter the name of the option (e.g., “Size”).
    • Add the option values (e.g., “Small”, “Medium”, “Large”).
    • Repeat this process for other options (e.g., “Color”).
  2. Generate Variants:

    • Click the “Generate Variants” button. Medusa will automatically create all possible combinations of your options (e.g., “Small, Red”, “Small, Blue”, “Medium, Red”, etc.).
  3. Edit Variants:

    • Click on a variant to edit its details.
    • Title: You can customize the variant title.
    • SKU: Enter a unique SKU for the variant.
    • Prices:
      • Click the “Add Price” button.
      • Select the currency (e.g., “USD”).
      • Enter the price for the variant in that currency.
      • Repeat for other currencies if needed.
    • Inventory:
      • Enter the quantity of the variant in stock.
      • Enable “Manage Inventory” if you want Medusa to track inventory levels.

Setting Prices and Inventory

As mentioned above, you set prices and inventory at the variant level. Medusa supports multiple currencies, so you can specify prices for different regions. The inventory management feature allows you to track stock levels and prevent overselling.

Once you’ve entered all the product details, click the “Save” button to create your product. You can now view your product in the admin dashboard and, later, on your storefront.


5. Setting Up Regions and Shipping

Before you can start selling products, you need to define the regions you ship to and configure your shipping options.

Defining Regions (Countries/Areas you ship to)

Regions represent the geographic areas where you offer your products and services.

  1. Access Regions: In the admin dashboard, click on “Settings” in the sidebar, then select “Regions”.
  2. Create a New Region: Click the “New Region” button.
  3. Region Details:
    • Name: Enter the name of the region (e.g., “United States”, “Europe”).
    • Currency Code: Select the currency used in this region (e.g., “USD”, “EUR”).
    • Tax Rate: Enter the tax rate for this region (e.g., 0.07 for 7% sales tax).
    • Countries: Select the countries that belong to this region. You can select multiple countries.
    • Payment Providers: Select the payment providers that are available in this region (you’ll configure these later).
    • Fulfillment Providers: Select the fulfillment providers that are available in this region (you’ll configure these later).
  4. Save: Click the “Save” button to create the region.

Configuring Shipping Options (Flat Rate, Free Shipping, etc.)

Shipping options define the different ways you ship your products to customers.

  1. Access Shipping Options: In the admin dashboard, go to “Settings” -> “Regions”. Select the region you want to configure. Then, click on the “Shipping Options” tab.
  2. Create a New Shipping Option: Click the “New Shipping Option” button.
  3. Shipping Option Details:
    • Name: Enter the name of the shipping option (e.g., “Standard Shipping”, “Express Shipping”).
    • Region: This should be pre-selected based on the current region.
    • Data:
      • This field allows for additional information to be provided, such as: price_type: which can be flat_rate or calculated.
      • amount: Enter the price for the shipping option (e.g., 5.00 for $5.00). If you’re using a calculated shipping provider, you might leave this blank.
    • Requirements:
      • You can set minimum and maximum order subtotals for the shipping option to be available. For example, you could offer free shipping for orders over $50.
  4. Save: Click the “Save” button to create the shipping option.

Connecting Shipping Providers (Optional – for later expansion)

MedusaJS supports integrations with various shipping providers (e.g., Shippo, EasyPost). These integrations allow you to automatically calculate shipping rates, generate shipping labels, and track shipments. This is a more advanced topic that we’ll cover briefly in the “Further Steps” section. For now, you can set up basic flat-rate shipping options.


6. Managing Orders and Customers

Once your store is set up and you start receiving orders, you’ll need to manage them efficiently.

Order Lifecycle in Medusa

An order in MedusaJS goes through several stages:

  1. Created: The order is created when a customer completes the checkout process.
  2. Requires Action: Some orders might require additional actions to be performed.
  3. Payment Authorized: The customer’s payment is authorized (but not yet captured).
  4. Payment Captured: The payment is captured.
  5. Fulfillment Created: The order should be fulfilled.
  6. Shipped: The order has been shipped.
  7. Delivered: The order has been delivered to the customer.
  8. Completed: The order is complete.
  9. Returned: The order was returned.
  10. Canceled: The order has been canceled.

Viewing and Managing Orders in the Admin

  1. Access Orders: In the admin dashboard, click on “Orders” in the sidebar.
  2. Order List: You’ll see a list of all orders, with their status, customer, total amount, and other details.
  3. View Order Details: Click on an order to view its full details.
  4. Manage Order: From the order details page, you can:
    • Capture Payment: If the payment hasn’t been captured yet, you can capture it.
    • Create Fulfillment: Start the fulfillment process.
    • Mark as Shipped: Update the order status when it’s shipped.
    • Mark as Delivered: Update the order status when it’s delivered.
    • Cancel Order: Cancel the order.
    • Add Notes: Add internal notes about the order.

Customer Accounts and Management

MedusaJS allows customers to create accounts, which can store their shipping addresses, order history, and other information.

  1. Access Customers: In the admin dashboard, click on “Customers” in the sidebar.
  2. Customer List: You’ll see a list of all registered customers.
  3. View Customer Details: Click on a customer to view their information, including:
    • Email: The customer’s email address.
    • Name: The customer’s name.
    • Orders: A list of the customer’s orders.
    • Addresses: The customer’s saved shipping and billing addresses.

Handling Payments (Conceptual – integration later)

MedusaJS doesn’t directly handle payment processing. Instead, it integrates with payment providers like Stripe, PayPal, and others. You’ll need to create an account with a payment provider and configure the integration in MedusaJS. This is a more advanced topic that we’ll touch on in the “Further Steps” section. For now, you can simulate orders and mark them as paid manually in the admin dashboard.


7. Customizing Your Backend (Extending Functionality)

One of the key advantages of MedusaJS is its extensibility. You can customize the backend to add new features, modify existing behavior, and integrate with third-party services.

Creating Custom Services

Services are where you implement your custom business logic. To create a custom service:

  1. Create a Service File: Create a new file in the src/services directory. The filename should follow the convention my-custom-service.ts (or .js).

  2. Define the Service Class: Create a TypeScript class that extends the TransactionBaseService class.

    “`typescript
    import { TransactionBaseService } from “@medusajs/medusa”;
    import { EntityManager } from “typeorm”;

    class MyCustomService extends TransactionBaseService {
    protected manager: EntityManager;
    protected transactionManager: EntityManager | undefined;

    constructor(container, options?) {
    super(container);
    this.manager = container.manager; // Access to the entity manager
    }

    async myCustomMethod(data: any): Promise {
    // Your custom logic here
    console.log(“My custom method was called with data:”, data);

    // Example: Interact with the database
    // const productRepository = this.manager.getCustomRepository(ProductRepository);
    // const product = await productRepository.findOne({ where: { id: data.productId } });
    
    return { message: "Success!" };
    

    }
    }

    export default MyCustomService;
    “`

  3. Register Service
    To make the service available to the dependency injection container, you have to register it using a loader.
    Create src/loaders/my-service.ts with the following:

    “`typescript
    import { asClass, AwilixContainer } from “awilix”;

    export default async function myCustomServiceLoader({ container }: { container: AwilixContainer }) {
    container.register({
    myCustomService: asClass(MyCustomService).singleton()
    });
    }

    “`

    Update medusa-config.js: Add the loader file’s path into loaders:

    javascript
    loaders: [
    // other loaders
    "./src/loaders/my-service",
    ],

    Now, it can be injected to other resources.

  4. Use the Service: You can now inject your custom service into other services, API routes, or subscribers using dependency injection. For example, in an API route:

    “`typescript
    import { Request, Response } from “express”;

    export default async (req: Request, res: Response) => {
    const myCustomService = req.scope.resolve(“myCustomService”);
    const result = await myCustomService.myCustomMethod(req.body);
    res.json(result);
    };
    “`

Adding Custom Endpoints (API Routes)

To create custom API endpoints:

  1. Create an API Route File: Create a new file in the src/api directory. For example, src/api/my-custom-route.ts.

  2. Define the Route Handler: Export a default function that handles the request.

    “`typescript
    import { Request, Response } from “express”;

    export default async (req: Request, res: Response) => {
    try {
    // Your custom logic here
    // Access request data: req.body, req.query, req.params
    // Access Medusa services: req.scope.resolve(“productService”)

    res.status(200).json({ message: "Hello from my custom route!" });
    

    } catch (error) {
    res.status(500).json({ error: error.message });
    }
    };

    export const config = {
    api: {
    bodyParser: true, // Enable body parsing if needed
    },
    };
    “`

  3. Register the Route: MedusaJS uses a file-based routing system. The filename determines the route path. By default Medusa uses /store and /admin for its APIs, for example, to register the custom endpoint created above on /store/custom-route you can create the file src/api/routes/store/custom-route.ts and import the route handler.

    “`typescript
    import { Router } from “express”;
    import myCustomRouteHandler from “../../my-custom-route”; //Import created above

    const router = Router();

    export default (app) => {
    app.use(“/store/custom-route”, router);
    router.post(“/”, myCustomRouteHandler);
    }
    ``
    Now, accessing
    /store/custom-routewill trigger yourmyCustomRouteHandler` function. You can use different HTTP methods (GET, POST, PUT, DELETE) to define different actions for your route.

Working with Subscribers (Event Handling)

Subscribers allow you to react to events that occur within MedusaJS. For example, you could send a welcome email when a new customer registers or update an external system when an order is placed.

  1. Create a Subscriber File: Create a new file in the src/subscribers directory (e.g., src/subscribers/order-placed.ts).

  2. Define the Subscriber Class: Create a class that subscribes to a specific event.

    “`typescript
    import { EventBusService } from “@medusajs/medusa”;

    class OrderPlacedSubscriber {
    protected readonly eventBusService_: EventBusService

    constructor({ eventBusService }) {
    this.eventBusService_ = eventBusService;

    this.eventBusService_.subscribe("order.placed", this.handleOrderPlaced);
    

    }

    handleOrderPlaced = async (data: Record) => {
    // Your custom logic here
    console.log(“Order placed:”, data);

    // Example: Send an email notification
    // const emailService = this.container.resolve("emailService");
    // await emailService.sendOrderConfirmation(data.orderId);
    

    };
    }

    export default OrderPlacedSubscriber;
    “`

    • The constructor subscribes to the order.placed event using the eventBusService. You can find a list of available events in the MedusaJS documentation.
    • The handleOrderPlaced method is called whenever an order is placed. It receives the event data as an argument.
  3. Register the Subscriber: Similar to the service, the subscriber must be registered.
    Create src/loaders/order-subscriber.ts:

    “`typescript
    import { asClass, AwilixContainer } from “awilix”;

    export default async function orderSubscriberLoader({ container }: { container: AwilixContainer }) {
    container.register({
    orderPlacedSubscriber: asClass(OrderPlacedSubscriber).singleton()
    });
    }
    ``
    Update
    medusa-config.js`:

    javascript
    loaders: [
    // other loaders
    "./src/loaders/order-subscriber",
    ],

    4

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top