Medusa.js Development
Overview
Build and extend headless e-commerce backends with Medusa.js using custom services, subscribers (event handlers), API route extensions, custom entities with migrations, and module architecture. This skill covers Medusa v2 project setup, the dependency injection container, custom workflows, admin UI extensions, and integration patterns for connecting Medusa to storefronts, ERPs, and payment providers.
When to Use This Skill
- When setting up a new headless e-commerce backend with Medusa
- When building custom business logic as Medusa services and workflows
- When extending the Medusa API with custom endpoints for storefront or admin use
- When implementing event-driven automation via subscribers (e.g., send email on order placed)
- When integrating external systems (ERP, CMS, fulfillment) with Medusa
Prerequisites & Platform Notes
This skill is written for custom/headless storefronts (Node.js, Python, or similar backend). The code examples use TypeScript/Node.js and can be adapted to any stack.
Shopify: Shopify Hydrogen is Shopify's headless framework. MACH/composable patterns apply when using Shopify as the commerce backend with a custom frontend, or when mixing Shopify with other best-of-breed services.
WooCommerce: WooCommerce can serve as a headless backend via its REST API and WPGraphQL. These patterns apply when decoupling the frontend from WordPress.
Magento: Magento's GraphQL API and PWA Studio support headless architectures. These composable patterns apply to Magento as a backend service in a MACH stack.
You'll need:
- Node.js 18+ (or adapt to your backend language)
- PostgreSQL (or your preferred relational database)
- Redis for caching/queues
- Stripe account and API keys
- An email sending service (SendGrid, AWS SES, or Postmark)
Core Instructions
Set up a Medusa project
# Create a new Medusa project
npx create-medusa-app@latest my-store
# Project structure (Medusa v2)
# my-store/
# ├── src/
# │ ├── api/ # Custom API routes
# │ ├── jobs/ # Scheduled jobs
# │ ├── links/ # Module links
# │ ├── modules/ # Custom modules
# │ ├── subscribers/ # Event subscribers
# │ └── workflows/ # Custom workflows
# ├── medusa-config.ts
# └── package.json
# Start the development server
npx medusa develop
Configure medusa-config.ts:
import { defineConfig, loadEnv } from '@medusajs/framework/utils';
loadEnv(process.env.NODE_ENV || 'development', process.cwd());
export default defineConfig({
projectConfig: {
databaseUrl: process.env.DATABASE_URL,
redisUrl: process.env.REDIS_URL,
http: {
storeCors: process.env.STORE_CORS || 'http://localhost:8000',
adminCors: process.env.ADMIN_CORS || 'http://localhost:9000',
authCors: process.env.AUTH_CORS || 'http://localhost:8000,http://localhost:9000',
},
},
modules: [
// Register custom modules here
],
});
Create a custom module with a service
// src/modules/loyalty/service.ts
import { MedusaService } from '@medusajs/framework/utils';
import { LoyaltyPoints } from './models/loyalty-points';
class LoyaltyModuleService extends MedusaService({
LoyaltyPoints,
}) {
async awardPoints(customerId: string, points: number, reason: string) {
return await this.createLoyaltyPointss({
customer_id: customerId,
points,
reason,
type: 'earned',
});
}
async redeemPoints(customerId: string, points: number) {
const balance = await this.getBalance(customerId);
if (balance < points) {
throw new Error(`Insufficient points. Balance: ${balance}, requested: ${points}`);
}
return await this.createLoyaltyPointss({
customer_id: customerId,
points: -points,
reason: 'redeemed',
type: 'redeemed',
});
}
async getBalance(customerId: string): Promise<number> {
const records = await this.listLoyaltyPointss({
customer_id: customerId,
});
return records.reduce((sum, r) => sum + r.points, 0);
}
}
export default LoyaltyModuleService;
Define the data model:
// src/modules/loyalty/models/loyalty-points.ts
import { model } from '@medusajs/framework/utils';
export const LoyaltyPoints = model.define('loyalty_points', {
id: model.id().primaryKey(),
customer_id: model.text(),
points: model.number(),
reason: model.text(),
type: model.enum(['earned', 'redeemed', 'adjusted']),
});
Register the module:
// src/modules/loyalty/index.ts
import LoyaltyModuleService from './service';
import { Module } from '@medusajs/framework/utils';
export const LOYALTY_MODULE = 'loyaltyModuleService';
export default Module(LOYALTY_MODULE, {
service: LoyaltyModuleService,
});
Create event subscribers
// src/subscribers/order-placed.ts
import type { SubscriberArgs, SubscriberConfig } from '@medusajs/framework';
import { Modules } from '@medusajs/framework/utils';
import { LOYALTY_MODULE } from '../modules/loyalty';
export default async function orderPlacedHandler({
event,
container,
}: SubscriberArgs<{ id: string }>) {
const orderId = event.data.id;
const orderService = container.resolve(Modules.ORDER);
const loyaltyService = container.resolve(LOYALTY_MODULE);
const logger = container.resolve('logger');
try {
const order = await orderService.retrieveOrder(orderId, {
relations: ['items'],
});
// Award 1 point per dollar spent
const pointsToAward = Math.floor(order.total / 100);
if (order.customer_id && pointsToAward > 0) {
await loyaltyService.awardPoints(
order.customer_id,
pointsToAward,
`Order ${order.display_id}`
);
logger.info(`Awarded ${pointsToAward} loyalty points for order ${order.display_id}`);
}
} catch (error) {
logger.error(`Failed to award loyalty points for order ${orderId}: ${error.message}`);
}
}
export const config: SubscriberConfig = {
event: 'order.placed',
};
Add custom API routes
// src/api/store/loyalty/route.ts
import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http';
import { LOYALTY_MODULE } from '../../../modules/loyalty';
// GET /store/loyalty — get current customer's loyalty balance
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const customerId = req.auth_context?.actor_id;
if (!customerId) {
return res.status(401).json({ message: 'Authentication required' });
}
const loyaltyService = req.scope.resolve(LOYALTY_MODULE);
const balance = await loyaltyService.getBalance(customerId);
const history = await loyaltyService.listLoyaltyPointss(
{ customer_id: customerId },
{ order: { created_at: 'DESC' }, take: 20 }
);
res.json({ balance, history });
}
// POST /store/loyalty/redeem — redeem points for a discount
export async function POST(req: MedusaRequest, res: MedusaResponse) {
const customerId = req.auth_context?.actor_id;
if (!customerId) {
return res.status(401).json({ message: 'Authentication required' });
}
const { points } = req.body as { points: number };
if (!points || points <= 0) {
return res.status(400).json({ message: 'Invalid points amount' });
}
const loyaltyService = req.scope.resolve(LOYALTY_MODULE);
try {
const record = await loyaltyService.redeemPoints(customerId, points);
const newBalance = await loyaltyService.getBalance(customerId);
res.json({ redeemed: points, newBalance, record });
} catch (error) {
res.status(400).json({ message: error.message });
}
}
Build custom workflows
// src/workflows/award-loyalty-points.ts
import {
createWorkflow,
createStep,
StepResponse,
} from '@medusajs/framework/workflows-sdk';
import { LOYALTY_MODULE } from '../modules/loyalty';
const validatePointsStep = createStep(
'validate-points',
async ({ customerId, points }: { customerId: string; points: number }) => {
if (!customerId) throw new Error('Customer ID required');
if (points <= 0) throw new Error('Points must be positive');
return new StepResponse({ customerId, points });
}
);
const awardPointsStep = createStep(
'award-points',
async (
{ customerId, points, reason }: { customerId: string; points: number; reason: string },
{ container }
) => {
const loyaltyService = container.resolve(LOYALTY_MODULE);
const record = await loyaltyService.awardPoints(customerId, points, reason);
return new StepResponse(record, { recordId: record.id });
},
// Compensation function for rollback
async ({ recordId }, { container }) => {
const loyaltyService = container.resolve(LOYALTY_MODULE);
await loyaltyService.deleteLoyaltyPoints(recordId);
}
);
export const awardLoyaltyPointsWorkflow = createWorkflow(
'award-loyalty-points',
(input: { customerId: string; points: number; reason: string }) => {
const validated = validatePointsStep(input);
const record = awardPointsStep({
customerId: validated.customerId,
points: validated.points,
reason: input.reason,
});
return record;
}
);
Create a scheduled job
// src/jobs/expire-loyalty-points.ts
import type { MedusaContainer } from '@medusajs/framework/types';
import { LOYALTY_MODULE } from '../modules/loyalty';
export default async function expireLoyaltyPointsJob(container: MedusaContainer) {
const loyaltyService = container.resolve(LOYALTY_MODULE);
const logger = container.resolve('logger');
// Find points older than 12 months
const expirationDate = new Date();
expirationDate.setFullYear(expirationDate.getFullYear() - 1);
const expiredRecords = await loyaltyService.listLoyaltyPointss({
type: 'earned',
created_at: { $lt: expirationDate },
});
let expiredCount = 0;
for (const record of expiredRecords) {
if (record.points > 0) {
await loyaltyService.createLoyaltyPointss({
customer_id: record.customer_id,
points: -record.points,
reason: `Expired: original from ${record.created_at}`,
type: 'adjusted',
});
expiredCount++;
}
}
logger.info(`Expired ${expiredCount} loyalty point records.`);
}
export const config = {
name: 'expire-loyalty-points',
schedule: '0 2 * * *', // Daily at 2 AM
};
Examples
Connecting a Next.js storefront
// storefront/lib/medusa-client.ts
import Medusa from '@medusajs/js-sdk';
const medusa = new Medusa({
baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || 'http://localhost:9000',
auth: {
type: 'session',
},
});
// Fetch products for a collection page
export async function getProducts(collectionId?: string) {
const { products, count } = await medusa.store.product.list({
collection_id: collectionId ? [collectionId] : undefined,
limit: 24,
fields: '+variants.calculated_price',
});
return { products, count };
}
// Add item to cart
export async function addToCart(cartId: string, variantId: string, quantity: number) {
const { cart } = await medusa.store.cart.createLineItem(cartId, {
variant_id: variantId,
quantity,
});
return cart;
}
// Fetch loyalty balance (custom endpoint)
export async function getLoyaltyBalance() {
const response = await fetch(
`${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/loyalty`,
{ credentials: 'include' }
);
if (!response.ok) throw new Error('Failed to fetch loyalty balance');
return response.json();
}
Custom payment provider module
// src/modules/custom-payment/service.ts
import {
AbstractPaymentProvider,
} from '@medusajs/framework/utils';
import type {
CreatePaymentProviderSession,
UpdatePaymentProviderSession,
ProviderWebhookPayload,
WebhookActionResult,
} from '@medusajs/framework/types';
class CustomPaymentProviderService extends AbstractPaymentProvider<{}> {
static identifier = 'custom-payment';
async initiatePayment(
data: CreatePaymentProviderSession
): Promise<Record<string, unknown>> {
// Call your payment gateway's API to create a payment session
const response = await fetch('https://api.custompay.com/v1/sessions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: data.amount,
currency: data.currency_code,
metadata: { medusa_cart_id: data.context.cart_id },
}),
});
const session = await response.json();
return { session_id: session.id, client_token: session.client_token };
}
async authorizePayment(
paymentSessionData: Record<string, unknown>
): Promise<{ status: string; data: Record<string, unknown> }> {
const sessionId = paymentSessionData.session_id as string;
const response = await fetch(
`https://api.custompay.com/v1/sessions/${sessionId}`,
{
headers: { 'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}` },
}
);
const session = await response.json();
return {
status: session.status === 'paid' ? 'authorized' : 'pending',
data: { ...paymentSessionData, gateway_status: session.status },
};
}
async capturePayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown>> {
const sessionId = paymentSessionData.session_id as string;
await fetch(`https://api.custompay.com/v1/sessions/${sessionId}/capture`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}` },
});
return { ...paymentSessionData, captured: true };
}
async refundPayment(
paymentSessionData: Record<string, unknown>,
refundAmount: number
): Promise<Record<string, unknown>> {
const sessionId = paymentSessionData.session_id as string;
await fetch(`https://api.custompay.com/v1/sessions/${sessionId}/refund`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ amount: refundAmount }),
});
return { ...paymentSessionData, refunded_amount: refundAmount };
}
async cancelPayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown>> {
return { ...paymentSessionData, cancelled: true };
}
async deletePayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown>> {
return {};
}
async getPaymentStatus(
paymentSessionData: Record<string, unknown>
): Promise<string> {
return (paymentSessionData.gateway_status as string) || 'pending';
}
async getWebhookActionAndData(
payload: ProviderWebhookPayload
): Promise<WebhookActionResult> {
const event = JSON.parse(payload.rawData as string);
switch (event.type) {
case 'payment.captured':
return { action: 'captured', data: { session_id: event.session_id } };
case 'payment.failed':
return { action: 'failed', data: { session_id: event.session_id } };
default:
return { action: 'not_supported' };
}
}
}
export default CustomPaymentProviderService;
Best Practices
- Use the module system for encapsulation -- each domain (loyalty, custom fulfillment, analytics) should be its own module with its own service, models, and migrations
- Always add compensation functions to workflow steps -- if a step can fail, the compensation function rolls back the previous step's side effects for clean error recovery
- Resolve dependencies from the container, not with imports -- use
container.resolve() for services to respect the DI configuration and enable testing
- Use subscribers for side effects, not core logic -- subscribers should trigger notifications, sync external systems, and log events; keep order processing in workflows
- Validate API input with Zod -- define Zod schemas for request bodies and use middleware to validate before the handler runs
- Write migrations for schema changes -- never modify the database manually; use Medusa's migration system so changes are reproducible across environments
- Use the Medusa Admin SDK for admin extensions -- extend the admin dashboard with custom widgets using the
@medusajs/admin-sdk package instead of building separate UIs
- Pin your Medusa version -- Medusa v2 is evolving rapidly; lock the version in
package.json and test before upgrading
Common Pitfalls
| Problem |
Solution |
| Custom module not found at runtime |
Register it in medusa-config.ts under the modules array and run npx medusa db:migrate to apply any model changes |
| Subscriber fires but data is stale |
Subscribers run asynchronously; re-fetch the entity inside the subscriber handler rather than relying on event payload data |
| API route returns 404 |
Ensure the file path matches the URL pattern: src/api/store/loyalty/route.ts maps to /store/loyalty; check for missing export on the handler function |
| Workflow step fails without rollback |
Every step that has side effects needs a compensation function as the second argument to createStep |
| Database migration conflicts after merge |
Run npx medusa db:migrate after pulling changes; if migrations conflict, generate a new migration that resolves the diff |
| CORS errors from storefront |
Configure storeCors in medusa-config.ts to include your storefront's origin URL including the port |
Related Skills
- @product-data-modeling
- @stripe-integration
- @ecommerce-caching
- @ecommerce-seo
- @erp-integration
1---2name: medusa-development3description: Extend the open-source Medusa commerce platform with custom services, event subscribers, and API endpoints for unique business requirements4---56# Medusa.js Development78## Overview910Build and extend headless e-commerce backends with Medusa.js using custom services, subscribers (event handlers), API route extensions, custom entities with migrations, and module architecture. This skill covers Medusa v2 project setup, the dependency injection container, custom workflows, admin UI extensions, and integration patterns for connecting Medusa to storefronts, ERPs, and payment providers.1112## When to Use This Skill1314- When setting up a new headless e-commerce backend with Medusa15- When building custom business logic as Medusa services and workflows16- When extending the Medusa API with custom endpoints for storefront or admin use17- When implementing event-driven automation via subscribers (e.g., send email on order placed)18- When integrating external systems (ERP, CMS, fulfillment) with Medusa1920## Prerequisites & Platform Notes2122**This skill is written for custom/headless storefronts** (Node.js, Python, or similar backend). The code examples use TypeScript/Node.js and can be adapted to any stack.2324**Shopify**: Shopify Hydrogen is Shopify's headless framework. MACH/composable patterns apply when using Shopify as the commerce backend with a custom frontend, or when mixing Shopify with other best-of-breed services.25**WooCommerce**: WooCommerce can serve as a headless backend via its REST API and WPGraphQL. These patterns apply when decoupling the frontend from WordPress.26**Magento**: Magento's GraphQL API and PWA Studio support headless architectures. These composable patterns apply to Magento as a backend service in a MACH stack.2728**You'll need**:29- Node.js 18+ (or adapt to your backend language)30- PostgreSQL (or your preferred relational database)31- Redis for caching/queues32- Stripe account and API keys33- An email sending service (SendGrid, AWS SES, or Postmark)3435## Core Instructions36371. **Set up a Medusa project**3839 ```bash40 # Create a new Medusa project41 npx create-medusa-app@latest my-store4243 # Project structure (Medusa v2)44 # my-store/45 # ├── src/46 # │ ├── api/ # Custom API routes47 # │ ├── jobs/ # Scheduled jobs48 # │ ├── links/ # Module links49 # │ ├── modules/ # Custom modules50 # │ ├── subscribers/ # Event subscribers51 # │ └── workflows/ # Custom workflows52 # ├── medusa-config.ts53 # └── package.json5455 # Start the development server56 npx medusa develop57 ```5859 Configure `medusa-config.ts`:60 ```typescript61 import { defineConfig, loadEnv } from '@medusajs/framework/utils';6263 loadEnv(process.env.NODE_ENV || 'development', process.cwd());6465 export default defineConfig({66 projectConfig: {67 databaseUrl: process.env.DATABASE_URL,68 redisUrl: process.env.REDIS_URL,69 http: {70 storeCors: process.env.STORE_CORS || 'http://localhost:8000',71 adminCors: process.env.ADMIN_CORS || 'http://localhost:9000',72 authCors: process.env.AUTH_CORS || 'http://localhost:8000,http://localhost:9000',73 },74 },75 modules: [76 // Register custom modules here77 ],78 });79 ```80812. **Create a custom module with a service**8283 ```typescript84 // src/modules/loyalty/service.ts85 import { MedusaService } from '@medusajs/framework/utils';86 import { LoyaltyPoints } from './models/loyalty-points';8788 class LoyaltyModuleService extends MedusaService({89 LoyaltyPoints,90 }) {91 async awardPoints(customerId: string, points: number, reason: string) {92 return await this.createLoyaltyPointss({93 customer_id: customerId,94 points,95 reason,96 type: 'earned',97 });98 }99100 async redeemPoints(customerId: string, points: number) {101 const balance = await this.getBalance(customerId);102 if (balance < points) {103 throw new Error(`Insufficient points. Balance: ${balance}, requested: ${points}`);104 }105106 return await this.createLoyaltyPointss({107 customer_id: customerId,108 points: -points,109 reason: 'redeemed',110 type: 'redeemed',111 });112 }113114 async getBalance(customerId: string): Promise<number> {115 const records = await this.listLoyaltyPointss({116 customer_id: customerId,117 });118 return records.reduce((sum, r) => sum + r.points, 0);119 }120 }121122 export default LoyaltyModuleService;123 ```124125 Define the data model:126 ```typescript127 // src/modules/loyalty/models/loyalty-points.ts128 import { model } from '@medusajs/framework/utils';129130 export const LoyaltyPoints = model.define('loyalty_points', {131 id: model.id().primaryKey(),132 customer_id: model.text(),133 points: model.number(),134 reason: model.text(),135 type: model.enum(['earned', 'redeemed', 'adjusted']),136 });137 ```138139 Register the module:140 ```typescript141 // src/modules/loyalty/index.ts142 import LoyaltyModuleService from './service';143 import { Module } from '@medusajs/framework/utils';144145 export const LOYALTY_MODULE = 'loyaltyModuleService';146147 export default Module(LOYALTY_MODULE, {148 service: LoyaltyModuleService,149 });150 ```1511523. **Create event subscribers**153154 ```typescript155 // src/subscribers/order-placed.ts156 import type { SubscriberArgs, SubscriberConfig } from '@medusajs/framework';157 import { Modules } from '@medusajs/framework/utils';158 import { LOYALTY_MODULE } from '../modules/loyalty';159160 export default async function orderPlacedHandler({161 event,162 container,163 }: SubscriberArgs<{ id: string }>) {164 const orderId = event.data.id;165166 const orderService = container.resolve(Modules.ORDER);167 const loyaltyService = container.resolve(LOYALTY_MODULE);168 const logger = container.resolve('logger');169170 try {171 const order = await orderService.retrieveOrder(orderId, {172 relations: ['items'],173 });174175 // Award 1 point per dollar spent176 const pointsToAward = Math.floor(order.total / 100);177178 if (order.customer_id && pointsToAward > 0) {179 await loyaltyService.awardPoints(180 order.customer_id,181 pointsToAward,182 `Order ${order.display_id}`183 );184 logger.info(`Awarded ${pointsToAward} loyalty points for order ${order.display_id}`);185 }186 } catch (error) {187 logger.error(`Failed to award loyalty points for order ${orderId}: ${error.message}`);188 }189 }190191 export const config: SubscriberConfig = {192 event: 'order.placed',193 };194 ```1951964. **Add custom API routes**197198 ```typescript199 // src/api/store/loyalty/route.ts200 import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http';201 import { LOYALTY_MODULE } from '../../../modules/loyalty';202203 // GET /store/loyalty — get current customer's loyalty balance204 export async function GET(req: MedusaRequest, res: MedusaResponse) {205 const customerId = req.auth_context?.actor_id;206207 if (!customerId) {208 return res.status(401).json({ message: 'Authentication required' });209 }210211 const loyaltyService = req.scope.resolve(LOYALTY_MODULE);212 const balance = await loyaltyService.getBalance(customerId);213 const history = await loyaltyService.listLoyaltyPointss(214 { customer_id: customerId },215 { order: { created_at: 'DESC' }, take: 20 }216 );217218 res.json({ balance, history });219 }220221 // POST /store/loyalty/redeem — redeem points for a discount222 export async function POST(req: MedusaRequest, res: MedusaResponse) {223 const customerId = req.auth_context?.actor_id;224225 if (!customerId) {226 return res.status(401).json({ message: 'Authentication required' });227 }228229 const { points } = req.body as { points: number };230231 if (!points || points <= 0) {232 return res.status(400).json({ message: 'Invalid points amount' });233 }234235 const loyaltyService = req.scope.resolve(LOYALTY_MODULE);236237 try {238 const record = await loyaltyService.redeemPoints(customerId, points);239 const newBalance = await loyaltyService.getBalance(customerId);240 res.json({ redeemed: points, newBalance, record });241 } catch (error) {242 res.status(400).json({ message: error.message });243 }244 }245 ```2462475. **Build custom workflows**248249 ```typescript250 // src/workflows/award-loyalty-points.ts251 import {252 createWorkflow,253 createStep,254 StepResponse,255 } from '@medusajs/framework/workflows-sdk';256 import { LOYALTY_MODULE } from '../modules/loyalty';257258 const validatePointsStep = createStep(259 'validate-points',260 async ({ customerId, points }: { customerId: string; points: number }) => {261 if (!customerId) throw new Error('Customer ID required');262 if (points <= 0) throw new Error('Points must be positive');263 return new StepResponse({ customerId, points });264 }265 );266267 const awardPointsStep = createStep(268 'award-points',269 async (270 { customerId, points, reason }: { customerId: string; points: number; reason: string },271 { container }272 ) => {273 const loyaltyService = container.resolve(LOYALTY_MODULE);274 const record = await loyaltyService.awardPoints(customerId, points, reason);275 return new StepResponse(record, { recordId: record.id });276 },277 // Compensation function for rollback278 async ({ recordId }, { container }) => {279 const loyaltyService = container.resolve(LOYALTY_MODULE);280 await loyaltyService.deleteLoyaltyPoints(recordId);281 }282 );283284 export const awardLoyaltyPointsWorkflow = createWorkflow(285 'award-loyalty-points',286 (input: { customerId: string; points: number; reason: string }) => {287 const validated = validatePointsStep(input);288 const record = awardPointsStep({289 customerId: validated.customerId,290 points: validated.points,291 reason: input.reason,292 });293 return record;294 }295 );296 ```2972986. **Create a scheduled job**299300 ```typescript301 // src/jobs/expire-loyalty-points.ts302 import type { MedusaContainer } from '@medusajs/framework/types';303 import { LOYALTY_MODULE } from '../modules/loyalty';304305 export default async function expireLoyaltyPointsJob(container: MedusaContainer) {306 const loyaltyService = container.resolve(LOYALTY_MODULE);307 const logger = container.resolve('logger');308309 // Find points older than 12 months310 const expirationDate = new Date();311 expirationDate.setFullYear(expirationDate.getFullYear() - 1);312313 const expiredRecords = await loyaltyService.listLoyaltyPointss({314 type: 'earned',315 created_at: { $lt: expirationDate },316 });317318 let expiredCount = 0;319 for (const record of expiredRecords) {320 if (record.points > 0) {321 await loyaltyService.createLoyaltyPointss({322 customer_id: record.customer_id,323 points: -record.points,324 reason: `Expired: original from ${record.created_at}`,325 type: 'adjusted',326 });327 expiredCount++;328 }329 }330331 logger.info(`Expired ${expiredCount} loyalty point records.`);332 }333334 export const config = {335 name: 'expire-loyalty-points',336 schedule: '0 2 * * *', // Daily at 2 AM337 };338 ```339340## Examples341342### Connecting a Next.js storefront343344```typescript345// storefront/lib/medusa-client.ts346import Medusa from '@medusajs/js-sdk';347348const medusa = new Medusa({349 baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || 'http://localhost:9000',350 auth: {351 type: 'session',352 },353});354355// Fetch products for a collection page356export async function getProducts(collectionId?: string) {357 const { products, count } = await medusa.store.product.list({358 collection_id: collectionId ? [collectionId] : undefined,359 limit: 24,360 fields: '+variants.calculated_price',361 });362 return { products, count };363}364365// Add item to cart366export async function addToCart(cartId: string, variantId: string, quantity: number) {367 const { cart } = await medusa.store.cart.createLineItem(cartId, {368 variant_id: variantId,369 quantity,370 });371 return cart;372}373374// Fetch loyalty balance (custom endpoint)375export async function getLoyaltyBalance() {376 const response = await fetch(377 `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/loyalty`,378 { credentials: 'include' }379 );380 if (!response.ok) throw new Error('Failed to fetch loyalty balance');381 return response.json();382}383```384385### Custom payment provider module386387```typescript388// src/modules/custom-payment/service.ts389import {390 AbstractPaymentProvider,391} from '@medusajs/framework/utils';392import type {393 CreatePaymentProviderSession,394 UpdatePaymentProviderSession,395 ProviderWebhookPayload,396 WebhookActionResult,397} from '@medusajs/framework/types';398399class CustomPaymentProviderService extends AbstractPaymentProvider<{}> {400 static identifier = 'custom-payment';401402 async initiatePayment(403 data: CreatePaymentProviderSession404 ): Promise<Record<string, unknown>> {405 // Call your payment gateway's API to create a payment session406 const response = await fetch('https://api.custompay.com/v1/sessions', {407 method: 'POST',408 headers: {409 'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}`,410 'Content-Type': 'application/json',411 },412 body: JSON.stringify({413 amount: data.amount,414 currency: data.currency_code,415 metadata: { medusa_cart_id: data.context.cart_id },416 }),417 });418 const session = await response.json();419420 return { session_id: session.id, client_token: session.client_token };421 }422423 async authorizePayment(424 paymentSessionData: Record<string, unknown>425 ): Promise<{ status: string; data: Record<string, unknown> }> {426 const sessionId = paymentSessionData.session_id as string;427428 const response = await fetch(429 `https://api.custompay.com/v1/sessions/${sessionId}`,430 {431 headers: { 'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}` },432 }433 );434 const session = await response.json();435436 return {437 status: session.status === 'paid' ? 'authorized' : 'pending',438 data: { ...paymentSessionData, gateway_status: session.status },439 };440 }441442 async capturePayment(443 paymentSessionData: Record<string, unknown>444 ): Promise<Record<string, unknown>> {445 const sessionId = paymentSessionData.session_id as string;446447 await fetch(`https://api.custompay.com/v1/sessions/${sessionId}/capture`, {448 method: 'POST',449 headers: { 'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}` },450 });451452 return { ...paymentSessionData, captured: true };453 }454455 async refundPayment(456 paymentSessionData: Record<string, unknown>,457 refundAmount: number458 ): Promise<Record<string, unknown>> {459 const sessionId = paymentSessionData.session_id as string;460461 await fetch(`https://api.custompay.com/v1/sessions/${sessionId}/refund`, {462 method: 'POST',463 headers: {464 'Authorization': `Bearer ${process.env.CUSTOM_PAYMENT_API_KEY}`,465 'Content-Type': 'application/json',466 },467 body: JSON.stringify({ amount: refundAmount }),468 });469470 return { ...paymentSessionData, refunded_amount: refundAmount };471 }472473 async cancelPayment(474 paymentSessionData: Record<string, unknown>475 ): Promise<Record<string, unknown>> {476 return { ...paymentSessionData, cancelled: true };477 }478479 async deletePayment(480 paymentSessionData: Record<string, unknown>481 ): Promise<Record<string, unknown>> {482 return {};483 }484485 async getPaymentStatus(486 paymentSessionData: Record<string, unknown>487 ): Promise<string> {488 return (paymentSessionData.gateway_status as string) || 'pending';489 }490491 async getWebhookActionAndData(492 payload: ProviderWebhookPayload493 ): Promise<WebhookActionResult> {494 const event = JSON.parse(payload.rawData as string);495496 switch (event.type) {497 case 'payment.captured':498 return { action: 'captured', data: { session_id: event.session_id } };499 case 'payment.failed':500 return { action: 'failed', data: { session_id: event.session_id } };501 default:502 return { action: 'not_supported' };503 }504 }505}506507export default CustomPaymentProviderService;508```509510## Best Practices511512- **Use the module system for encapsulation** -- each domain (loyalty, custom fulfillment, analytics) should be its own module with its own service, models, and migrations513- **Always add compensation functions to workflow steps** -- if a step can fail, the compensation function rolls back the previous step's side effects for clean error recovery514- **Resolve dependencies from the container, not with imports** -- use `container.resolve()` for services to respect the DI configuration and enable testing515- **Use subscribers for side effects, not core logic** -- subscribers should trigger notifications, sync external systems, and log events; keep order processing in workflows516- **Validate API input with Zod** -- define Zod schemas for request bodies and use middleware to validate before the handler runs517- **Write migrations for schema changes** -- never modify the database manually; use Medusa's migration system so changes are reproducible across environments518- **Use the Medusa Admin SDK for admin extensions** -- extend the admin dashboard with custom widgets using the `@medusajs/admin-sdk` package instead of building separate UIs519- **Pin your Medusa version** -- Medusa v2 is evolving rapidly; lock the version in `package.json` and test before upgrading520521## Common Pitfalls522523| Problem | Solution |524|---------|----------|525| Custom module not found at runtime | Register it in `medusa-config.ts` under the `modules` array and run `npx medusa db:migrate` to apply any model changes |526| Subscriber fires but data is stale | Subscribers run asynchronously; re-fetch the entity inside the subscriber handler rather than relying on event payload data |527| API route returns 404 | Ensure the file path matches the URL pattern: `src/api/store/loyalty/route.ts` maps to `/store/loyalty`; check for missing `export` on the handler function |528| Workflow step fails without rollback | Every step that has side effects needs a compensation function as the second argument to `createStep` |529| Database migration conflicts after merge | Run `npx medusa db:migrate` after pulling changes; if migrations conflict, generate a new migration that resolves the diff |530| CORS errors from storefront | Configure `storeCors` in `medusa-config.ts` to include your storefront's origin URL including the port |531532## Related Skills533534- @product-data-modeling535- @stripe-integration536- @ecommerce-caching537- @ecommerce-seo538- @erp-integration