1 # Medusa Development Conventions
2
3 Conventions to verify when reviewing code contributions. Focus on areas relevant to the changed files.
4
5 ## API Changes
6
7 - **Integration tests required**: Changes to `packages/medusa/src/api/` must include corresponding changes in `integration-tests/http/__tests__/`.
8 - **Zod validation**: API routes that accept a request body must validate it with a Zod schema. Look for a `validator` middleware or a `.zod.ts` schema file alongside the route.
9 - **HTTP types**: Zod schema changes must be reflected in HTTP types. These can be generated using `packages/cli/http-types-generator`. If a Zod schema changed but no HTTP type changed, flag it.
10 - **Typed route arguments**: Request and response types for API routes must use type arguments for query params, request body, and response. The types must be HTTP types from `@medusajs/framework/types`. Example:
11 ```typescript
12 // Correct
13 export const POST = async (
14 req: AuthenticatedMedusaRequest<AdminCreateOrderBody>,
15 res: MedusaResponse<AdminOrderResponse>
16 ) => { ... }
17
18 // Wrong — missing type arguments
19 export const POST = async (req: AuthenticatedMedusaRequest, res: MedusaResponse) => { ... }
20 ```
21
22 ## Code Comments
23
24 - **No issue/PR references in code**: Comments in source files must not reference GitHub issue or PR numbers, or link to issues/PRs. The relationship between a change and an issue belongs in the PR body and commit messages — not in the code, where it becomes stale, meaningless out of context, and noise for future readers. Flag any added comment that references an issue/PR, such as:
25 ```typescript
26 // ❌ Wrong — references an issue/PR
27 // fixes #1234
28 // see PR #5678
29 // related to https://github.com/medusajs/medusa/issues/1234
30 // this handles the edge case reported in issue 4321
31 ```
32 Ask the author to remove the reference (moving any needed context into the comment as a plain explanation, or into the PR description). This is a required change.
33
34 ## Naming Conventions
35
36 - **Object properties**: snake_case (`region_id`, `created_at`)
37 - **Variables and function parameters**: camelCase (`regionId`, `createdAt`)
38 - **Private/protected class properties**: suffixed with `_` (`this.service_`, `protected manager_`)
39 - **File names**: kebab-case (`order-module-service.ts`, `delete-promotions.ts`)
40 - **Variable names must be readable** — avoid abbreviations like `ord`, `rej`, `tmp`
41
42 ## Code Style
43
44 - No semicolons
45 - Double quotes for strings
46 - 2-space indentation
47 - ES5 trailing commas
48 - Arrow functions always use parentheses around parameters: `(x) => x + 1`
49
50 ## Architecture Patterns
51
52 - **Services**: Must extend `MedusaService`. Public methods use `@InjectManager()`. Protected methods (for transactions) use `@InjectTransactionManager()`. Both accept `@MedusaContext() sharedContext: Context = {}` as the last parameter.
53 - **Mutations**: Must go through workflows (`createWorkflow` / `createStep`). API routes must not call module services directly for writes.
54 - **Errors**: Use `new MedusaError(MedusaError.Types.NOT_FOUND, "...")` — never raw `throw new Error(...)`.
55 - **Barrel exports**: Use `export * from` for module re-exports.
56 - **Step compensation**: `createStep` should include a compensation function when the step has side effects that can be rolled back.
57
58 ## Testing
59
60 - Unit tests: `__tests__/` directories alongside source, `.spec.ts` or `.test.ts` suffix.
61 - Integration tests for HTTP routes: `integration-tests/http/__tests__/`.
62 - New functionality must have tests. Minor bug fixes may omit tests if the fix is trivial and clear, but tests are always preferred.
63
64 ## Security Requirements
65
66 - **Authentication**: All new admin routes must include `authenticate("user", ["bearer", "session", "api-key"])` middleware. Store routes that require authentication must use `authenticate("customer", ...)`.
67 - **Input validation**: All fields accepted from request bodies must be declared in the Zod schema. Unknown fields should be stripped, not passed through.
68 - **No raw SQL**: Use the ORM query builder. Do not construct SQL strings from user-provided values.
69 - **No sensitive fields in responses**: Passwords, secrets, and internal tokens must not appear in HTTP type definitions or serialized responses.
70 - **No hardcoded secrets**: Credentials, API keys, and tokens must come from environment variables via `configModule` — never committed to source.
71 - **Filesystem operations**: Paths constructed from user input must be normalized and validated to prevent path traversal (e.g., reject paths containing `..`).
72
73 ## Performance Requirements
74
75 - **Pagination required**: List routes must pass `pagination: req.queryConfig.pagination` (which contains `{ skip, take, order? }`) to every query. Never omit pagination. The framework enforces a default `take` of 50; custom defaults must be set in the route's `queryConfig` — not hardcoded in the handler.
76
77 - **No unbounded queries**: Any call to `query.graph()`, `query.index()`, `remoteQueryObjectFromString()`, or a direct service method that fetches a list must include pagination. Omitting it means a full-table scan. Example of correct usage:
78
79 ```typescript
80 // ✅ Correct
81 const { data, metadata } = await query.graph({
82 entity: "order",
83 fields: req.queryConfig.fields,
84 filters: req.filterableFields,
85 pagination: req.queryConfig.pagination,
86 })
87
88 // ❌ Wrong — no pagination
89 const { data } = await query.graph({
90 entity: "order",
91 fields: req.queryConfig.fields,
92 })
93 ```
94
95 - **Response must include count/offset/limit**: List route responses must always return `count`, `offset` (`metadata.skip`), and `limit` (`metadata.take`) alongside the items array so clients can paginate. Omitting these is a bug.
96
97 - **No N+1 queries**: Do not call `query.graph()` or any service method inside a loop over a result set. Instead, batch-fetch all related records in a single query before the loop using `filters: { id: ids }`.
98
99 - **Async parallelism**: Use `Promise.all()` when multiple independent async operations can run concurrently. Sequential `await` in a loop is a red flag.
100
101 - **Database indexes**: New fields used in `filters` or `order` inside a `query.graph()` / `remoteQueryObjectFromString()` call must have a corresponding index in the entity decorator or migration.