Expert guidelines for building e-commerce platforms with Medusa v2 and Next.js 14+. Covers API routes, workflows, data models, modules, and storefront development patterns.
You are an expert in developing e-commerce platforms using Medusa.js v2 and Next.js 14+ App Router.
This skill covers two main components:
1. **Backend**: Medusa.js application server
2. **Storefront**: Next.js 14+ App Router storefront
Create API endpoints in `src/api/admin/` (authenticated) or `src/api/store/` (public):
```typescript
// src/api/[admin|store]/[route-name]/route.ts
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const query = req.scope.resolve("query")
// Your logic here
res.json({ data: result })
}
```
**Key Rules**:
Orchestrate complex business logic with automatic rollback support:
```typescript
import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
export const myCustomWorkflow = createWorkflow(
"my-custom-workflow",
function (input: InputType) {
const step1Result = step1(input)
const step2Result = step2(step1Result)
return new WorkflowResponse({ result: step2Result })
}
)
```
**Key Rules**:
Define database models using Data Model Language (DML):
```typescript
import { model } from "@medusajs/framework/utils"
export const MyModel = model.define("my_model", {
id: model.id().primaryKey(),
name: model.text(),
description: model.text().nullable(),
})
```
**Key Rules**:
Structure modules by business domain:
```
src/modules/[module-name]/
├── models/ # Data models
├── services/ # Business logic
├── workflows/ # Complex operations
├── migrations/ # Database migrations
└── index.ts # Module exports
```
**Service Pattern**:
```typescript
import { MedusaService } from "@medusajs/framework/utils"
class MyModuleService extends MedusaService({ MyModel }) {
async customMethod(id: string) {
// Custom logic
}
}
export default MyModuleService
```
React to domain events:
```typescript
import type { SubscriberConfig } from "@medusajs/framework"
export default async function orderPlacedHandler({ event, container }) {
// React to event
}
export const config: SubscriberConfig = {
event: "order.placed",
}
```
**Key Rules**:
Create custom admin widgets and pages:
```typescript
import { defineWidgetConfig } from "@medusajs/admin-sdk"
const MyWidget = () => {
return <div>My Custom Widget</div>
}
export const config = defineWidgetConfig({
zone: "product.details.after",
})
export default MyWidget
```
```
src/
├── app/ # Next.js App Router
│ ├── [countryCode]/ # Multi-region routing
│ │ ├── (checkout)/ # Checkout flow (route group)
│ │ └── (main)/ # Main store (route group)
│ └── layout.tsx
├── modules/ # Feature modules
├── lib/ # Utilities and data fetching
└── types/ # TypeScript types
```
Structure features as self-contained modules:
```
modules/[feature]/
├── components/ # Feature-specific components
│ └── [component]/index.tsx
└── templates/ # Page templates
└── index.tsx
```
**Key Modules**: account, cart, checkout, products, collections, categories, order, layout, common
Server-side data fetching pattern:
```typescript
import { cookies } from "next/headers"
import { getAuthHeaders } from "./cookies"
export async function getProduct(id: string) {
const headers = {
...getAuthHeaders(),
"x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY!,
}
const response = await fetch(
`${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/products/${id}`,
{
headers,
next: { tags: [`product:${id}`] }
}
)
return response.json()
}
```
**Key Rules**:
**Server Components** (default):
```typescript
export default async function ProductPage({ params }: { params: { id: string } }) {
const product = await getProduct(params.id)
return <ProductTemplate product={product} />
}
```
**Client Components** (when needed):
```typescript
"use client"
import { useState } from "react"
export default function InteractiveComponent() {
const [state, setState] = useState()
// Component logic
}
```
**Key Rules**:
```typescript
// Good: Semantic utility classes
<div className="flex items-center justify-between p-4 bg-white rounded-lg shadow-md">
```
**Key Rules**:
**Backend**:
```bash
cd [backend-dir]
npm install
npm run dev # http://localhost:9000
```
**Storefront**:
```bash
cd [storefront-dir]
npm install
npm run dev # http://localhost:3000
```
```bash
cd [backend-dir]
npx medusa db:migrate
npx medusa db:seed
```
**Required Variables**:
```bash
NEXT_PUBLIC_MEDUSA_BACKEND_URL=http://localhost:9000
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_...
NEXT_PUBLIC_DEFAULT_REGION=us
```
**Key Rules**:
1. **Module not found**: Check `tsconfig.json` paths and ensure modules are registered in `medusa-config.ts`
2. **CORS issues**: Configure CORS properly in `medusa-config.ts` for admin and store
3. **Authentication**: Include proper auth headers for authenticated requests
4. **Cache invalidation**: Use Next.js cache tags and revalidation strategies
1. **Use dependency injection** via `req.scope.resolve()` in backend
2. **Prefer Server Components** for data fetching in storefront
3. **Keep modules focused** on single business domains
4. **Write workflows** for complex, multi-step operations
5. **Use TypeScript strictly** across the entire stack
6. **Follow REST conventions** for API design
7. **Leverage Medusa's built-in features** before building custom solutions
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/medusajs-e-commerce-development/raw