
medusa-dev
- GitHub stars
- 237
Install
/plugin install medusa-dev@medusaRun it inside Claude Code after adding the marketplace with /plugin marketplace add medusajs/medusa-agent-skills.
Contents
Discovered from sourceSkills 7
Medusa Admin Dashboard Customizations
Build custom UI extensions for the Medusa Admin dashboard using the Admin SDK and Medusa UI components.
Note: "UI Routes" are custom admin pages, different from backend API routes (which use building-with-medusa skill).
When to Apply
Load this skill for ANY admin UI development task, including:
- Creating widgets for product/order/customer pages
- Building custom admin pages
- Implementing forms and modals
- Displaying data with tables or lists
- Adding navigation between pages
Also load these skills when:
- building-with-medusa: Building backend API routes that the admin UI calls
- building-storefronts: If working on storefront instead of admin dashboard
CRITICAL: Load Reference Files When Needed
The quick reference below is NOT sufficient for implementation. You MUST load relevant reference files before writing code for that component.
Load these references based on what you're implementing:
- Creating widgets? → MUST load
references/data-loading.mdfirst - Building forms/modals? → MUST load
references/forms.mdfirst - Displaying data in tables/lists? → MUST load
references/display-patterns.mdfirst - Selecting from large datasets? → MUST load
references/table-selection.mdfirst - Adding navigation? → MUST load
references/navigation.mdfirst - Styling components? → MUST load
references/typography.mdfirst
Minimum requirement: Load at least 1-2 reference files relevant to your specific task before implementing.
When to Use This Skill vs MedusaDocs MCP Server
⚠️ CRITICAL: This skill should be consulted FIRST for planning and implementation.
Use this skill for (PRIMARY SOURCE):
- Planning - Understanding how to structure admin UI features
- Component patterns - Widgets, pages, forms, tables, modals
- Design system - Typography, colors, spacing, semantic classes
- Data loading - Critical separate query pattern, cache invalidation
- Best practices - Correct vs incorrect patterns (e.g., display queries on mount)
- Critical rules - What NOT to do (common mistakes like conditional display queries)
Use MedusaDocs MCP server for (SECONDARY SOURCE):
- Specific component prop signatures after you know which component to use
- Available widget zones list
- JS SDK method details
- Configuration options reference
Why skills come first:
- Skills contain critical patterns like separate display/modal queries that MCP doesn't emphasize
- Skills show correct vs incorrect patterns; MCP shows what's possible
- Planning requires understanding patterns, not just API reference
Critical Setup Rules
SDK Client Configuration
CRITICAL: Always use exact configuration - different values cause errors:
// src/admin/lib/client.ts
import Medusa from "@medusajs/js-sdk"
export const sdk = new Medusa({
baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
debug: import.meta.env.DEV,
auth: {
type: "session",
},
})
pnpm Users ONLY
CRITICAL: Install peer dependencies BEFORE writing any code:
# Find exact version from dashboard
pnpm list @tanstack/react-query --depth=10 | grep @medusajs/dashboard
# Install that exact version
pnpm add @tanstack/react-query@[exact-version]
# If using navigation (Link component)
pnpm list react-router-dom --depth=10 | grep @medusajs/dashboard
pnpm add react-router-dom@[exact-version]
npm/yarn users: DO NOT install these packages - already available.
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Data Loading | CRITICAL | data- |
| 2 | Design System | CRITICAL | design- |
| 3 | Data Display | HIGH (includes CRITICAL price rule) | display- |
| 4 | Typography | HIGH | typo- |
| 5 | Forms & Modals | MEDIUM | form- |
| 6 | Selection Patterns | MEDIUM | select- |
Quick Reference
1. Data Loading (CRITICAL)
data-sdk-always- ALWAYS use Medusa JS SDK for ALL API requests - NEVER use regular fetch() (missing auth headers causes errors)data-sdk-method-choice- Use existing SDK methods for built-in endpoints (sdk.admin.product.list()), usesdk.client.fetch()for custom routesdata-display-on-mount- Display queries MUST load on mount (no enabled condition based on UI state)data-separate-queries- Separate display queries from modal/form queriesdata-invalidate-display- Invalidate display queries after mutations, not just modal queriesdata-loading-states- Always show loading states (Spinner), not empty statesdata-pnpm-install-first- pnpm users MUST install @tanstack/react-query BEFORE coding
2. Design System (CRITICAL)
design-semantic-colors- Always use semantic color classes (bg-ui-bg-base, text-ui-fg-subtle), never hardcodeddesign-spacing- Use px-6 py-4 for section padding, gap-2 for lists, gap-3 for itemsdesign-button-size- Always use size="small" for buttons in widgets and tablesdesign-medusa-components- Always use Medusa UI components (Container, Button, Text), not raw HTML
3. Data Display (HIGH)
display-price-format- CRITICAL: Prices from Medusa are stored as-is ($49.99 = 49.99, NOT in cents). Display them directly - NEVER divide by 100
4. Typography (HIGH)
typo-text-component- Always use Text component from @medusajs/ui, never plain span/p tagstypo-labels- Use<Text size="small" leading="compact" weight="plus">for labels/headingstypo-descriptions- Use<Text size="small" leading="compact" className="text-ui-fg-subtle">for descriptionstypo-no-heading-widgets- Never use Heading for small sections in widgets (use Text instead)
5. Forms & Modals (MEDIUM)
form-focusmodal-create- Use FocusModal for creating new entitiesform-drawer-edit- Use Drawer for editing existing entitiesform-disable-pending- Always disable actions during mutations (disabled={mutation.isPending})form-show-loading- Show loading state on submit button (isLoading={mutation.isPending})
6. Selection Patterns (MEDIUM)
select-small-datasets- Use Select component for 2-10 options (statuses, types, etc.)select-large-datasets- Use DataTable with FocusModal for large datasets (products, categories, etc.)select-search-config- Must pass search configuration to useDataTable to avoid "search not enabled" error
Critical Data Loading Pattern
ALWAYS follow this pattern - never load display data conditionally:
// ✅ CORRECT - Separate queries with proper responsibilities
const RelatedProductsWidget = ({ data: product }) => {
const [modalOpen, setModalOpen] = useState(false)
// Display query - loads on mount
const { data: displayProducts } = useQuery({
queryFn: () => fetchSelectedProducts(selectedIds),
queryKey: ["related-products-display", product.id],
// No 'enabled' condition - loads immediately
})
// Modal query - loads when needed
const { data: modalProducts } = useQuery({
queryFn: () => sdk.admin.product.list({ limit: 10, offset: 0 }),
queryKey: ["products-selection"],
enabled: modalOpen, // OK for modal-only data
})
// Mutation with proper invalidation
const updateProduct = useMutation({
mutationFn: updateFunction,
onSuccess: () => {
// Invalidate display data query to refresh UI
queryClient.invalidateQueries({ queryKey: ["related-products-display", product.id] })
// Also invalidate the entity query
queryClient.invalidateQueries({ queryKey: ["product", product.id] })
// Note: No need to invalidate modal selection query
},
})
return (
<Container>
{/* Display uses displayProducts */}
{displayProducts?.map(p => <div key={p.id}>{p.title}</div>)}
<FocusModal open={modalOpen} onOpenChange={setModalOpen}>
{/* Modal uses modalProducts */}
</FocusModal>
</Container>
)
}
// ❌ WRONG - Single query with conditional loading
const BrokenWidget = ({ data: product }) => {
const [modalOpen, setModalOpen] = useState(false)
const { data } = useQuery({
queryFn: () => sdk.admin.product.list(),
enabled: modalOpen, // ❌ Display breaks on page refresh!
})
// Trying to display from modal query
const displayItems = data?.filter(item => ids.includes(item.id)) // No data until modal opens
return <div>{displayItems?.map(...)}</div> // Empty on mount!
}
Why this matters:
- On page refresh, modal is closed, so conditional query doesn't run
- User sees empty state instead of their data
- Display depends on modal interaction (broken UX)
Common Mistakes Checklist
Before implementing, verify you're NOT doing these:
Data Loading:
- Using regular fetch() instead of Medusa JS SDK (causes missing auth header errors)
- Not using existing SDK methods for built-in endpoints (e.g., using sdk.client.fetch("/admin/products") instead of sdk.admin.product.list())
- Loading display data conditionally based on modal/UI state
- Using a single query for both display and modal
- Forgetting to invalidate display queries after mutations
- Not handling loading states (showing empty instead of spinner)
- pnpm users: Not installing @tanstack/react-query before coding
Design System:
- Using hardcoded colors instead of semantic classes
- Forgetting size="small" on buttons in widgets
- Not using px-6 py-4 for section padding
- Using raw HTML elements instead of Medusa UI components
Data Display:
- CRITICAL: Dividing prices by 100 when displaying (prices are stored as-is: $49.99 = 49.99, NOT in cents)
Typography:
- Using plain span/p tags instead of Text component
- Not using weight="plus" for labels
- Not using text-ui-fg-subtle for descriptions
- Using Heading in small widget sections
Forms:
- Using Drawer for creating (should use FocusModal)
- Using FocusModal for editing (should use Drawer)
- Not disabling buttons during mutations
- Not showing loading state on submit
Selection:
- Using DataTable for <10 items (overkill)
- Using Select for >10 items (poor UX)
- Not configuring search in useDataTable (causes error)
Reference Files Available
Load these for detailed patterns:
references/data-loading.md - useQuery/useMutation patterns, cache invalidation
references/forms.md - FocusModal/Drawer patterns, validation
references/table-selection.md - Complete DataTable selection pattern
references/display-patterns.md - Lists, tables, cards for entities
references/typography.md - Text component patterns
references/navigation.md - Link, useNavigate, useParams patterns
Each reference contains:
- Step-by-step implementation guides
- Correct vs incorrect code examples
- Common mistakes and solutions
- Complete working examples
Integration with Backend
⚠️ CRITICAL: ALWAYS use the Medusa JS SDK for ALL API requests - NEVER use regular fetch()
Admin UI connects to backend API routes using the SDK:
import { sdk } from "[LOCATE SDK INSTANCE IN PROJECT]"
// ✅ CORRECT - Built-in endpoint: Use existing SDK method
const { data: product } = useQuery({
queryKey: ["product", productId],
queryFn: () => sdk.admin.product.retrieve(productId),
})
// ✅ CORRECT - Custom endpoint: Use sdk.client.fetch()
const { data: reviews } = useQuery({
queryKey: ["reviews", product.id],
queryFn: () => sdk.client.fetch(`/admin/products/${product.id}/reviews`),
})
// ❌ WRONG - Using regular fetch
const { data } = useQuery({
queryKey: ["reviews", product.id],
queryFn: () => fetch(`http://localhost:9000/admin/products/${product.id}/reviews`),
// ❌ Error: Missing Authorization header!
})
// Mutation to custom backend route
const createReview = useMutation({
mutationFn: (data) => sdk.client.fetch("/admin/reviews", {
method: "POST",
body: data
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["reviews", product.id] })
toast.success("Review created")
},
})
Why the SDK is required:
- Admin routes need
Authorizationand session cookie headers - Store routes need
x-publishable-api-keyheader - SDK handles all required headers automatically
- Regular fetch() without headers → authentication/authorization errors
- Using existing SDK methods provides better type safety
When to use what:
- Built-in endpoints: Use existing SDK methods (
sdk.admin.product.list(),sdk.store.product.list()) - Custom endpoints: Use
sdk.client.fetch()for your custom API routes
For implementing backend API routes, load the building-with-medusa skill.
Widget vs UI Route
Widgets extend existing admin pages:
// src/admin/widgets/custom-widget.tsx
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { DetailWidgetProps } from "@medusajs/framework/types"
const MyWidget = ({ data }: DetailWidgetProps<HttpTypes.AdminProduct>) => {
return <Container>Widget content</Container>
}
export const config = defineWidgetConfig({
zone: "product.details",
})
export default MyWidget
⚠️ .before / .after no longer control placement (v2.17.2+):
Since the Layout Composer landed, admin users arrange components — including widgets — through the dashboard's Editor view, and the arrangement is persisted in the database. The .before and .after zone suffixes are deprecated: a widget in product.details.before and one in product.details.after land in the same injection zone, and the final order is whatever the user configured.
- Don't promise the user a specific position based on the suffix. Say "the widget appears in the product details page and can be repositioned in the Editor view".
.sideis still meaningful — it targets the side column of two-column page layouts.- For new widgets, prefer the unsuffixed zone (e.g.
product.details) unless the project already standardizes on a suffix.
Newer zones added in v2.16.0 cover draft orders, gift cards, and store credit accounts (draft_order.*, gift_card.*, store_credit_account.*, in details/list/side variants). Ask the MedusaDocs MCP server for the authoritative zone list rather than guessing a zone name.
UI Routes create new admin pages:
// src/admin/routes/custom-page/page.tsx
import { defineRouteConfig } from "@medusajs/admin-sdk"
const CustomPage = () => {
return <div>Page content</div>
}
export const config = defineRouteConfig({
label: "Custom Page",
})
export default CustomPage
Browser tab title (v2.17.2+): by default a UI route's tab title is its label. Export a handle with an seo resolver to override it, including dynamically from the route's loader data:
// src/admin/routes/brands/[id]/page.tsx
import { UIMatch } from "react-router-dom"
export const handle = {
seo: (match: UIMatch<BrandResponse>) => ({
title: match.loaderData?.brand.name || "Brand",
}),
}
If seo returns no title, the dashboard falls back to the sidebar label, then the breadcrumb, then Medusa.
Custom injection zones (v2.16.0+): custom pages — most usefully in plugins — can expose their own widget injection zones by laying the page out with LayoutComposer from @medusajs/dashboard/components:
import { LayoutComposer } from "@medusajs/dashboard/components"
const BrandDetailsPage = () => (
<LayoutComposer
widgetsZonePrefix="brand.details" // exposes "brand.details" and "brand.details.side"
preferredLayoutId="core:two-column"
data={brand} // passed to widgets as their `data` prop
sections={{ main: <GeneralSection brand={brand} />, side: <MediaSection brand={brand} /> }}
/>
)
- Name zones
{resource}.{page-context}(e.g.brand.list,brand.details), plus.sidefor the side section. Never add.before/.after. - Register the zones in the
InjectionZoneRegistryinterface for type checking and autocompletion indefineWidgetConfig, and include"../../.medusa/types/augmentation-refs.d.ts"insrc/admin/tsconfig.json'sincludearray. - A build warning about an unknown zone is expected for custom zones — verify the zone name is spelled correctly rather than ignoring it blindly.
Common Issues & Solutions
"Cannot find module" errors (pnpm users):
- Install peer dependencies BEFORE coding
- Use exact versions from dashboard
"No QueryClient set" error:
- pnpm: Install @tanstack/react-query
- npm/yarn: Remove incorrectly installed package
"DataTable.Search not enabled":
- Must pass search configuration to useDataTable
Widget not refreshing:
- Invalidate display queries, not just modal queries
- Include all dependencies in query keys
Display empty on refresh:
- Display query has conditional
enabledbased on UI state - Remove condition - display data must load on mount
Next Steps - Testing Your Implementation
After successfully implementing a feature, always provide these next steps to the user:
1. Start the Development Server
If the server isn't already running, start it:
npm run dev # or pnpm dev / yarn dev
2. Access the Admin Dashboard
Open your browser and navigate to:
- Admin Dashboard: http://localhost:9000/app
Log in with your admin credentials.
3. Navigate to Your Custom UI
For Widgets: Navigate to the page where your widget is displayed. Common widget zones:
- Product widgets: Go to Products → Select a product → Your widget appears on the page
- Order widgets: Go to Orders → Select an order → Your widget appears on the page
- Customer widgets: Go to Customers → Select a customer → Your widget appears on the page
Its exact position within the page is controlled by the user in the dashboard's Editor view (Layout Composer), not by the zone's .before/.after suffix. Tell the user they can drag the widget where they want it.
For UI Routes (Custom Pages):
- Look for your custom page in the admin sidebar/navigation (based on the
labelyou configured) - Or navigate directly to:
http://localhost:9000/app/[your-route-path]
4. Test Functionality
Depending on what was implemented, test:
- Forms: Try creating/editing entities, verify validation and error messages
- Tables: Test pagination, search, sorting, and row selection
- Data display: Verify data loads correctly and refreshes after mutations
- Modals: Open FocusModal/Drawer, test form submission, verify data updates
- Navigation: Click links and verify routing works correctly
Format for Presenting Next Steps
Always present next steps in a clear, actionable format after implementation:
## Implementation Complete
The [feature name] has been successfully implemented. Here's how to see it:
### Start the Development Server
[command based on package manager]
### Access the Admin Dashboard
Open http://localhost:9000/app in your browser and log in.
### View Your Custom UI
**For Widgets:**
1. Navigate to [specific admin page, e.g., "Products"]
2. Select [an entity, e.g., "any product"]
3. Scroll to [zone location, e.g., "the bottom of the page"]
4. You'll see your "[widget name]" widget
**For UI Routes:**
1. Look for "[page label]" in the admin navigation
2. Or navigate directly to http://localhost:9000/app/[route-path]
### What to Test
1. [Specific test case 1]
2. [Specific test case 2]
3. [Specific test case 3]
Medusa Storefront Development
Frontend integration guide for building storefronts with Medusa. Covers SDK usage, React Query patterns, and calling custom API routes.
When to Apply
Load this skill for ANY storefront development task, including:
- Calling custom Medusa API routes from the storefront
- Integrating Medusa SDK in frontend applications
- Using React Query for data fetching
- Implementing mutations with optimistic updates
- Error handling and cache invalidation
Also load building-with-medusa when: Building the backend API routes that the storefront calls
CRITICAL: Load Reference Files When Needed
The quick reference below is NOT sufficient for implementation. You MUST load the reference file before writing storefront integration code.
Load this reference when implementing storefront features:
- Calling API routes? → MUST load
references/frontend-integration.mdfirst - Using SDK? → MUST load
references/frontend-integration.mdfirst - Implementing React Query? → MUST load
references/frontend-integration.mdfirst
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | SDK Usage | CRITICAL | sdk- |
| 2 | React Query Patterns | HIGH | query- |
| 3 | Data Display | HIGH (includes CRITICAL price rule) | display- |
| 4 | Error Handling | MEDIUM | error- |
Quick Reference
1. SDK Usage (CRITICAL)
sdk-always-use- ALWAYS use the Medusa JS SDK for ALL API requests - NEVER use regular fetch()sdk-existing-methods- For built-in endpoints, use existing SDK methods (sdk.store.product.list(),sdk.admin.order.retrieve())sdk-client-fetch- For custom API routes, usesdk.client.fetch()sdk-required-headers- SDK automatically adds required headers (publishable API key for store, auth for admin) - regular fetch() missing these headers causes errorssdk-no-json-stringify- NEVER use JSON.stringify() on body - SDK handles serialization automaticallysdk-plain-objects- Pass plain JavaScript objects to body, not stringssdk-locate-first- Always locate where SDK is instantiated in the project before using it
2. React Query Patterns (HIGH)
query-use-query- UseuseQueryfor GET requests (data fetching)query-use-mutation- UseuseMutationfor POST/DELETE requests (mutations)query-invalidate- Invalidate queries inonSuccessto refresh data after mutationsquery-keys-hierarchical- Structure query keys hierarchically for effective cache managementquery-loading-states- Always handleisLoading,isPending,isErrorstates
3. Data Display (HIGH)
display-price-format- CRITICAL: Prices from Medusa are stored as-is ($49.99 = 49.99, NOT in cents). Display them directly - NEVER divide by 100
4. Error Handling (MEDIUM)
error-on-error- ImplementonErrorcallback in mutations to handle failureserror-display- Show error messages to users when mutations failerror-rollback- Use optimistic updates with rollback on error for better UX
Critical SDK Pattern
ALWAYS pass plain objects to the SDK - NEVER use JSON.stringify():
// ✅ CORRECT - Plain object
await sdk.client.fetch("/store/reviews", {
method: "POST",
body: {
product_id: "prod_123",
rating: 5,
}
})
// ❌ WRONG - JSON.stringify breaks the request
await sdk.client.fetch("/store/reviews", {
method: "POST",
body: JSON.stringify({ // ❌ DON'T DO THIS!
product_id: "prod_123",
rating: 5,
})
})
Why this matters:
- The SDK handles JSON serialization automatically
- Using JSON.stringify() will double-serialize and break the request
- The server won't be able to parse the body
Common Mistakes Checklist
Before implementing, verify you're NOT doing these:
SDK Usage:
- Using regular fetch() instead of the Medusa JS SDK (causes missing header errors)
- Not using existing SDK methods for built-in endpoints (e.g., using sdk.client.fetch("/store/products") instead of sdk.store.product.list())
- Using JSON.stringify() on the body parameter
- Manually setting Content-Type headers (SDK adds them)
- Hardcoding SDK import paths (locate in project first)
- Not using sdk.client.fetch() for custom routes
React Query:
- Not invalidating queries after mutations
- Using flat query keys instead of hierarchical
- Not handling loading and error states
- Forgetting to disable buttons during mutations (isPending)
Data Display:
- CRITICAL: Dividing prices by 100 when displaying (prices are stored as-is: $49.99 = 49.99, NOT in cents)
Error Handling:
- Not implementing onError callbacks
- Not showing error messages to users
- Not handling network failures gracefully
How to Use
For detailed patterns and examples, load reference file:
references/frontend-integration.md - SDK usage, React Query patterns, API integration
The reference file contains:
- Step-by-step SDK integration patterns
- Complete React Query examples
- Correct vs incorrect code examples
- Query key best practices
- Optimistic update patterns
- Error handling strategies
When to Use MedusaDocs MCP Server
Use this skill for (PRIMARY SOURCE):
- How to call custom API routes from storefront
- SDK usage patterns (sdk.client.fetch)
- React Query integration patterns
- Common mistakes and anti-patterns
Use MedusaDocs MCP server for (SECONDARY SOURCE):
- Built-in SDK methods (sdk.admin., sdk.store.)
- Official Medusa SDK API reference
- Framework-specific configuration options
Why skills come first:
- Skills contain critical patterns like "don't use JSON.stringify" that MCP doesn't emphasize
- Skills show correct vs incorrect patterns; MCP shows what's possible
- Planning requires understanding patterns, not just API reference
Integration with Backend
⚠️ CRITICAL: ALWAYS use the Medusa JS SDK - NEVER use regular fetch()
When building features that span backend and frontend:
- Backend (building-with-medusa skill): Module → Workflow → API Route
- Storefront (this skill): SDK → React Query → UI Components
- Connection:
- Built-in endpoints: Use existing SDK methods (
sdk.store.product.list()) - Custom API routes: Use
sdk.client.fetch("/store/my-route") - NEVER use regular fetch() - missing publishable API key causes errors
- Built-in endpoints: Use existing SDK methods (
Why the SDK is required:
- Store routes need
x-publishable-api-keyheader - Admin routes need
Authorizationand session headers - SDK handles all required headers automatically
- Regular fetch() without headers → authentication/authorization errors
See building-with-medusa for backend API route patterns.
Medusa Backend Development
Comprehensive backend development guide for Medusa applications. Contains patterns across 6 categories covering architecture, type safety, business logic placement, and common pitfalls.
When to Apply
Load this skill for ANY backend development task, including:
- Creating or modifying custom modules and data models
- Implementing workflows for mutations
- Building API routes (store or admin)
- Defining module links between entities
- Writing business logic or validation
- Querying data across modules
- Implementing authentication/authorization
Also load these skills when:
- building-admin-dashboard-customizations: Building admin UI (widgets, pages, forms)
- building-storefronts: Calling backend API routes from storefronts (SDK integration)
CRITICAL: Load Reference Files When Needed
The quick reference below is NOT sufficient for implementation. You MUST load relevant reference files before writing code for that component.
Load these references based on what you're implementing:
- Creating a module? → MUST load
reference/custom-modules.mdfirst - Creating workflows? → MUST load
reference/workflows.mdfirst - Creating API routes? → MUST load
reference/api-routes.mdfirst - Creating module links? → MUST load
reference/module-links.mdfirst - Querying data? → MUST load
reference/querying-data.mdfirst - Adding authentication? → MUST load
reference/authentication.mdfirst
Minimum requirement: Load at least 1-2 reference files relevant to your specific task before implementing.
Critical Architecture Pattern
ALWAYS follow this flow - never bypass layers:
Module (data models + CRUD operations)
↓ used by
Workflow (business logic + mutations with rollback)
↓ executed by
API Route (HTTP interface, validation middleware)
↓ called by
Frontend (admin dashboard/storefront via SDK)
Key conventions:
- Only GET, POST, DELETE methods (never PUT/PATCH)
- Workflows are required for ALL mutations
- Business logic belongs in workflow steps, NOT routes
- Query with
query.graph()for cross-module data retrieval and filtering across linked modules - Module links maintain isolation between modules
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Architecture Violations | CRITICAL | arch- |
| 2 | Type Safety | CRITICAL | type- |
| 3 | Business Logic Placement | HIGH | logic- |
| 4 | Import & Code Organization | HIGH | import- |
| 5 | Data Access Patterns | MEDIUM (includes CRITICAL price rule) | data- |
| 6 | File Organization | MEDIUM | file- |
Quick Reference
1. Architecture Violations (CRITICAL)
arch-workflow-required- Use workflows for ALL mutations, never call module services from routesarch-layer-bypass- Never bypass layers (route → service without workflow)arch-http-methods- Use only GET, POST, DELETE (never PUT/PATCH)arch-module-isolation- Use module links, not direct cross-module service callsarch-query-config-fields- Don't set explicitfieldswhen usingreq.queryConfig
2. Type Safety (CRITICAL)
type-request-schema- Pass Zod inferred type toMedusaRequest<T>when usingreq.validatedBodytype-authenticated-request- UseAuthenticatedMedusaRequestfor protected routes (notMedusaRequest)type-export-schema- Export both Zod schema AND inferred type from middlewarestype-linkable-auto- Never add.linkable()to data models (automatically added)type-module-name-camelcase- Module names MUST be camelCase, never use dashes (causes runtime errors)
3. Business Logic Placement (HIGH)
logic-workflow-validation- Put business validation in workflow steps, not API routeslogic-ownership-checks- Validate ownership/permissions in workflows, not routeslogic-module-service- Keep modules simple (CRUD only), put logic in workflows
4. Import & Code Organization (HIGH)
import-top-level- Import workflows/modules at file top, never useawait import()in route bodyimport-static-only- Use static imports for all dependenciesimport-no-dynamic-routes- Dynamic imports add overhead and break type checkingimport-zod-framework- Import Zod from@medusajs/framework/zod, never fromzoddirectly. Medusa is on Zod v4 (since v2.14.0): usez.email()/z.url()/z.uuid()instead ofz.string().email()etc.,.extend(other.shape)instead of.merge(other),z.strictObject()/z.looseObject()instead of.strict()/.passthrough(),z.enum(MyEnum)instead ofz.nativeEnum(), andz.record(z.string(), value)instead ofz.record(value)
5. Data Access Patterns (MEDIUM)
data-price-format- CRITICAL: Prices are stored as-is in Medusa (49.99 stored as 49.99, NOT in cents). Never multiply by 100 when saving or divide by 100 when displayingdata-query-method- Usequery.graph()for retrieving data and filtering across linked modules via cross-module joinsdata-query-graph- Usequery.graph()for cross-module queries with dot notation, including cross-module filtering with nested linked data model filtersdata-list-and-count- UselistAndCountfor single-module paginated queriesdata-linked-filtering- Usequery.graph()with nested linked data model filters to filter by linked module fields;query.index()is deprecated since v2.22.7data-no-js-filter- Don't use JavaScript.filter()on linked data - use database filters (query.graph()with nested filters or query the entity)data-same-module-ok- Can filter by same-module relations withquery.graph()(e.g., product.variants)data-auth-middleware- Trustauthenticatemiddleware, don't manually checkreq.auth_context
6. File Organization (MEDIUM)
file-workflow-steps- Recommended: Create steps insrc/workflows/steps/[name].tsfile-workflow-composition- Composition functions insrc/workflows/[name].tsfile-middleware-exports- Export schemas and types from middleware filesfile-links-directory- Define module links insrc/links/[name].ts
Workflow Composition Rules
The workflow function has critical constraints:
// ✅ CORRECT
const myWorkflow = createWorkflow(
"name",
function (input) { // Regular function, not async, not arrow
const result = myStep(input) // No await
return new WorkflowResponse(result)
}
)
// ❌ WRONG
const myWorkflow = createWorkflow(
"name",
async (input) => { // ❌ No async, no arrow functions
const result = await myStep(input) // ❌ No await
if (input.condition) { /* ... */ } // ❌ No conditionals
return new WorkflowResponse(result)
}
)
Constraints:
- No async/await (runs at load time)
- No arrow functions (use
function) - No conditionals/ternaries (use
when()) - No variable manipulation (use
transform()) - No date creation (use
transform()) - Multiple step calls need
.config({ name: "unique-name" })to avoid conflicts
Common Mistakes Checklist
Before implementing, verify you're NOT doing these:
Architecture:
- Calling module services directly from API routes
- Using PUT or PATCH methods
- Bypassing workflows for mutations
- Setting
fieldsexplicitly withreq.queryConfig - Skipping migrations after creating module links
Type Safety:
- Forgetting
MedusaRequest<SchemaType>type argument - Using
MedusaRequestinstead ofAuthenticatedMedusaRequestfor protected routes - Not exporting Zod inferred type from middlewares
- Adding
.linkable()to data models - Using dashes in module names (must be camelCase)
Business Logic:
- Validating business rules in API routes
- Checking ownership in routes instead of workflows
- Manually checking
req.auth_context?.actor_idwhen middleware already applied
Imports:
- Using
await import()in route handler bodies - Dynamic imports for workflows or modules
Data Access:
- CRITICAL: Multiplying prices by 100 when saving or dividing by 100 when displaying (prices are stored as-is: $49.99 = 49.99)
- Using JavaScript
.filter()on linked data (usequery.graph()with nested filters or query the linked entity directly) - Not using
query.graph()for cross-module data retrieval and filtering - Using the deprecated
query.index()method (usequery.graph()with nested linked data model filters instead)
Validating Implementation
CRITICAL: Always run the build command after completing implementation to catch type errors and runtime issues.
When to Validate
- After implementing any new feature
- After making changes to modules, workflows, or API routes
- Before marking tasks as complete
- Proactively, without waiting for the user to ask
How to Run Build
Detect the package manager and run the appropriate command:
npm run build # or pnpm build / yarn build
Handling Build Errors
If the build fails:
- Read the error messages carefully
- Fix type errors, import issues, and syntax errors
- Run the build again to verify the fix
- Do NOT mark implementation as complete until build succeeds
Common build errors:
- Missing imports or exports
- Type mismatches (e.g., missing
MedusaRequest<T>type argument) - Incorrect workflow composition (async functions, conditionals)
Linting
Since Medusa v2.16.0, projects can install @medusajs/eslint-plugin, which catches violations of Medusa conventions (API routes, subscribers, scheduled jobs, admin customizations, module patterns) that a type check won't.
- If the project has an
eslint.config.*with@medusajs/eslint-plugin,medusa buildandmedusa developrun linting by default and fail on lint errors. Fix lint errors rather than passing--no-lint. - Run linting explicitly with
npx medusa lint(supports--fixand--quiet). Run it after implementing a feature, alongside the build. - If the project has no ESLint config, suggest adding it (
@medusajs/eslint-plugin,eslint, andjitias dev dependencies, then aneslint.config.tsexportingdefineConfig([...medusa.configs.recommended])) — but don't add it unprompted.
Next Steps - Testing Your Implementation
After successfully implementing a feature, always provide these next steps to the user:
1. Start the Development Server
If the server isn't already running, start it:
npm run dev # or pnpm dev / yarn dev
2. Access the Admin Dashboard
Open your browser and navigate to:
- Admin Dashboard: http://localhost:9000/app
Log in with your admin credentials to test any admin-related features.
3. Test API Routes
If you implemented custom API routes, list them for the user to test:
Admin Routes (require authentication):
POST http://localhost:9000/admin/[your-route]- Description of what it doesGET http://localhost:9000/admin/[your-route]- Description of what it does
Store Routes (public or customer-authenticated):
POST http://localhost:9000/store/[your-route]- Description of what it doesGET http://localhost:9000/store/[your-route]- Description of what it does
Testing with cURL example:
# Admin route (requires authentication)
curl -X POST http://localhost:9000/admin/reviews/123/approve \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
--cookie "connect.sid=YOUR_SESSION_COOKIE"
# Store route
curl -X POST http://localhost:9000/store/reviews \
-H "Content-Type: application/json" \
-d '{"product_id": "prod_123", "rating": 5, "comment": "Great product!"}'
4. Additional Testing Steps
Depending on what was implemented, mention:
- Workflows: Test mutation operations and verify rollback on errors
- Subscribers: Trigger events and check logs for subscriber execution
- Scheduled jobs: Wait for job execution or check logs for cron output
Format for Presenting Next Steps
Always present next steps in a clear, actionable format after implementation:
## Implementation Complete
The [feature name] has been successfully implemented. Here's how to test it:
### Start the Development Server
[server start command based on package manager]
### Access the Admin Dashboard
Open http://localhost:9000/app in your browser
### Test the API Routes
I've added the following routes:
**Admin Routes:**
- POST /admin/[route] - [description]
- GET /admin/[route] - [description]
**Store Routes:**
- POST /store/[route] - [description]
### What to Test
1. [Specific test case 1]
2. [Specific test case 2]
3. [Specific test case 3]
How to Use
For detailed patterns and examples, load reference files:
reference/custom-modules.md - Creating modules with data models
reference/workflows.md - Workflow creation and step patterns
reference/api-routes.md - API route structure and validation
reference/module-links.md - Linking entities across modules
reference/querying-data.md - Query patterns and filtering rules
reference/authentication.md - Protecting routes and accessing users
reference/error-handling.md - MedusaError types and patterns
reference/scheduled-jobs.md - Cron jobs and periodic tasks
reference/subscribers-and-events.md - Event handling
reference/troubleshooting.md - Common errors and solutions
Each reference file contains:
- Step-by-step implementation checklists
- Correct vs incorrect code examples
- TypeScript patterns and type safety
- Common pitfalls and solutions
When to Use This Skill vs MedusaDocs MCP Server
⚠️ CRITICAL: This skill should be consulted FIRST for planning and implementation.
Use this skill for (PRIMARY SOURCE):
- Planning - Understanding how to structure Medusa backend features
- Architecture - Module → Workflow → API Route patterns
- Best practices - Correct vs incorrect code patterns
- Critical rules - What NOT to do (common mistakes and anti-patterns)
- Implementation patterns - Step-by-step guides with checklists
Use MedusaDocs MCP server for (SECONDARY SOURCE):
- Specific method signatures after you know which method to use
- Built-in module configuration options
- Official type definitions
- Framework-level configuration details
Why skills come first:
- Skills contain opinionated guidance and anti-patterns MCP doesn't have
- Skills show architectural patterns needed for planning
- MCP is reference material; skills are prescriptive guidance
Integration with Frontend Applications
⚠️ CRITICAL: Frontend applications MUST use the Medusa JS SDK for ALL API requests
When building features that span backend and frontend:
For Admin Dashboard:
- Backend (this skill): Module → Workflow → API Route
- Frontend: Load
building-admin-dashboard-customizationsskill - Connection:
- Built-in endpoints: Use existing SDK methods (
sdk.admin.product.list()) - Custom API routes: Use
sdk.client.fetch("/admin/my-route") - NEVER use regular fetch() - missing auth headers will cause errors
- Built-in endpoints: Use existing SDK methods (
For Storefronts:
- Backend (this skill): Module → Workflow → API Route
- Frontend: Load
building-storefrontsskill - Connection:
- Built-in endpoints: Use existing SDK methods (
sdk.store.product.list()) - Custom API routes: Use
sdk.client.fetch("/store/my-route") - NEVER use regular fetch() - missing publishable API key will cause errors
- Built-in endpoints: Use existing SDK methods (
Why the SDK is required:
- Store routes need
x-publishable-api-keyheader - Admin routes need
Authorizationand session headers - SDK handles all required headers automatically
- Regular fetch() without headers → authentication/authorization errors
See respective frontend skills for complete integration patterns.
Creating Agents in Medusa
This skill covers the full stack for adding an internal, admin-facing AI agent to a Medusa project. These agents are used by merchants and store operators through the Medusa admin dashboard — not by customers on a storefront. For customer-facing agents (e.g. a storefront chatbot), a different architecture is needed: public API routes, no MedusaExec, and storefront auth.
Constraints
- Internal use only — this architecture is for admin users (merchants, operators, support staff), not customers. Routes live under
src/api/admin/, the UI lives in the Medusa admin dashboard, and access is gated by admin authentication throughout. - Authentication is non-negotiable — MedusaExec runs arbitrary TypeScript with full database access. All agent routes must use
AuthenticatedMedusaRequestand live undersrc/api/admin/. An unauthenticated endpoint is a remote code execution vulnerability. - Use MedusaExec, not custom tools — for any data operation, the agent writes TypeScript and executes it via MedusaExec. Only build a custom tool for capabilities that cannot be expressed as executable TypeScript (e.g. calling an external API with a secret key).
- One shared module, multiple agents —
AgentSessionandAgentMessageare shared infrastructure. Useagent_typeto distinguish sessions per agent. Never create separate models per agent. - Pass
MedusaContainerviaexperimental_context— never import services directly in tool files; that causes circular dependencies. - Stream format is NDJSON —
Content-Type: application/x-ndjson, one JSON object per line followed by\n. - Run migrations after adding or changing models (
npx medusa db:generate agent && npx medusa db:migrate). - Tool descriptions live in config, not inline in
tool()— the config object overrides them at runtime.
CRITICAL: Load Reference Files When Needed
⚠️ The quick reference below is NOT sufficient for implementation. Load the relevant reference file before writing any code.
| Task | Load this file |
|---|---|
| Defining conversation models | reference/data-models.md |
| Setting up the module service | reference/service.md |
| Configuring tools, prompt, streamText | reference/agent-setup.md |
| Building the POST chat endpoint | reference/api-route.md |
| Implementing NDJSON streaming | reference/streaming.md |
| Building the admin chat UI | reference/admin-extension.md |
| Giving the agent code execution capability | reference/medusa-exec.md |
Minimum requirement: Load at least the reference file matching your current task before writing code.
Related Skills
Load these alongside this skill when relevant:
building-with-medusa— Medusa module patterns, workflows, data model conventions. Load when implementing the module service or custom backend logic.building-admin-dashboard-customizations— Admin UI component patterns, TanStack Query, route registration. Load when building or extending the admin chat UI.
Architecture Overview
src/modules/agent/
index.ts ← Module() export + AGENT_MODULE constant
service.ts ← MedusaService + Anthropic client + stream(messages, container, config)
models/
session.ts ← AgentSession (shared across all agents, filtered by agent_type)
message.ts ← AgentMessage
agents/index.ts ← streamText() orchestration
tools/
medusa-exec.ts ← MedusaExec tool (primary tool for all data operations)
todo-write.ts ← TodoWrite tool
config/
<agent-type>.ts ← per-agent system prompt + tool descriptions
src/api/admin/agent/<agent-type>/
route.ts ← POST (AuthenticatedMedusaRequest, session lifecycle, NDJSON stream)
sessions/route.ts ← GET session list (filtered by agent_type)
sessions/[id]/route.ts ← GET messages for a session
src/admin/routes/<agent-type>/
page.tsx ← React chat UI (admin extension)
src/lib/code-mode/
executor.ts ← sandboxed TypeScript executor used by MedusaExec
Common Mistakes
Verify you are NOT doing these:
Security:
- Agent route uses
MedusaRequestinstead ofAuthenticatedMedusaRequest - Agent route placed outside
src/api/admin/
Architecture:
- Creating separate
AgentSession/AgentMessagemodels per agent instead of usingagent_type - Importing services directly in tool files instead of resolving from
experimental_context - Building a custom tool for a data operation instead of using MedusaExec
Streaming:
- Missing
res.end()after the stream loop (response never closes) - Missing
Transfer-Encoding: chunkedorContent-Type: application/x-ndjsonheaders - Not buffering incomplete lines on the client (JSON parse errors on split packets)
Module:
- Forgetting to register the module in
medusa-config.ts - Forgetting to run migrations after changing models
- Hardcoding tool descriptions in
tool()instead of the config object
Reference Files Available
reference/data-models.md - model.define(), agent_type discriminator, relationships, migrations
reference/service.md - MedusaService extension, Anthropic init, stream(), module index, config registration
reference/agent-setup.md - streamText(), MedusaExec tool wiring, system prompt, context passing
reference/api-route.md - POST route, session lifecycle, message persistence, streaming headers
reference/streaming.md - NDJSON emission, fullStream iteration, chunk types, client-side parsing
reference/admin-extension.md - React chat UI, streaming fetch, message rendering, tool call display, session sidebar
reference/medusa-exec.md - Executor setup, MedusaExec tool, query.graph() patterns, error codes
Testing
Once the agent is implemented, test it end-to-end directly in the admin dashboard:
- Start the Medusa dev server (
npx medusa develop) - Open the admin dashboard and navigate to the agent's page in the sidebar (the label set in
defineRouteConfig) - Type a simple read-only prompt — e.g. "How many products are in the store?" — and submit
- Verify the response streams in and a new session appears in the sidebar
- Send a follow-up message in the same session to confirm conversation history is preserved
- Reload the page, select the session from the sidebar, and confirm the message history is restored from the database
If anything is broken, check:
- Browser network tab — the POST request should return
Content-Type: application/x-ndjsonwith chunked lines - Server logs —
[agent] tool_calland[agent] step_finishlines confirm the agent is running - Database —
agent_sessionandagent_messagetables should have rows with the correctagent_type
Generate Database Migrations
Generate database migrations for the specified Medusa module.
The user will provide the module name as an argument (e.g., brand, product, custom-module).
For example: /medusa-dev:db-generate brand
Use the Bash tool to execute the command npx medusa db:generate <module-name>, replacing <module-name> with the provided argument.
Report the results to the user, including:
- The module name for which migrations were generated
- Migration file name or location
- Any errors or warnings
- Next steps (running
npx medusa db:migrateto apply the migrations)
Run Database Migrations
Execute the Medusa database migration command to apply pending migrations.
Use the Bash tool to execute: npx medusa db:migrate
Report the migration results to the user, including:
- Number of migrations applied
- Any errors that occurred
- Success confirmation
Create Admin User
Create a new admin user in Medusa with the specified email and password.
The user will provide two arguments:
- First argument: email address
- Second argument: password
For example: /medusa-dev:user admin@test.com supersecret
Use the Bash tool to execute the command npx medusa user -e <email> -p <password>, replacing <email> with the first argument and <password> with the second argument.
Report the results to the user, including:
- Confirmation that the admin user was created successfully
- The email address of the created user
- Any errors that occurred
- Next steps (e.g., logging in to the admin dashboard)
MCP servers 1
Sponsors
Details
- Marketplace
- medusajs/medusa-agent-skills
- Source
- plugins/medusa-dev
- Category
- Community