
Medusa Development
- 65 installs
- 41 repo stars
- Updated March 13, 2026
- finsilabs/awesome-ecommerce-skills
Extend the open-source Medusa commerce platform with custom services, event subscribers, and API endpoints for unique business logic.
About
Covers extending Medusa with custom services, event subscribers, and API routes to implement business-specific commerce requirements. A developer uses it when building on the headless open-source Medusa stack.
- Custom services and event subscribers
- Custom API endpoints for bespoke business logic
Medusa Development by the numbers
- 65 all-time installs (skills.sh)
- Ranked #3,110 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/finsilabs/awesome-ecommerce-skills --skill medusa-developmentAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 65 |
|---|---|
| repo stars | ★ 41 |
| Last updated | March 13, 2026 |
| Repository | finsilabs/awesome-ecommerce-skills ↗ |
What it does
Extend the open-source Medusa commerce platform with custom services, event subscribers, and API endpoints for unique business logic.
Files
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
1. 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 developConfigure 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
],
});2. 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,
});3. 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',
};4. 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 });
}
}5. 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;
}
);6. 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-sdkpackage instead of building separate UIs - Pin your Medusa version -- Medusa v2 is evolving rapidly; lock the version in
package.jsonand 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
{
"context": "Tests whether the agent correctly implements custom Medusa v2 API routes, including TypeScript type imports, file path to URL mapping, named HTTP method exports, service resolution via req.scope, authenticated customer ID access, and Zod schema validation for request bodies.",
"type": "weighted_checklist",
"checklist": [
{
"name": "MedusaRequest/MedusaResponse types",
"max_score": 8,
"description": "Route handler functions use MedusaRequest and MedusaResponse type annotations imported from '@medusajs/framework/http'"
},
{
"name": "Correct import path",
"max_score": 6,
"description": "MedusaRequest and MedusaResponse are imported specifically from '@medusajs/framework/http' (not from '@medusajs/framework' or '@medusajs/medusa')"
},
{
"name": "Named method exports",
"max_score": 10,
"description": "HTTP handlers are exported as named exports matching the HTTP verb (e.g. export async function GET, export async function POST) rather than a default export router"
},
{
"name": "URL-matching file paths",
"max_score": 10,
"description": "Route files are placed at src/api/<scope>/<resource>/route.ts so that the file path directly maps to the intended URL (e.g. src/api/store/wishlist/route.ts for /store/wishlist)"
},
{
"name": "req.scope.resolve() for services",
"max_score": 10,
"description": "Services inside route handlers are obtained with req.scope.resolve() rather than imported directly or obtained via container.resolve()"
},
{
"name": "req.auth_context for customer ID",
"max_score": 10,
"description": "The authenticated customer's ID is read from req.auth_context?.actor_id rather than from request body, query params, or a JWT decode"
},
{
"name": "401 on missing auth",
"max_score": 6,
"description": "Route handler returns a 401 response when req.auth_context?.actor_id is not present (unauthenticated request)"
},
{
"name": "Zod schema defined",
"max_score": 12,
"description": "At least one request body is validated using a Zod schema (z.object(...)) rather than relying on TypeScript types alone or manual if-checks"
},
{
"name": "Zod validation before handler logic",
"max_score": 8,
"description": "The Zod schema is parsed/validated before the main handler logic executes (either via middleware or an explicit parse/safeParse call at the top of the handler)"
},
{
"name": "400 on validation failure",
"max_score": 6,
"description": "The handler returns a 400 response with an error message when Zod validation fails"
},
{
"name": "Store scope route",
"max_score": 6,
"description": "At least one route is placed under src/api/store/ (not under src/api/admin/) for customer-facing access"
},
{
"name": "No direct service imports",
"max_score": 8,
"description": "Service classes are NOT imported and instantiated directly in route files — they are always resolved from req.scope"
}
]
}
Storefront Wishlist API Endpoints
Problem/Feature Description
A fashion retailer running Medusa wants to add a wishlist feature to their Next.js storefront. Shoppers should be able to save products they're interested in and come back to purchase them later. The feature needs to be customer-specific — each logged-in shopper has their own private wishlist — and the storefront will call the Medusa backend directly to manage it.
The backend team has already built and registered a WishlistModuleService (registered under the key 'wishlistModuleService') that exposes the following methods:
addItem(customerId: string, variantId: string): Promise<WishlistItem>removeItem(customerId: string, variantId: string): Promise<void>listItems(customerId: string): Promise<WishlistItem[]>
Your job is to expose these through Medusa's custom route system so the storefront can interact with them. The storefront team expects the following HTTP interface:
GET /store/wishlist— return the current customer's wishlist itemsPOST /store/wishlist— add an item; request body containsvariant_id(string, required)DELETE /store/wishlist/:variant_id— remove an item
All three endpoints require the customer to be authenticated. The POST endpoint must validate the request body before calling the service.
Output Specification
Produce the route handler file(s) under the appropriate src/api/ path(s). The file layout should reflect the URL structure. Include a brief IMPLEMENTATION.md that describes each endpoint's file path, its URL, and how authentication is handled.
{
"context": "Tests whether the agent follows Medusa v2 module architecture patterns: using MedusaService with model-based CRUD generation, defining data models with the model DSL, registering the module with Module(), and wiring it into medusa-config.ts. Also checks correct TypeScript import paths and module encapsulation.",
"type": "weighted_checklist",
"checklist": [
{
"name": "MedusaService extension",
"max_score": 12,
"description": "Service class extends MedusaService() (called with a model map) rather than a plain class or other base class"
},
{
"name": "Correct service import",
"max_score": 8,
"description": "MedusaService is imported from '@medusajs/framework/utils'"
},
{
"name": "model.define() usage",
"max_score": 10,
"description": "Data model is defined using model.define() rather than a TypeORM entity class or other ORM decorator approach"
},
{
"name": "model DSL field types",
"max_score": 8,
"description": "Model fields use model.id().primaryKey(), model.text(), model.number(), or model.enum() — not raw TypeScript type annotations or decorators"
},
{
"name": "model import path",
"max_score": 6,
"description": "model is imported from '@medusajs/framework/utils'"
},
{
"name": "Module() registration",
"max_score": 10,
"description": "Module's index.ts exports a default created with Module() from '@medusajs/framework/utils' and specifies the service"
},
{
"name": "Module identifier constant",
"max_score": 8,
"description": "A named string constant (e.g. WARRANTY_MODULE) is exported from the module index and used as the module key"
},
{
"name": "medusa-config.ts registration",
"max_score": 10,
"description": "The custom module is listed in the modules array inside medusa-config.ts (or a comment/instruction notes it must be added there)"
},
{
"name": "defineConfig usage",
"max_score": 8,
"description": "medusa-config.ts uses defineConfig (and optionally loadEnv) imported from '@medusajs/framework/utils'"
},
{
"name": "Module encapsulation",
"max_score": 10,
"description": "The new domain is implemented as its own module directory (e.g. src/modules/<name>/) containing the service, models, and index rather than scattered files"
},
{
"name": "db:migrate instruction",
"max_score": 6,
"description": "Output includes mention of running 'npx medusa db:migrate' or equivalent migration step to apply the new model"
},
{
"name": "container.resolve() pattern",
"max_score": 4,
"description": "Any usage of the module service (e.g. in a route or subscriber) uses container.resolve() rather than a direct import of the service class"
}
]
}
Warranty Claims Module for Medusa Backend
Problem/Feature Description
A B2B hardware retailer has recently migrated their storefront to Medusa. Their product catalog includes electronics and appliances that carry manufacturer warranties of varying lengths (1-year, 2-year, lifetime). Currently, when customers submit warranty claims through the website, staff handle them manually in a spreadsheet — a process that breaks down as order volume grows.
The engineering team has been asked to add warranty claim tracking directly into the Medusa backend. Each warranty claim must record which order it belongs to, which product variant is affected, the warranty duration in months, and the current claim status (open, approved, rejected, resolved). The service should expose methods to create a claim, update its status, and list claims for a given order. The team also wants a brief developer notes document explaining how to activate the module in the project configuration and apply the database schema changes.
Output Specification
Produce the following files:
src/modules/warranty/models/warranty-claim.ts— the data model definitionsrc/modules/warranty/service.ts— the module servicesrc/modules/warranty/index.ts— module registrationmedusa-config.ts— project config showing how the module is wired in (may be partial/illustrative, but must show the relevant registration)NOTES.md— a short developer notes file explaining how to activate the module and run the required database command after adding it
{
"context": "Tests whether the agent correctly implements Medusa v2 event subscribers and custom workflows, including proper TypeScript imports, using the DI container to resolve services, re-fetching entity data inside the subscriber, and adding compensation functions to workflow steps that have side effects.",
"type": "weighted_checklist",
"checklist": [
{
"name": "SubscriberArgs/SubscriberConfig import",
"max_score": 8,
"description": "Subscriber file imports SubscriberArgs and/or SubscriberConfig from '@medusajs/framework' (not from a sub-path like /utils)"
},
{
"name": "Subscriber config export",
"max_score": 8,
"description": "Subscriber file exports a `config` object of type SubscriberConfig containing an `event` field with the event name string"
},
{
"name": "container.resolve() in subscriber",
"max_score": 10,
"description": "All services used inside the subscriber are obtained via container.resolve() rather than direct imports"
},
{
"name": "Entity re-fetched in subscriber",
"max_score": 10,
"description": "The subscriber retrieves the full entity data (e.g. order) from a service using the ID from the event payload, rather than relying solely on the event payload for entity fields"
},
{
"name": "Subscriber for side effects only",
"max_score": 8,
"description": "The subscriber delegates substantive processing to a workflow or service call rather than containing inline core business logic"
},
{
"name": "createWorkflow / createStep imports",
"max_score": 8,
"description": "Workflow file imports createWorkflow, createStep, and StepResponse from '@medusajs/framework/workflows-sdk'"
},
{
"name": "StepResponse returned from step",
"max_score": 8,
"description": "Each createStep handler returns a new StepResponse(...) rather than returning a plain object or value"
},
{
"name": "Compensation function on side-effect step",
"max_score": 12,
"description": "At least one step that writes data or calls an external API includes a compensation function (third argument to createStep) for rollback"
},
{
"name": "Compensation data passed to StepResponse",
"max_score": 8,
"description": "The StepResponse for a step with a compensation function passes rollback data as the second argument (e.g. new StepResponse(result, { id: result.id }))"
},
{
"name": "container.resolve() in workflow step",
"max_score": 10,
"description": "Services accessed inside workflow steps are resolved from the container (second argument to the step handler), not imported directly"
},
{
"name": "Correct file placement",
"max_score": 6,
"description": "Subscriber file is placed under src/subscribers/ and workflow file under src/workflows/"
},
{
"name": "Logger resolved from container",
"max_score": 4,
"description": "Logging uses a logger resolved from the container (container.resolve('logger')) rather than console.log"
}
]
}
Automated Fulfillment Notification System
Problem/Feature Description
A growing e-commerce company fulfills orders through a third-party logistics (3PL) partner. Currently, staff manually export new orders each morning and email them to the 3PL — a process that causes delays and occasional missed shipments. The engineering team has been asked to automate this: whenever an order is placed, the system should automatically send the order details to the 3PL's webhook endpoint and record a fulfillment request in the database so the operations team can audit what was sent.
The team has an existing FulfillmentRequestModuleService already registered under the key 'fulfillmentRequestModuleService' that exposes createFulfillmentRequest(data) and deleteFulfillmentRequest(id) methods — you do not need to reimplement it. Focus on the event-driven automation layer: the subscriber that reacts to placed orders and the workflow that does the actual work.
Output Specification
Produce the following files:
src/subscribers/order-placed.ts— the event subscriber that triggers when an order is placedsrc/workflows/notify-fulfillment-partner.ts— the workflow responsible for calling the 3PL and persisting the fulfillment recordworkflow-design.md— a brief document describing each workflow step, what it does, and how failure at any step is handled
The 3PL webhook URL is https://3pl.example.com/api/inbound-orders. For authentication use a Bearer token from an environment variable FULFILLMENT_PARTNER_TOKEN. The fulfillment request record should capture at minimum: the order ID, the 3PL's response reference ID, and a status field.
{
"name": "finsi/medusa-development",
"version": "0.1.0",
"summary": "Medusa.js setup, custom services, subscribers, and API extensions",
"skills": {
"medusa-development": {
"path": "SKILL.md"
}
}
}