by Kira

Medusa is a modular, open-source commerce platform providing composable building blocks—carts, orders, payments, fulfillment, promotions, and more—for developers building custom B2B, DTC, or marketplace applications.
This block is the core server source for the Medusa Commerce Backend (packages/medusa/src). It provides the full REST API surface (admin, store, auth, hooks), loader infrastructure, module wiring, workflow execution, and all supporting utilities for a self-hosted Medusa v2 application. The typical buyer is a Node.js/TypeScript team embedding or extending a Medusa backend inside their own monorepo or service.
api/ - Express route handlers and middleware for every admin, store, auth, and webhook endpointapi/admin/ - Admin REST endpoints grouped by resource (orders, products, promotions, price-lists, etc.)api/store/ - Storefront-facing REST endpointsapi/auth/ - Authentication routes (JWT, session)api/hooks/ - Webhook/event ingress routesapi/cloud/ - Medusa Cloud integration routesapi/utils/ - Shared validators and response helpers used across route filesapi/middlewares.ts - Global Express middleware registrationcommands/ - CLI command implementations (start, migrate, seed, etc.)core-flows/ - Pre-built Medusa workflow definitions (order, cart, fulfillment, etc.)feature-flags/ - Feature flag definitions and runtime checksinstrumentation/ - OpenTelemetry / tracing setuploaders/ - Application bootstrap loaders (modules, plugins, express, jobs)migration-scripts/ - Data-migration helpers for version upgradesmodules/ - Local module overrides and registrationspolicies/ - RBAC / access-policy definitionssubscribers/ - Event-bus subscriber registrationstypes/ - Shared TypeScript type definitions exported from the package rootutils/ - General-purpose utilities (cleanResponseData, etc.)index.ts - Package entry point; re-exports Commands, types, utils, and instrumentationnpm install @medusajs/medusa @medusajs/framework @medusajs/utils
npm install express
npm install @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node
npm install typeorm reflect-metadata
npm install dotenv
Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 084332564b5f19c6…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
@medusajs/frameworkand@medusajs/utilsare first-party peer packages consumed heavily insideapi/andutils/. They must be present at the same major version as the installed@medusajs/medusa. No native build steps (pods, NDK) are required; this is a pure Node.js package.
Drop the source. Place the contents of source/ at src/medusa-core/ (or any path you prefer) inside your TypeScript project.
tsconfig.json – enable decorators and path aliases:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "CommonJS",
"target": "ES2020",
"strict": true,
"paths": {
"@medusa-core/*": ["./src/medusa-core/*"]
}
}
}
Environment variables – create .env:
DATABASE_URL=postgres://user:pass@localhost:5432/medusa
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-jwt-secret
COOKIE_SECRET=your-cookie-secret
NODE_ENV=development
Entry point – load reflect-metadata before anything else, then use the loaders:
import "reflect-metadata"
import dotenv from "dotenv"
dotenv.config()
// import and invoke loaders from source/loaders/
Run migrations via the Commands export (see examples below) before starting the server.
import { Commands } from "@medusa-core/index"
// Commands is a namespace object:
// Commands.migrate(options)
// Commands.start(options)
// Commands.seed(options)
The Commands namespace aggregates every CLI command implementation from source/commands/. Use it to programmatically trigger database migrations, server start, or seeding within custom scripts or test harnesses without invoking the Medusa CLI binary.
import { buildPriceListResponse } from "@medusa-core/api/admin/price-lists/queries"
function buildPriceListResponse(
priceLists: any[],
apiFields: string[]
): AdminPriceListRemoteQueryDTO[]
Takes raw price-list records from the remote query (including nested price_list_rules and prices), normalises rules via buildPriceListRules, expands prices via buildPriceSetPricesForCore, and strips any fields not listed in apiFields using cleanResponseData. Call this in any custom admin route that returns price-list data to ensure consistent shape.
import {
buildPriceListRules,
buildPriceSetPricesForCore,
} from "@medusajs/framework/utils"
const rules = buildPriceListRules(rawPriceList.price_list_rules)
const prices = buildPriceSetPricesForCore(rawPriceList.prices)
buildPriceListRules converts the raw join-table price_list_rules array into a flat key→value rule map. buildPriceSetPricesForCore flattens price-set money amounts into the core price shape expected by admin clients. Both are consumed inside buildPriceListResponse; call them directly when you need lower-level access.
Invoke the built-in migrate command from application code instead of the CLI, useful in test setup or custom deploy scripts.
import "reflect-metadata"
import dotenv from "dotenv"
dotenv.config()
import { Commands } from "./src/medusa-core/index"
async function runMigrations() {
await (Commands as any).migrate({
directory: process.cwd(),
})
console.log("Migrations complete")
}
runMigrations().catch(console.error)
Wrap the helper in an Express handler to return normalised price-list data with only the fields your client needs.
import { Router, Request, Response } from "express"
import { buildPriceListResponse } from "./src/medusa-core/api/admin/price-lists/queries"
const router = Router()
router.get("/admin/custom/price-lists", async (req: Request, res: Response) => {
// assume rawPriceLists fetched from remoteQuery
const rawPriceLists: any[] = (req as any).priceLists ?? []
const apiFields = [
"id",
"name",
"status",
"rules",
"prices",
"starts_at",
"ends_at",
]
const result = buildPriceListResponse(rawPriceLists, apiFields)
res.json({ price_lists: result, count: result.length })
})
export default router
The promotions utils expose operator maps and attribute validators used by the admin promotion engine. Reuse them in a custom promotion-rules validation service.
import {
operatorsMap,
validateRuleAttribute,
validateRuleType,
} from "./src/medusa-core/api/admin/promotions/utils"
interface RuleInput {
attribute: string
operator: string
type: string
values: unknown[]
}
function validatePromotionRule(rule: RuleInput): string[] {
const errors: string[] = []
const attrError = validateRuleAttribute(rule.attribute)
if (attrError) errors.push(attrError)
const typeError = validateRuleType(rule.type)
if (typeError) errors.push(typeError)
if (!operatorsMap[rule.operator]) {
errors.push(`Unknown operator: ${rule.operator}`)
}
return errors
}
const issues = validatePromotionRule({
attribute: "customer.groups",
operator: "in",
type: "rules",
values: ["vip"],
})
console.log(issues) // [] on valid input
Commands, all types, all utils, and all instrumentation symbols; the single entry point for external consumers.common, products) used across multiple resource routes.migrate, start, seed, and other CLI sub-commands, consumed by index.ts as the Commands namespace.index.ts for host apps to initialise tracing.@medusajs/framework defaults.cleanResponseData used throughout the API layer.reflect-metadata import – Decorators silently fail at runtime; add import "reflect-metadata" as the very first line of your entry point.@medusajs/framework version mismatch – The API layer calls internal framework utils directly; pin @medusajs/framework to the exact same minor version as @medusajs/medusa in your package.json.DATABASE_URL not set before loaders run – Loaders read env vars synchronously at import time; call dotenv.config() before any import from this source (use a dedicated env.ts bootstrapper)."module": "CommonJS" in tsconfig.json; TypeORM decorators break under native ESM in Node.js <22.emitDecoratorMetadata missing – Entity relationship resolution fails silently; ensure both experimentalDecorators and emitDecoratorMetadata are true in tsconfig.json.Commands.migrate; some migration-scripts are destructive and not reversible.I have dropped the Medusa Commerce Backend core source into `src/medusa-core/`
(upstream package: `@medusajs/medusa`, domain: `backend`).
The integration reference is in `USAGE.md` at the project root.
Please help me integrate this source into my existing Node.js/TypeScript/Express
project step by step:
1. Read `USAGE.md` fully before writing any code.
2. Add the required dependencies from the "Required dependencies" section to
my `package.json` and run `npm install`.
3. Update `tsconfig.json` with the settings in "Project setup".
4. Create a `.env` file with all variables listed in "Project setup".
5. Wire `src/medusa-core/loaders/` into my Express app entry point, ensuring
`reflect-metadata` is the first import.
6. Add a migration script using `Commands` from `src/medusa-core/index.ts`.
7. Show me how to add a custom admin route that calls `buildPriceListResponse`
from `src/medusa-core/api/admin/price-lists/queries`.
8. Point out any conflicts with my existing code and suggest fixes.
Use only the exports documented in `USAGE.md` - do not invent new APIs.
Licensed under the MIT License. Source is part of the medusajs/medusa monorepo. Upstream npm package: @medusajs/medusa. See source/LICENSE if present in your copy of the source.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
eCommerce, Marketplace & POS Systems
$14.11