The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
docs: add best practices guide for developing with Mercur (#1215)
Viktor Holik90a56e85cf50
diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 8804d6c2c..d22714ab0 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -124,6 +124,20 @@"rc/resources/integrations/notifications"]},+ {+ "group": "Best practices",+ "pages": [+ "rc/resources/best-practices/overview",+ "rc/resources/best-practices/modules",+ "rc/resources/best-practices/module-links",+ "rc/resources/best-practices/workflows",+ "rc/resources/best-practices/api-routes",+ "rc/resources/best-practices/subscribers-and-jobs",+ "rc/resources/best-practices/types",+ "rc/resources/best-practices/custom-fields",+ "rc/resources/best-practices/frontend"+ ]+ },{"group": "Deployment","pages": [diff --git a/apps/docs/rc/resources/best-practices/api-routes.mdx b/apps/docs/rc/resources/best-practices/api-routes.mdxnew file mode 100644index 000000000..e88e8e43e--- /dev/null+++ b/apps/docs/rc/resources/best-practices/api-routes.mdx@@ -0,0 +1,304 @@+---+title: "API routes"+description: "Thin HTTP adapters — typed request/response generics, Zod validation with createFindParams, filterable fields, middlewares as filters, and queryConfig."+---++An API route is a thin adapter between HTTP and the rest of the system. Its whole job is: validate the request, run a [workflow](/rc/resources/best-practices/workflows) (for writes) or a [Query](/rc/resources/best-practices/workflows#the-query-engine) (for reads), and shape the response. No business logic lives here.++<Note>+ Routes are [Medusa file-based API routes](https://docs.medusajs.com/learn/fundamentals/api-routes): a `route.ts` under `src/api/**` exports handlers named after HTTP verbs, and a sibling `middlewares.ts` wires validation and filters. Examples below use a custom **Brand** module exposed under `/admin/brands`.+</Note>++## Type both the request and the response++Every handler is typed on **both** sides — mirror how Medusa's own routes are written:++- `AuthenticatedMedusaRequest<TBodyOrQuery>` — the generic is the validated **body** (writes) or **query params** (reads) type.+- `MedusaResponse<TResponse>` — the generic is the **response shape**, so `res.json(...)` is checked and the SDK infers a real return type instead of `unknown`.++```ts title="src/api/admin/brands/route.ts"+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework/http"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import { createBrandsWorkflow } from "../../../workflows/create-brands"+import {+ AdminCreateBrandType,+ AdminGetBrandsParamsType,+} from "./validators"+import { AdminBrandListResponse, AdminBrandResponse } from "./types"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminGetBrandsParamsType>,+ res: MedusaResponse<AdminBrandListResponse>+) => {+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)++ const { data: brands, metadata } = await query.graph({+ entity: "brand",+ fields: req.queryConfig.fields,+ filters: req.filterableFields,+ pagination: req.queryConfig.pagination,+ })++ res.json({+ brands,+ count: metadata!.count,+ offset: metadata!.skip,+ limit: metadata!.take,+ })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminCreateBrandType>,+ res: MedusaResponse<AdminBrandResponse>+) => {+ const { result } = await createBrandsWorkflow(req.scope).run({+ input: { brands: [req.validatedBody] },+ })++ res.json({ brand: result[0] })+}+```++<Warning>+ Don't leave `MedusaResponse` bare. An untyped response means `res.json({...})` accepts anything and the typed SDK resolves that endpoint to an empty/`unknown` response — the exact opposite of the point of the typed client. Always pass the response generic.+</Warning>++## Only `GET`, `POST`, `DELETE`++<Warning>+ Mercur routes use **only** `GET`, `POST`, and `DELETE`. There is no `PUT` or `PATCH` — model an update as a `POST` to the resource. Keeping to three verbs is what keeps the typed SDK (`.query` / `.mutate` / `.delete`) consistent across every route.+</Warning>++| Verb | Meaning | SDK method |+| --- | --- | --- |+| `GET` | Read (list or retrieve) | `.query()` |+| `POST` | Create **and** update | `.mutate()` |+| `DELETE` | Remove | `.delete()` |++## Validation with Zod + exported types++Validation happens in `middlewares.ts` via `validateAndTransformBody` / `validateAndTransformQuery`, and every schema exports its inferred type so the handler generic and the SDK share one source of truth.++**Bodies** are plain Zod objects:++```ts title="src/api/admin/brands/validators.ts"+import { z } from "zod"++export const AdminCreateBrand = z.object({+ name: z.string(),+ is_active: z.boolean().optional(),+})++export type AdminCreateBrandType = z.infer<typeof AdminCreateBrand>+```++**List/read params** use the framework helpers — `createFindParams` (pagination + `fields` + `order`) and `createSelectParams` (retrieve) — rather than a hand-rolled object. This is what wires pagination and field selection consistently across every route:++```ts title="src/api/admin/brands/validators.ts"+import { createFindParams, createOperatorMap } from "@medusajs/medusa/api/utils/validators"++export const AdminGetBrandsParams = createFindParams({+ limit: 20,+ offset: 0,+}).merge(+ z.object({+ // declare the fields that may be filtered on+ id: z.union([z.string(), z.array(z.string())]).optional(),+ name: z.string().optional(),+ is_active: z.boolean().optional(),+ created_at: createOperatorMap().optional(), // gt/lt/gte/lte ranges+ })+)++export type AdminGetBrandsParamsType = z.infer<typeof AdminGetBrandsParams>+```++The handler then trusts `req.validatedBody` / the validated query to already match those types — never re-validate inside the handler.++## List vs retrieve++A list route (`GET /admin/brands`) and a retrieve route (`GET /admin/brands/:id`) select fields the same way but differ in their params helper and response shape. Retrieve uses `createSelectParams` (field selection only — no pagination or filters) and returns a single entity:++```ts title="src/api/admin/brands/[id]/route.ts"+export const GET = async (+ req: AuthenticatedMedusaRequest<AdminGetBrandParamsType>,+ res: MedusaResponse<AdminBrandResponse>+) => {+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)++ const {+ data: [brand],+ } = await query.graph({+ entity: "brand",+ fields: req.queryConfig.fields,+ filters: { id: req.params.id },+ })++ if (!brand) {+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Brand ${req.params.id} not found`)+ }++ res.json({ brand })+}+```++```ts title="src/api/admin/brands/validators.ts — retrieve params"+import { createSelectParams } from "@medusajs/medusa/api/utils/validators"++export const AdminGetBrandParams = createSelectParams()+export type AdminGetBrandParamsType = z.infer<typeof AdminGetBrandParams>+```++Both share the same `defaults` idea but declare them separately in the query config (`list` vs `retrieve`) — see [`queryConfig`](/rc/resources/best-practices/api-routes#queryconfig-and-field-selection) below.++## Filterable fields++`req.filterableFields` is the **parsed, validated filter set** produced by `validateAndTransformQuery` from the query params above. Only fields your validator declares can appear there — an unknown query param is dropped, not passed through. The handler forwards it straight to Query:++```ts+const { data: brands, metadata } = await query.graph({+ entity: "brand",+ fields: req.queryConfig.fields,+ filters: req.filterableFields, // e.g. { is_active: true, created_at: { gt: ... } }+ pagination: req.queryConfig.pagination,+})+```++<Tip>+ This is why filtering is declarative and safe: to make a field filterable you add it to the validator; to scope a request you inject onto `req.filterableFields` in middleware (next section). The handler never builds a `where` clause by hand.+</Tip>++## Middlewares as filters++Middlewares aren't only for validation — they're where you inject **scoping filters** so handlers stay ignorant of the rule. A small middleware writes onto `req.filterableFields`; because the handler already forwards that to Query, the scope is applied without the handler knowing. For example, let `GET /admin/products?brand_id=…` filter products by their linked brand:++```ts title="src/api/admin/products/middlewares.ts"+import {+ MedusaRequest,+ MedusaResponse,+ MedusaNextFunction,+} from "@medusajs/framework/http"++const filterByBrand = (+ req: MedusaRequest,+ _res: MedusaResponse,+ next: MedusaNextFunction+) => {+ if (req.query.brand_id) {+ req.filterableFields.brand = { id: req.query.brand_id }+ }+ next()+}++export const adminProductsMiddlewares = [+ {+ method: ["GET"],+ matcher: "/admin/products",+ middlewares: [+ validateAndTransformQuery(AdminGetProductsParams, adminProductQueryConfig.list),+ filterByBrand,+ ],+ },+]+```++<Tip>+ Filtering by a **linked** field (like `brand`) works because the [module link](/rc/resources/best-practices/module-links#filtering-by-links) exists — Query resolves the relation. Applying it in middleware means a new route on the same resource is scoped correctly by construction, not by remembering to add a filter.+</Tip>++## Trust the auth middleware++Authentication and actor resolution happen in middleware (`authenticate`), so by the time your handler runs the actor is already established — **trust it**. Read identity from the request context, never from the body:++```ts+const userId = req.auth_context.actor_id // set by the authenticate middleware+```++<Warning>+ Don't re-derive or re-check identity inside handlers, and don't read user/owner ids from the request body — always take them from `req.auth_context` (or a context object a scoping middleware populated). Trusting the middleware keeps authorization in one place.+</Warning>++## Vendor routes: `seller_context`++Every route under `/vendor/*` is **already authenticated and seller-scoped** — you don't wire auth yourself. By the time your handler runs, the caller is a verified seller member and the request carries a `req.seller_context` you can trust:++```ts+export const POST = async (+ req: AuthenticatedMedusaRequest<VendorCreateOfferType>,+ res: MedusaResponse+) => {+ const sellerId = req.seller_context!.seller_id // the acting seller+ const currency = req.seller_context!.currency_code+ // ...run a workflow scoped to this seller+}+```++`req.seller_context` gives you `seller_id`, `currency_code`, and the `seller_member` — all verified, so you never re-check membership in a handler.++<Warning>+ Never take a `seller_id` from the request body or query to decide ownership — that's caller-supplied. The **only** authoritative seller is `req.seller_context.seller_id`. To scope a vendor list route to the caller's data, add the `filterBySellerId()` middleware and every query is constrained automatically — no per-handler `where`:++ ```ts title="src/api/vendor/offers/middlewares.ts"+ import { filterBySellerId } from "@mercurjs/core/..."++ {+ method: ["GET"],+ matcher: "/vendor/offers",+ middlewares: [+ validateAndTransformQuery(VendorGetOffersParams, vendorOfferQueryConfig.list),+ filterBySellerId(),+ ],+ }+ ```+</Warning>++## `queryConfig` and field selection++`validateAndTransformQuery` takes a query config that controls which `fields` are selectable, `isList`, and default pagination. The handler reads the resolved selection from `req.queryConfig.fields` and pagination from `req.queryConfig.pagination`.++```ts title="src/api/admin/brands/query-config.ts"+export const adminBrandQueryConfig = {+ list: {+ defaults: ["id", "name", "is_active", "created_at"],+ isList: true,+ },+ retrieve: {+ defaults: ["id", "name", "is_active"],+ },+}+```++<Warning>+ **`fields` replaces defaults unless prefixed.** An unprefixed field in the request's `fields` param *replaces* the route's default set; prefix with `+`/`-` to merge (e.g. `+brand.name`) or base fields like `thumbnail` silently drop. This is the `medusa-fields-param` gotcha.+</Warning>++## Response types++Declare the response shapes next to the route (or in `@mercurjs/types` for shared ones) and use them as the `MedusaResponse` generic — the SDK reads these to type `.query()` / `.mutate()` returns:++```ts title="src/api/admin/brands/types.ts"+import { PaginatedResponse } from "@medusajs/framework/types"++export interface AdminBrandResponse {+ brand: BrandDTO+}++export type AdminBrandListResponse = PaginatedResponse<{+ brands: BrandDTO[]+}>+```++## Checklist for a route++- Handler is thin: validate → run workflow (writes) or `query.graph` (reads) → respond.+- **Both** generics set: `AuthenticatedMedusaRequest<TBody|TQuery>` and `MedusaResponse<TResponse>` — never a bare `MedusaResponse`.+- Only `GET` / `POST` / `DELETE` exported; updates are `POST`.+- Query params built with `createFindParams` / `createSelectParams`; bodies with Zod; inferred types exported.+- Filterable fields declared in the validator; scoping injected via a `filterableFields` middleware, not inlined.+- Identity read from `req.auth_context`, never the body. On vendor routes, the authoritative seller is `req.seller_context.seller_id` (set by `ensureSellerMiddleware`); scope reads with `filterBySellerId()`.+- `fields` prefixed with `+`/`-` to merge; defaults declared in `queryConfig`.+- No mutations outside a workflow.diff --git a/apps/docs/rc/resources/best-practices/custom-fields.mdx b/apps/docs/rc/resources/best-practices/custom-fields.mdxnew file mode 100644index 000000000..5e2821a29--- /dev/null+++ b/apps/docs/rc/resources/best-practices/custom-fields.mdx@@ -0,0 +1,241 @@+---+title: "Custom fields"+description: "The full loop — add a custom field in core, render it in the panels with defineCustomFieldsConfig, pull linked data with the link property, and type it end-to-end."+---++Custom Fields attach extra data to an existing entity (a product, customer, order…) through configuration — no hand-written model or migration. What makes them powerful is the **full loop across the stack**: you declare the field in core, render it in the panels with `defineCustomFieldsConfig`, optionally pull in [linked-module](/rc/resources/best-practices/module-links) data with the `link` property, and [type it end-to-end](/rc/resources/best-practices/types) so every SDK call carries it.++This page is the best-practices view. For the full storage-side setup see [Custom Fields](/rc/resources/customization/custom-fields).++## Reach for a custom field vs a module++The decision is about the **shape and lifecycle** of the data, not its size.++<CardGroup cols={2}>+ <Card title="Use a custom field when…" icon="circle-check">+ The data is a plain property of one existing record: `is_featured` on a product, `tier` on a customer, `source` on an order. One row per parent, no lifecycle of its own, read alongside the parent.+ </Card>+ <Card title="Build a module when…" icon="cube">+ The data has its own lifecycle, relates to more than one entity, has many rows per parent, or carries business logic and its own routes. Reviews, tickets, subscriptions.+ </Card>+</CardGroup>++<Warning>+ Custom Fields is strictly **one row per parent entity**. Forcing a one-to-many or stateful concept into it works until you need a second row or a state transition. If in doubt, model it as a [module](/rc/resources/best-practices/modules).+</Warning>++## The full loop++### 1. Declare the field in core++Register the Custom Fields module and describe the field in `medusa-config.ts`. The module generates the side table, the link, and the schema on `db:migrate`:++```ts title="medusa-config.ts"+{+ resolve: "@mercurjs/core/modules/custom-fields",+ options: {+ customFields: {+ Product: {+ is_featured: { type: "boolean", nullable: true },+ },+ },+ },+}+```++The value now lives in the module's own `custom_fields` side table — linked to the product, queryable through `query.graph`, and written through `additional_data` on the entity's create/update route.++<Warning>+ **Prefer the `custom_fields` link over stuffing values into `metadata`.** `metadata` is an untyped JSON bag with no schema, no queryable columns, and no clean extension point — it turns into a dumping ground. The Custom Fields module gives you a real linked table (`custom_fields.*`) with typed columns you can query and filter, while still being config-only. Reach for `metadata` only for genuinely throwaway, never-queried scratch data.+</Warning>++<Tip>+ Mutations still go through workflows. The panel submits custom-field values under **`additional_data`** on the parent's create/update route — and `additional_data` is exactly what [workflow hooks](/rc/resources/best-practices/workflows#hooks--let-others-extend-your-workflow) receive. So the same values you enter in the panel can be consumed by a `productsCreated` / `productUpdated` hook to run follow-up logic, persist to the linked table, or trigger side effects. Never write a custom-field value with a direct route write.+</Tip>++### 2. Render it in the panel with `defineCustomFieldsConfig`++Drop one file per model under the panel's `src/custom-fields/`. A single config contributes **form fields** (edit drawer, submitted under `additional_data`), read-only **displays** (detail sections), and **list columns**. Declare `link: "custom_fields"` so the module's data is fetched alongside the product and available to your fields and displays:++```tsx title="apps/vendor/src/custom-fields/product.tsx"+import { defineCustomFieldsConfig } from "@mercurjs/dashboard-sdk"+import { createFormHelper } from "@mercurjs/dashboard-shared"++type ProductWithCustomFields = { custom_fields?: { is_featured?: boolean } }++const form = createFormHelper<ProductWithCustomFields>()++export default defineCustomFieldsConfig({+ model: "product",+ link: "custom_fields", // fetch custom_fields.* with the product — no hand-written field list+ forms: [+ {+ zone: "edit",+ fields: {+ is_featured: form.define({+ validation: form.boolean().optional(),+ label: "Featured",+ // read the current value from the linked table, not metadata+ defaultValue: (data) => Boolean(data?.custom_fields?.is_featured),+ }),+ },+ },+ ],+ displays: [+ {+ zone: "general",+ fields: [+ {+ id: "is_featured",+ component: ({ data }) => (data.custom_fields?.is_featured ? "Featured" : "—"),+ },+ ],+ },+ ],+})+```++<Note>+ The `zone` values are typed — the panel's codegen scans the host `<FormExtensionZone>` / `<DisplayExtensionZone>` usages and emits the valid zones per model into `extension-targets.d.ts`. `zone: "nope"` fails `tsc`. You don't hand-maintain that list.+</Note>++The `displays` fields follow an add / replace / remove convention keyed by `id`:++- **unknown id** → appends a new read-only row,+- **built-in id + component** → replaces that field's render,+- **built-in id + `component: null`** → hides the field.++## The extension API `link` property++A custom-field config can also declare **module links to fetch alongside the entity** with the `link` property. This is how you surface data from a linked module (e.g. a `brand`) in the product's columns and displays without wiring a second query:++```tsx title="apps/vendor/src/custom-fields/product.tsx"+export default defineCustomFieldsConfig({+ model: "product",+ link: "brand", // fetch brand.* with each product — one or an array of links+ list: {+ columns: [+ // linked data is available on the row, no extra fetch+ { id: "brand_name", header: "Brand", component: ({ row }) => row.brand?.name },+ ],+ },+ displays: [+ {+ zone: "general",+ fields: [{ id: "brand", component: ({ data }) => data.brand?.name ?? "-" }],+ },+ ],+})+```++<Tip>+ `link` replaces the old "remember to add the fields to every fetch" chore. Under the hood the panel reads the registry's links (`getLinks(model)`) and merges them into the built-in list, detail, and edit fetches with `withLinkFields(fields, links)` (`+brand.*`) — so the linked data is present in **all three** places automatically. There's no `extendFields`: declaring the `link` is what makes its fields available to both columns and displays.+</Tip>++<Warning>+ The link must actually exist as a [module link](/rc/resources/best-practices/module-links) and, in the vendor panel, respect the curated-field constraint — the fetch derived from `link` runs against the vendor product query, which rejects arbitrary `*`-relation overrides. Declare the link, then reference only its real fields.+</Warning>++## 3. Type it end-to-end++The rendered value comes back from the API, but the panel's `ProductDTO` doesn't know about `is_featured` yet. Close the gap with a one-line declaration-merging `.d.ts` so **every** SDK endpoint is typed — no per-call casts:++```ts title="apps/vendor/src/types/custom-fields.d.ts"+import "@medusajs/types"++declare module "@medusajs/types" {+ interface ProductDTO {+ custom_fields?: { is_featured?: boolean }+ }+}+```++Now `product.custom_fields?.is_featured` is typed on every `sdk.vendor.products.*` response — the runtime value is delivered by the `link` / registry merge above, not a hand-added `+field.*` (the vendor product query rejects arbitrary `*`-relation overrides). The mechanics — why merging into the upstream interface flows through — are covered in [Types & augmentation](/rc/resources/best-practices/types#the-scenario-a-custom-field-typed-end-to-end).++## The full override flow: `additional_data` → route → workflow hook++Rendering and typing a field is only half the story. The reason custom fields submit under **`additional_data`** is that it's the framework's built-in extension channel: values entered in the panel travel through the entity's existing API route into the workflow's **hooks**, where your own code consumes them — **without forking the route or the workflow**. This is exactly what a Mercur override looks like.++The flow has three links in the chain.++### 1. The panel submits under `additional_data`++You already did this — a `defineCustomFieldsConfig` `edit`/`create` field is submitted as `additional_data.<field>` on the entity's create/update request. Nothing else to wire on the frontend.++### 2. The route accepts it via `additionalDataValidator`++The vendor/admin product routes accept an `additional_data` body param, but each key must be **declared** or it's rejected. Register the allowed keys with `additionalDataValidator` in a middleware — no need to touch the route handler:++```ts title="src/api/middlewares.ts"+import { defineMiddlewares } from "@medusajs/framework/http"+import { z } from "@medusajs/framework/zod"++export default defineMiddlewares({+ routes: [+ {+ method: "POST",+ matcher: "/vendor/products",+ additionalDataValidator: {+ brand_id: z.string().optional(),+ },+ },+ ],+})+```++### 3. A workflow hook consumes it++Mercur's product create workflow — `createProductsWorkflow` from `@mercurjs/core/workflows` (id `mercur-create-products`) — is what the vendor route runs, and it exposes a `productsCreated` **hook** that runs after the products are created, receiving both the created records and your `additional_data`. Consume it to perform the real work — here, [linking](/rc/resources/best-practices/module-links) the product to a brand — with a compensation function so a failure rolls the link back:++```ts title="src/workflows/hooks/created-product.ts"+import { createProductsWorkflow } from "@mercurjs/core/workflows"+import { StepResponse } from "@medusajs/framework/workflows-sdk"+import { Modules } from "@medusajs/framework/utils"+import { LinkDefinition } from "@medusajs/framework/types"+import { BRAND_MODULE } from "../../modules/brand"++createProductsWorkflow.hooks.productsCreated(+ async ({ products, additional_data }, { container }) => {+ if (!additional_data?.brand_id) {+ return new StepResponse([], [])+ }++ const link = container.resolve("link")+ const links: LinkDefinition[] = products.map((product) => ({+ [Modules.PRODUCT]: { product_id: product.id },+ [BRAND_MODULE]: { brand_id: additional_data.brand_id },+ }))++ await link.create(links)+ return new StepResponse(links, links)+ },+ // compensation — undo the links if a later step fails+ async (links, { container }) => {+ if (!links?.length) {+ return+ }+ await container.resolve("link").dismiss(links)+ }+)+```++<Note>+ Mercur's `createProductsWorkflow` wraps Medusa's stock create-products flow and adds the marketplace layer (seller association, attributes, audit trail). Because it re-exposes the `validate` and `productsCreated` hooks, you extend the **Mercur** flow the same way you would a plain Medusa one — consume its hook, don't fork it.+</Note>++<Tip>+ This is the **override pattern** in one sentence: the panel writes to `additional_data`, the route lets it through via `additionalDataValidator`, and a `hooks.<name>` consumer turns it into real behaviour — all additively, without copying or replacing any built-in code. It's how you extend a Mercur (or Medusa) flow instead of forking it. See [Workflows → hooks](/rc/resources/best-practices/workflows#hooks--let-others-extend-your-workflow).+</Tip>++<Warning>+ The hook runs **inside** the workflow, so its mutation still obeys the [one-mutation-per-step + compensation](/rc/resources/best-practices/workflows#one-mutation-per-step--compensation) rule — always pair `link.create` with a `link.dismiss` compensation. Never do the work in a route handler after the workflow returns; put it in the hook.+</Warning>++## Checklist++- Data is genuinely one-row-per-parent with no lifecycle → custom field; otherwise a module.+- Field registered in `medusa-config.ts`; `db:migrate` run; writes go through `additional_data` on a workflow.+- Panel: one `defineCustomFieldsConfig` per model contributes forms / displays / list, with typed `zone`s.+- Linked-module data pulled in with the `link` property (not a hand-written second fetch); the link exists and respects vendor field constraints.+- Extended fields typed once via a `.d.ts` merging into the framework DTO, and requested with `+…*` so they arrive.+- The override chain is complete: panel → `additional_data` → `additionalDataValidator` declares the key → a `hooks.<name>` consumer does the work inside the workflow, with compensation. No route/workflow forked.diff --git a/apps/docs/rc/resources/best-practices/frontend.mdx b/apps/docs/rc/resources/best-practices/frontend.mdxnew file mode 100644index 000000000..14c294ff4--- /dev/null+++ b/apps/docs/rc/resources/best-practices/frontend.mdx@@ -0,0 +1,286 @@+---+title: "Frontend"+description: "Build panel UI the right way — @medusajs/ui usage, custom-field extensions (forms, tables, read-only section fields), and new pages, with the correct imports."+---++The Admin and Vendor panels share one design system. The three things you'll actually do — style with `@medusajs/ui`, extend built-in screens with **custom fields**, and add **new pages** — all have an established shape and, importantly, a set of **correct imports**. This page is that short list. The full reference is the [UI architecture](/rc/references/panel-extension-api).++## Use `@medusajs/ui` — and only it++<Warning>+ Never introduce a second UI library, and never restyle Medusa UI components with custom CSS. Build on the primitives; don't work around them.+</Warning>++- **Components** come from `@medusajs/ui`, **icons** from `@medusajs/icons`, and colours/spacing/type from Medusa UI **tokens** (`text-ui-fg-*`, `bg-ui-bg-*`, `border-ui-border-*`) — never hex, `rgb()`, or `text-gray-500`.++```tsx+import { Container, Heading, Text, Button, Badge, StatusBadge, toast } from "@medusajs/ui"+import { PencilSquare, Trash, EllipsisHorizontal } from "@medusajs/icons"+```++- A **section** is a `Container` with the standard shell — a divided card with a header row:++```tsx+<Container className="divide-y p-0">+ <div className="flex items-center justify-between px-6 py-4">+ <Heading level="h2">Details</Heading>+ <Button size="small" variant="secondary">Edit</Button>+ </div>+ <div className="px-6 py-4">+ <Text size="small" className="text-ui-fg-subtle">Body</Text>+ </div>+</Container>+```++## Extend built-in screens with custom fields++The primary way to customise an existing entity's screens (product, order, customer…) is a **custom-fields config** — one file per model that contributes form fields, table columns, and read-only section fields. See [Custom fields](/rc/resources/best-practices/custom-fields) for the full backend↔frontend loop; here's the frontend surface with the right imports.++<Note>+ The two imports you need — and where each lives:++ ```tsx+ import { defineCustomFieldsConfig } from "@mercurjs/dashboard-sdk" // the config helper+ import { createFormHelper } from "@mercurjs/dashboard-shared" // typed form fields (zod)+ ```++ `defineCustomFieldsConfig` is build-time config (SDK, zod-free); `createFormHelper` is the runtime form surface (dashboard-shared). Don't cross them over.+</Note>++### Add form fields (edit / create)++Contribute inputs into a built-in form `zone`. Values submit under `additional_data`:++```tsx title="apps/vendor/src/custom-fields/product.tsx"+import { defineCustomFieldsConfig } from "@mercurjs/dashboard-sdk"+import { createFormHelper } from "@mercurjs/dashboard-shared"++const form = createFormHelper<{ custom_fields?: { is_featured?: boolean } }>()++export default defineCustomFieldsConfig({+ model: "product",+ link: "custom_fields",+ forms: [+ {+ zone: "edit",+ fields: {+ is_featured: form.define({+ validation: form.boolean().optional(),+ label: "Featured",+ defaultValue: (data) => Boolean(data?.custom_fields?.is_featured),+ }),+ },+ },+ ],+})+```++### Change the list table++Add or override a column (and add bulk actions) on the model's built-in list:++```tsx+list: {+ columns: [+ { id: "is_featured", header: "Featured", component: ({ row }) => (row.custom_fields?.is_featured ? "★" : "") },+ ],+},+```++### Read-only fields in detail sections — e.g. surface (or change) a status++`displays` add read-only rows into an existing detail-page section, keyed by `id` (unknown id **adds**, built-in id **replaces**, `component: null` **hides**). A read-only field can render a `StatusBadge`, and a section `action` can trigger a status change through a mutation:++```tsx title="apps/vendor/src/custom-fields/product.tsx"+import { StatusBadge, Button, toast } from "@medusajs/ui"++// inside defineCustomFieldsConfig(...)+displays: [+ {+ zone: "general",+ fields: [+ {+ id: "review_status",+ component: ({ data }) => (+ <div className="flex items-center justify-between px-6 py-4">+ <StatusBadge color={data.custom_fields?.approved ? "green" : "orange"}>+ {data.custom_fields?.approved ? "Approved" : "Pending"}+ </StatusBadge>+ <Button+ size="small"+ variant="secondary"+ onClick={async () => {+ await sdk.vendor.products.$id.mutate({+ $id: data.id,+ additional_data: { approved: true },+ })+ toast.success("Approved")+ }}+ >+ Approve+ </Button>+ </div>+ ),+ },+ ],+ },+],+```++<Tip>+ Read-only displays are the idiomatic way to expose (and act on) an entity's state — an approval flag, a moderation status, an internal tag — without rebuilding the detail page. The mutation still goes through the typed SDK and rides `additional_data` into a [workflow hook](/rc/resources/best-practices/custom-fields#the-full-override-flow-additional_data--route--workflow-hook), never a direct write.+</Tip>++## Add a new page++A brand-new screen is one file: drop a `page.tsx` under the host app's `src/routes/`. The SDK registers the route from the file path and builds the sidebar entry from an exported `config`.++```tsx title="apps/vendor/src/routes/reviews/page.tsx"+import { Container, Heading } from "@medusajs/ui"+import { Star } from "@medusajs/icons"+import type { RouteConfig } from "@mercurjs/dashboard-sdk"++export const config: RouteConfig = {+ label: "Reviews",+ icon: Star,+}++export default function ReviewsPage() {+ return (+ <Container className="divide-y p-0">+ <div className="px-6 py-4">+ <Heading>Reviews</Heading>+ </div>+ </Container>+ )+}+```++<Note>+ Correct imports for a page: UI from `@medusajs/ui`, icons from `@medusajs/icons`, and the `RouteConfig` **type** from `@mercurjs/dashboard-sdk`. Dynamic segments use brackets — `src/routes/reviews/[id]/page.tsx` → `/reviews/:id`. See [Extending panels](/rc/resources/customization/extending-panels#routing-conventions).+</Note>++## Compose a full page: layout, table, sections, edit++For a real screen you assemble the same primitives the built-in pages use — all re-exported from `@mercurjs/dashboard-shared`, so you import from **one** place instead of Medusa internals.++```tsx+import {+ SingleColumnPage,+ TwoColumnPage,+ DataTable,+ useDataTable,+ SectionRow,+ RouteDrawer,+ Form,+ ActionMenu,+} from "@mercurjs/dashboard-shared"+import { Container, Heading, Text, Button, Input, toast } from "@medusajs/ui"+import { createColumnHelper } from "@tanstack/react-table"+```++### Layout + list table++Pick a layout — `SingleColumnPage` for lists/simple pages, `TwoColumnPage` for a detail with a sidebar — and mount a `DataTable` inside the standard section shell. Build columns with `createColumnHelper`, wire the table with `useDataTable`, page size 20, and `keepPreviousData` for smooth pagination:++```tsx title="apps/vendor/src/routes/reviews/page.tsx"+const columnHelper = createColumnHelper<Review>()++const columns = [+ columnHelper.accessor("title", { header: "Title" }),+ columnHelper.accessor("rating", { header: "Rating" }),+ columnHelper.display({+ id: "actions",+ cell: ({ row }) => (+ <ActionMenu groups={[{ actions: [{ label: "Edit", to: `${row.original.id}/edit` }] }]} />+ ),+ }),+]++export default function ReviewsPage() {+ const { reviews = [], count = 0, isLoading } = useReviews()+ const { table } = useDataTable({ data: reviews, columns, count, pageSize: 20, getRowId: (r) => r.id })++ return (+ <SingleColumnPage>+ <Container className="divide-y p-0">+ <div className="flex items-center justify-between px-6 py-4">+ <Heading>Reviews</Heading>+ </div>+ <DataTable table={table} columns={columns} count={count} pageSize={20} isLoading={isLoading} navigateTo={(row) => row.id} pagination search />+ </Container>+ </SingleColumnPage>+ )+}+```++### General section (label / value rows)++On a detail page, a "general" section is a `Container` header row plus `SectionRow` label/value pairs — the canonical way Medusa renders read-only entity data:++```tsx+<Container className="divide-y p-0">+ <div className="flex items-center justify-between px-6 py-4">+ <Heading>{review.title}</Heading>+ <ActionMenu groups={[{ actions: [{ label: "Edit", to: "edit" }] }]} />+ </div>+ <SectionRow title="Rating" value={`${review.rating} / 5`} />+ <SectionRow title="Status" value={review.approved ? "Approved" : "Pending"} />+</Container>+```++For a detail page with a sidebar, wrap sections in `TwoColumnPage` and place them under `TwoColumnPage.Main` / `TwoColumnPage.Sidebar` (each stacked with `gap-y-3`).++### Edit page (drawer)++Quick edits live in a routed `RouteDrawer` with `Form` (React Hook Form + Zod). Gate the form until the entity has loaded, and use `useRouteModal().handleSuccess()` to close on save:++```tsx title="apps/vendor/src/routes/reviews/[id]/edit/page.tsx"+export default function EditReviewPage() {+ return (+ <RouteDrawer>+ <RouteDrawer.Header>+ <RouteDrawer.Title asChild>+ <Heading>Edit review</Heading>+ </RouteDrawer.Title>+ </RouteDrawer.Header>+ {/* <EditReviewForm /> — RouteDrawer.Form + KeyboundForm, gated on !isPending && !!review */}+ </RouteDrawer>+ )+}+```++<Warning>+ Import these primitives from `@mercurjs/dashboard-shared`, **not** from deep Medusa dashboard paths like `../../../components/table/data-table`. The shared package is the public, stable surface; relative Medusa-internal imports are not available to consumer apps and break on upgrade.+</Warning>++## Data only through the typed SDK++<Warning>+ Never call `fetch` directly from a page. All HTTP goes through the typed SDK — `sdk.admin.*` in the admin panel, `sdk.vendor.*` in the vendor panel — wrapped in TanStack Query hooks.+</Warning>++```ts title="src/hooks/api/reviews.tsx"+import { useQuery } from "@tanstack/react-query"+import { sdk } from "../../lib/client"+import { queryKeysFactory } from "@mercurjs/dashboard-shared"++const reviewKeys = queryKeysFactory("reviews")++export const useReviews = (query?: Record<string, unknown>) =>+ useQuery({+ queryKey: reviewKeys.list(query),+ queryFn: () => sdk.vendor.reviews.query({ ...query }),+ })+```++Invalidate `lists()` / `details()` / `detail(id)` in mutations, throw on `isError` so the route `ErrorBoundary` catches it, and show a `Skeleton` while loading.++## Checklist for panel work++- Built only from `@medusajs/ui` + `@medusajs/icons`; Medusa UI tokens only, no custom CSS.+- Extending an existing screen → a `defineCustomFieldsConfig` file (`@mercurjs/dashboard-sdk`) with `createFormHelper` (`@mercurjs/dashboard-shared`); forms submit under `additional_data`.+- Read-only state (status/flags) surfaced via `displays`; changes go through the typed SDK + a workflow hook, not a direct write.+- New screen → a `page.tsx` under `src/routes/` with a typed `RouteConfig`; compose it from `SingleColumnPage`/`TwoColumnPage`, `DataTable`, `SectionRow`, and `RouteDrawer` — all imported from `@mercurjs/dashboard-shared`, never Medusa-internal paths.+- Data via `sdk.admin.*` / `sdk.vendor.*` in TanStack Query hooks; no raw `fetch`; mutations invalidate the right keys.+- Every visible string translated; every interactive element has a `data-testid`.diff --git a/apps/docs/rc/resources/best-practices/module-links.mdx b/apps/docs/rc/resources/best-practices/module-links.mdxnew file mode 100644index 000000000..b3e8d113d--- /dev/null+++ b/apps/docs/rc/resources/best-practices/module-links.mdx@@ -0,0 +1,166 @@+---+title: "Module links"+description: "Relate modules without coupling them — defineLink, the link-direction rule, built-in link steps, and filtering by links."+---++Modules are isolated: a module never imports another module's service or points a foreign key at another module's table (see [Modules](/rc/resources/best-practices/modules)). Relationships between modules are declared **outside** the modules, as **links**, and read through **Query**. This is what keeps each module independently migratable and upgrade-safe.++<Note>+ Links are a [Medusa framework primitive](https://docs.medusajs.com/learn/fundamentals/module-links). The examples below link a custom **Brand** module to Medusa's built-in **Product** module — the kind of relationship you'd add in your own project.+</Note>++## `defineLink`++A link is a small file that associates two linkable data models. Define it once and sync it to the database with a migration.++```ts title="src/links/product-brand.ts"+import { defineLink } from "@medusajs/framework/utils"+import ProductModule from "@medusajs/medusa/product"+import BrandModule from "../modules/brand"++export default defineLink(+ ProductModule.linkable.product,+ BrandModule.linkable.brand+)+```++After adding or changing a link, generate and run the migration so the link table exists:++```bash+npx medusa db:migrate+```++Once linked, you read across the boundary with Query — never by calling the other module's service:++```ts+const { data: products } = await query.graph({+ entity: "product",+ fields: ["id", "title", "brand.*"], // follows the product ↔ brand link+})+```++## The link-direction rule++The **order of arguments to `defineLink` is meaningful** and cardinality is controlled with `isList`. Read it left-to-right as "the left model links to the right model".++- `defineLink(A.linkable.a, B.linkable.b)` — one `a` ↔ one `b`.+- Wrap a side in `{ linkable, isList: true }` to make it the "many" side.++If one brand has many products but each product belongs to a single brand, mark the **product** side as the list:++```ts title="src/links/product-brand.ts — one brand, many products"+import { defineLink } from "@medusajs/framework/utils"+import ProductModule from "@medusajs/medusa/product"+import BrandModule from "../modules/brand"++export default defineLink(+ {+ linkable: ProductModule.linkable.product,+ isList: true,+ },+ BrandModule.linkable.brand+)+```++For a many-to-many relationship (a product can carry many brands *and* a brand spans many products) mark both sides as lists and pin an explicit table name:++```ts title="src/links/product-brand.ts — many-to-many"+export default defineLink(+ { linkable: ProductModule.linkable.product, isList: true },+ { linkable: BrandModule.linkable.brand, isList: true },+ {+ database: {+ table: "product_brand",+ },+ }+)+```++<Warning>+ Direction determines the generated relation names and the shape of the link table. Getting it backwards produces a link that "works" but exposes the wrong nesting (`brand.products` vs `product.brands`) and is painful to migrate away from. Decide the natural reading direction first, then set `isList` on the many side(s).+</Warning>++## Built-in link steps — create links inside workflows++Links are **data**, so creating or removing one is a mutation and must happen inside a [workflow](/rc/resources/best-practices/workflows) through the built-in link steps — never by writing to the link table directly.++- `createRemoteLinkStep` — create links (and it compensates by removing them on failure).+- `dismissRemoteLinkStep` — remove links.++Build the link definitions with `transform` (never inline logic in the composition function), then pass them to the step. Each entry names the two modules and the ids to associate:++```ts title="Linking a product to a brand inside a workflow"+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"+import { Modules } from "@medusajs/framework/utils"+import { LinkDefinition } from "@medusajs/framework/types"+import { BRAND_MODULE } from "../modules/brand"++const productBrandLinks = transform(+ { productId, brandId },+ ({ productId, brandId }): LinkDefinition[] => [+ {+ [Modules.PRODUCT]: { product_id: productId },+ [BRAND_MODULE]: { brand_id: brandId },+ },+ ]+)++createRemoteLinkStep(productBrandLinks)+```++<Tip>+ Because `createRemoteLinkStep` already knows how to compensate, links created this way are torn down automatically if a later step in the workflow throws. This is the whole reason to link inside a workflow rather than in a route.+</Tip>++## Filtering by links++A link isn't just for reading nested data — you can **filter and scope queries by it**. A common case: list only the products that belong to a given brand.++Because the `product ↔ brand` link exists, you can filter products by a field on the linked brand in a single `query.graph` call — no join to write, no second query:++```ts title="Filter products by their linked brand"+const { data: products } = await query.graph({+ entity: "product",+ fields: ["id", "title", "brand.name"],+ filters: {+ brand: {+ id: brandId, // only products linked to this brand+ },+ },+})+```++The idiomatic way to apply such a filter on a route is a small **middleware** that injects it onto `req.filterableFields`, so the handler stays ignorant of the scoping rule and every route on the resource is filtered by construction:++```ts title="src/api/admin/products/middlewares.ts"+const filterByBrand = (+ req: MedusaRequest,+ _res: MedusaResponse,+ next: MedusaNextFunction+) => {+ if (req.query.brand_id) {+ req.filterableFields.brand = { id: req.query.brand_id }+ }+ next()+}+```++```ts title="Handler just forwards the filters"+const { data: products, metadata } = await query.graph({+ entity: "product",+ fields: req.queryConfig.fields,+ filters: req.filterableFields, // brand filter already injected+ pagination: req.queryConfig.pagination,+})+```++The [middlewares-as-filters](/rc/resources/best-practices/api-routes#middlewares-as-filters) section covers this pattern in full.++## Checklist for a link++- Declared in its own file under `src/links/`, using `defineLink`.+- Argument order reflects the natural reading direction; `isList` set on the many side(s).+- Migration generated and run (`medusa db:migrate`).+- Cross-module reads go through `query.graph`, never a service-to-service call.+- Links are created/removed only inside workflows via `createRemoteLinkStep` / `dismissRemoteLinkStep`.+- Filtering/scoping by a linked field is applied as a `filterableFields` middleware, not inlined in each handler.diff --git a/apps/docs/rc/resources/best-practices/modules.mdx b/apps/docs/rc/resources/best-practices/modules.mdxnew file mode 100644index 000000000..fc42dc234--- /dev/null+++ b/apps/docs/rc/resources/best-practices/modules.mdx@@ -0,0 +1,144 @@+---+title: "Modules"+description: "Keep modules thin — data access and CRUD only. Naming, decorators, and what must never live in a module service."+---++A module is the lowest layer of the [architecture](/rc/resources/best-practices/overview): it owns exactly one domain's data and nothing else. Modules are isolated — they never reach into another module, never orchestrate a business operation, and never react to events. All of that lives one layer up, in [workflows](/rc/resources/best-practices/workflows).++<Note>+ A Mercur module is a standard [Medusa module](https://docs.medusajs.com/learn/fundamentals/modules). The examples below build a small **Brand** module — the kind of custom module you'd add to your own project alongside the built-in ones — so the rules stand on their own rather than relying on Mercur internals.+</Note>++## Thin CRUD only++A module service exists to read and write its own tables. Extend `MedusaService({ ...models })` and you get typed `list`, `listAndCount`, `retrieve`, `create`, `update`, and `delete` methods for every model for free — use them.++```ts title="src/modules/brand/models/brand.ts"+import { model } from "@medusajs/framework/utils"++export const Brand = model.define("brand", {+ id: model.id().primaryKey(),+ name: model.text(),+})+```++```ts title="src/modules/brand/service.ts"+import { MedusaService } from "@medusajs/framework/utils"+import { Brand } from "./models/brand"++class BrandModuleService extends MedusaService({+ Brand,+}) {+ // Generated for you: listBrands, retrieveBrand, createBrands,+ // updateBrands, deleteBrands, listAndCountBrands, ...+}++export default BrandModuleService+```++Only add a custom method when the logic is **about this module's own data** and can't be expressed with the generated methods — for example, a specialised query. When you do, use Medusa's DI decorators so the method runs in the ambient context:++```ts title="A justified custom method — still single-module"+class BrandModuleService extends MedusaService({ Brand }) {+ @InjectManager()+ async listActiveBrands(+ filters: FindConfig<BrandDTO> = {},+ @MedusaContext() sharedContext: Context = {}+ ): Promise<BrandDTO[]> {+ return this.listBrands({ ...filters, is_active: true }, {}, sharedContext)+ }+}+```++<Warning>+ **What must never live in a module service:** business orchestration, calls to another module's service, event emission, HTTP concerns, or anything that mutates data outside this module. If a method needs a second module's data or writes across a boundary, it belongs in a [workflow](/rc/resources/best-practices/workflows), not here. See the [logic-placement cheat sheet](/rc/resources/best-practices/overview#logic-placement-cheat-sheet).+</Warning>++## Naming++- **Register the module by a stable id constant.** Export the module id and register the service against it:++ ```ts title="src/modules/brand/index.ts"+ import { Module } from "@medusajs/framework/utils"+ import BrandModuleService from "./service"++ export const BRAND_MODULE = "brand"++ export default Module(BRAND_MODULE, {+ service: BrandModuleService,+ })+ ```++ <Tip>+ Mercur's own modules follow the same pattern but read their id from the shared `MercurModules` enum in `@mercurjs/types` (e.g. `Module(MercurModules.SELLER, …)`). For a project-local module, a single exported constant like `BRAND_MODULE` is enough — just never inline the raw string in more than one place.+ </Tip>++- **Methods are `camelCase` and model-suffixed.** Medusa generates `listBrands`, `createBrands`, `retrieveBrand` — match that casing and pluralisation when you add or override methods. Private helpers end with a trailing underscore (`computeBrandStats_`).+- **Models are lowercase-defined, referenced by their key.** `model.define("brand", { ... })`; the object key you pass to `MedusaService` (`Brand`) is what drives the generated method names.+- **Types live next to the module (or in a shared types package).** Export DTOs like `BrandDTO` and import them; never redeclare a model's shape ad hoc. See [Types & augmentation](/rc/resources/best-practices/types).++## Do not call `.linkable()` — links are declared separately++It is tempting to relate two modules by pointing a model at another module's table. Don't. A module model must not reference another module's data, and you should not wire relationships inside the model definition.++<Warning>+ Cross-module relationships are declared **outside** the modules, with `defineLink`, and read through **Query**. A module never imports another module's `.linkable` shape to build a foreign key into it. Keeping models link-free is what lets modules stay independently migratable and upgrade-safe.+</Warning>++Define the relationship as its own link file instead — covered in full on [Module links](/rc/resources/best-practices/module-links):++```ts title="Relationship declared as a link, not inside the model"+import { defineLink } from "@medusajs/framework/utils"+import ProductModule from "@medusajs/medusa/product"+import BrandModule from "../modules/brand"++export default defineLink(+ ProductModule.linkable.product,+ BrandModule.linkable.brand+)+```++The model itself stays flat — plain columns, no relations pointing at other modules:++```ts title="src/modules/brand/models/brand.ts"+export const Brand = model.define("brand", {+ id: model.id().primaryKey(),+ name: model.text(),+ is_active: model.boolean().default(true),+ metadata: model.json().nullable(),+})+```++## Decorators++Custom service methods that touch the database use Medusa's dependency-injection decorators so they participate in the ambient transaction and shared context:++| Decorator | Use it on | Purpose |+| --- | --- | --- |+| `@InjectManager()` | Read methods | Injects the entity manager so the method runs in the current context. |+| `@InjectTransactionManager()` | Write methods | Runs the method inside a transaction, enabling rollback. |+| `@MedusaContext()` | The trailing `sharedContext` parameter | Threads the request/transaction context through the call. |++```ts title="Decorator pattern for a custom write"+@InjectTransactionManager()+async deactivateBrand(+ id: string,+ @MedusaContext() sharedContext: Context = {}+): Promise<BrandDTO> {+ return this.updateBrands({ id, is_active: false }, sharedContext)+}+```++<Tip>+ If you don't need a custom method, don't write one. The generated `MedusaService` methods already carry the right decorators and transaction behaviour — reaching for them first keeps modules thin by default.+</Tip>++## Checklist for a module++- Extends `MedusaService({ ...models })`; leans on generated CRUD.+- Registered with `Module(BRAND_MODULE, { service })` against a stable id.+- No import of, or call into, any other module's service.+- Models are flat — no `.linkable()` wiring, no cross-module foreign keys.+- Custom methods use `@InjectManager` / `@InjectTransactionManager` + `@MedusaContext`.+- DTOs are exported and imported, never redeclared inline.+- No orchestration, no events, no HTTP — those live in workflows and routes.diff --git a/apps/docs/rc/resources/best-practices/overview.mdx b/apps/docs/rc/resources/best-practices/overview.mdxnew file mode 100644index 000000000..08a7cb26c--- /dev/null+++ b/apps/docs/rc/resources/best-practices/overview.mdx@@ -0,0 +1,115 @@+---+title: "Best Practices Overview"+description: "How to build with Mercur — the layered architecture, the non-negotiable rules, and where each piece of logic belongs."+---++This section is a practical guide for developing on Mercur, written for both **human developers** and **AI coding agents**. It captures the conventions the codebase already follows so that new code reads as if it belongs, stays testable, and survives upgrades of the underlying Medusa framework.++<Note>+ Mercur is a Medusa plugin. Every rule here is either a Medusa framework requirement or a Mercur convention that keeps the marketplace layer consistent. When Medusa's docs and this guide agree, follow both; when in doubt, mirror an existing module, workflow, or route in `packages/core`.+</Note>++## The layered architecture++Every feature in Mercur flows through the same four layers, top to bottom. Data and requests move **down**; results move back **up**. A layer may only talk to the layer directly beneath it.++```mermaid+graph TD+ F["Frontend<br/>(Admin · Vendor panels, Storefront)"]+ A["API Route<br/>(/admin/* · /vendor/* · /store/*)"]+ W["Workflow<br/>(orchestration + compensation)"]+ M["Module<br/>(thin data access / CRUD)"]+ DB[(PostgreSQL)]++ F -->|"typed SDK request"| A+ A -->|"run(workflow)"| W+ W -->|"module service calls (steps)"| M+ M --> DB+```++<CardGroup cols={2}>+ <Card title="Module" icon="cube">+ Owns one domain's data. Thin CRUD only — no orchestration, no cross-module calls.+ </Card>+ <Card title="Workflow" icon="diagram-project">+ Orchestrates a business operation across modules, step by step, with automatic rollback (compensation) on failure.+ </Card>+ <Card title="API Route" icon="plug">+ A thin HTTP adapter: validate input, run a workflow (or query for reads), shape the response.+ </Card>+ <Card title="Frontend" icon="window">+ Admin/Vendor panels and storefront. Talks to the API only through the typed SDK — never raw `fetch`.+ </Card>+</CardGroup>++Why this shape matters:++- **Testability** — business logic lives in workflows, which can be run in isolation without an HTTP request.+- **Reusability** — a workflow can be called from a route, a subscriber, or a scheduled job.+- **Upgrade safety** — modules stay thin, so Medusa framework upgrades rarely touch your logic.+- **Rollback** — because mutations are workflow steps, a failure halfway through automatically undoes the earlier steps.++## The non-negotiables++These are hard rules. Breaking one produces code that looks like it works but silently violates the architecture — no rollback, broken upgrades, or data written outside a workflow.++<Warning>+ **All mutations go through a workflow.** Never write to the database directly from an API route, a subscriber, or a scheduled job. Reads may query directly; writes must run a workflow so they get validation, compensation, and event emission.+</Warning>++<Warning>+ **Only `GET`, `POST`, and `DELETE`.** Mercur (following Medusa) does not use `PUT` or `PATCH`. Updates are modeled as `POST` to the resource. Keep every route to these three verbs.+</Warning>++<Warning>+ **No cross-module service calls.** A module service must never import or call another module's service. Modules are isolated. Cross-module reads happen through **Query** (the graph); cross-module relationships are declared with **module links**; cross-module writes are coordinated in a **workflow**.+</Warning>++Two more that follow from the above:++- **Modules are thin.** A module service is CRUD plus small, self-contained helpers. If a method touches more than one module's data, it belongs in a workflow, not the service.+- **One mutation per step.** Each workflow step performs a single mutation and defines how to compensate it. This is what makes rollback reliable.++## Logic-placement cheat sheet++When you're about to write a piece of logic, find the concern in this table before you decide where the code goes. The **"Never put it in"** column is the part people get wrong.++| Concern | Put it in | Never put it in |+| --- | --- | --- |+| **Input shape / type validation** | API route (Zod schema on the request) | Module service, workflow |+| **Ownership / scoping** (e.g. this seller may only see its own orders) | API middleware (filters) + workflow guard | The frontend alone |+| **Business orchestration** (multi-step, multi-module operations) | Workflow (steps + compensation) | API route handler, module service |+| **A single data mutation** | Workflow step (module service call inside it) | API route, subscriber, job |+| **Cross-module reads** | Query (`query.graph`) | Direct service-to-service imports |+| **Cross-module relationships** | Module link (`defineLink`) | A foreign key inside one module's model |+| **Reacting to something that happened** (emails, sync, indexing) | Subscriber (listens to an event, runs a workflow) | Inline inside the route that caused it |+| **Periodic / time-based work** (polling, daily settlement) | Scheduled job (runs a workflow) | A subscriber, a route |+| **Emitting domain events** | Workflow step (`emitEventStep`) | Module service, subscriber |+| **Response shaping / field selection** | API route `queryConfig` (fields) | The module service |+| **Presentation, composition, UX** | Frontend (panels / storefront) | The API or any backend layer |++<Tip>+ A quick mental test: *"Does this change data?"* → it must run inside a workflow. *"Does this react to a change?"* → it's a subscriber. *"Does this run on a schedule?"* → it's a job. *"Is this just reading and shaping data for a screen?"* → it's a route + Query. Everything else is either module CRUD or frontend.+</Tip>++## How to read the rest of this section++Each page that follows drills into one layer and its rules:++<CardGroup cols={2}>+ <Card title="Modules" href="/rc/resources/best-practices/modules" icon="cube">+ Thin CRUD, naming, and what must never live in a service.+ </Card>+ <Card title="Module links" href="/rc/resources/best-practices/module-links" icon="link">+ `defineLink`, link direction, and filtering by links.+ </Card>+ <Card title="Workflows" href="/rc/resources/best-practices/workflows" icon="diagram-project">+ Composition constraints, steps, compensation, and the query engine.+ </Card>+ <Card title="API routes" href="/rc/resources/best-practices/api-routes" icon="plug">+ Thin adapters, Zod validation, middlewares as filters, `queryConfig`.+ </Card>+ <Card title="Subscribers & jobs" href="/rc/resources/best-practices/subscribers-and-jobs" icon="clock">+ Event-driven side effects and scheduled work done safely.+ </Card>+</CardGroup>diff --git a/apps/docs/rc/resources/best-practices/subscribers-and-jobs.mdx b/apps/docs/rc/resources/best-practices/subscribers-and-jobs.mdxnew file mode 100644index 000000000..eee04f1fa--- /dev/null+++ b/apps/docs/rc/resources/best-practices/subscribers-and-jobs.mdx@@ -0,0 +1,133 @@+---+title: "Subscribers & jobs"+description: "React to events and run periodic work safely — fetch from { id }, mutate via workflows, log-don't-throw, idempotency and loop guards, cron jobs."+---++Subscribers and scheduled jobs are the two ways work happens *outside* a request. Both follow the same core rule as everything else: **they never mutate directly — they run a [workflow](/rc/resources/best-practices/workflows).**++## Subscribers — react to events++A subscriber listens for a domain event (emitted by a workflow via `emitEventStep`) and runs an asynchronous side effect: send a notification, sync a search index, create a link. It lives in `src/subscribers/` and exports a handler plus a `config` naming the event.++```ts title="src/subscribers/brand-created.ts"+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++export default async function brandCreatedHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ const { id } = event.data+ // ...fetch, then run a workflow+}++export const config: SubscriberConfig = {+ event: "brand.created",+}+```++### Fetch full data from `{ id }`++<Warning>+ Event payloads carry **ids, not entities.** A subscriber receives `{ id }` (sometimes a couple of ids) and must fetch the full record it needs via Query. Never rely on a fat event payload — it goes stale and couples the emitter to every consumer's needs.+</Warning>++```ts+const query = container.resolve(ContainerRegistrationKeys.QUERY)+const { data: [brand] } = await query.graph({+ entity: "brand",+ fields: ["id", "name", "products.*"],+ filters: { id: event.data.id },+})+```++### Mutate via workflows, never directly++If the subscriber needs to change data, it runs a workflow — same as a route would. The subscriber is the trigger; the workflow is the work.++```ts+await createBrandNotificationWorkflow(container).run({+ input: { brand_id: brand.id },+})+```++### Log, don't throw++<Warning>+ A subscriber runs detached from the request. Throwing doesn't surface to a user — it just fails silently or spams retries. **Catch errors and log them** (resolve the `logger`), then decide explicitly whether to rethrow for a retry or swallow.+</Warning>++```ts+const logger = container.resolve("logger")+try {+ await doWork()+} catch (e) {+ logger.error(`brand-created subscriber failed for ${event.data.id}: ${e}`)+}+```++### Idempotency and loop guards++Events can be delivered more than once, and a subscriber that mutates data can re-trigger the very event it listens to. Two defences:++- **Idempotency** — make the handler safe to run twice. Check current state before acting (e.g. "is this product already linked to a brand?" before creating the link), or clear the marker that triggered the work so a redelivered event finds nothing left to do.+- **Loop guards** — if handling event X causes a mutation that emits X again, gate on a condition that becomes false after the first run, or key off a marker you set. Never emit the same event unconditionally from its own subscriber.++<Tip>+ A good idempotency check reads the current state through Query first and returns early if the work is already done. This makes redelivery harmless and removes the need for exactly-once guarantees.+</Tip>++## Scheduled jobs — periodic work++A scheduled job runs on a cron interval to do time-based work: poll for records that became ready, reconcile drifted counters, emit a "settle now" event. It lives in `src/jobs/`, exports a handler taking the container, and a `config` with a `name` and a cron `schedule`.++```ts title="src/jobs/deactivate-stale-brands.ts"+import { MedusaContainer } from "@medusajs/framework/types"++export default async function deactivateStaleBrands(container: MedusaContainer) {+ const logger = container.resolve("logger")+ const query = container.resolve(ContainerRegistrationKeys.QUERY)++ const { data: stale } = await query.graph({+ entity: "brand",+ fields: ["id"],+ filters: { is_active: true /* + your staleness condition */ },+ })++ // pass all ids at once — the workflow handles the batch, not the job+ await deactivateBrandsWorkflow(container).run({+ input: { ids: stale.map((b) => b.id) },+ })++ logger.info(`deactivated ${stale.length} stale brands`)+}++export const config = {+ name: "deactivate-stale-brands",+ schedule: "0 1 * * *", // daily at 01:00 UTC+}+```++### When to use a job vs a subscriber++| Trigger | Use |+| --- | --- |+| "Something happened" (a workflow emitted an event) | **Subscriber** |+| "It's time" / "poll for anything that became ready" | **Scheduled job** |++A time-based pipeline often combines both: a daily job finds records that became eligible and emits an event (say `brand.review_due`), and a *subscriber* turns each event into a workflow run. Polling for "what's ready" is the job; reacting to each item is the subscriber.++### Job best practices++- **Do the work in batches** and bound result sets — a job that `SELECT`s an unbounded table will eventually time out. Page through with `LIMIT`/`OFFSET` or a cursor.+- **Idempotent by design** — a job re-runs on every tick; it must only act on records still needing action (filter on the not-yet-processed state).+- **Mutations run workflows**, reads run Query — same as everywhere.+- **Log a summary** each run (how many processed) so drift is visible.++## Checklist++- Subscriber `config.event` names a real emitted event; handler fetches full data from `{ id }` via Query.+- Subscriber mutations run a workflow; errors are caught and logged, not thrown blindly.+- Handler is idempotent and can't retrigger its own event without a guard.+- Job exports `{ name, schedule }`; cron is correct (UTC).+- Job filters to records still needing work, batches large sets, and logs a summary.+- Neither a subscriber nor a job writes to the database outside a workflow.diff --git a/apps/docs/rc/resources/best-practices/types.mdx b/apps/docs/rc/resources/best-practices/types.mdxnew file mode 100644index 000000000..7352355a4--- /dev/null+++ b/apps/docs/rc/resources/best-practices/types.mdx@@ -0,0 +1,120 @@+---+title: "Types & augmentation"+description: "Type the panels against your own backend extensions — augment framework DTOs with declaration merging so every SDK endpoint carries your custom data."+---++The panels are fully typed against the API through `@mercurjs/types` and the typed SDK. When you extend the backend — adding [custom fields](/rc/resources/best-practices/custom-fields), a [linked module](/rc/resources/best-practices/module-links), an extra field on a DTO — those additions aren't in the shipped types yet. You close the gap in the **frontend** with a small declaration-merging `.d.ts` file. Do that once and *every* SDK call that returns the entity carries your field, typed.++<Warning>+ **Never use `any` to paper over a missing field.** Casting a response to `any` (or `as { custom_fields: … }` at each call site) throws away type-checking and has to be repeated everywhere. Augment the type once instead.+</Warning>++## The scenario: a custom field, typed end-to-end++Say you added a custom field on the backend — for example `is_featured` on `product` (see [Custom fields](/rc/resources/best-practices/custom-fields)). The value now comes back from the API, but the panel's `ProductDTO` doesn't know about it, so `product.is_featured` is a type error.++Fix it in the panel with a declaration-merging file.++### Why merging works here++The `ProductDTO` the SDK returns ultimately resolves to Medusa's upstream `ProductDTO`, which is declared as an **`interface`** in `@medusajs/types`. Interfaces are open, so you can **merge into it** with `declare module "@medusajs/types"`.++Because everything downstream — `@mercurjs/types`, the SDK response wrappers (`AdminProductResponse`, list responses), and the panel hooks — refers back to that same interface, your added members appear in all of them at once. You augment in one place and every product-returning endpoint is typed.++### Add the `.d.ts` in the panel++Drop a declaration file anywhere under the panel's `src/` (it's picked up by the app's `tsconfig`):++```ts title="apps/vendor/src/types/custom-fields.d.ts"+import "@medusajs/types"++declare module "@medusajs/types" {+ interface ProductDTO {+ custom_fields?: {+ is_featured?: boolean+ }+ }+}+```++<Warning>+ Two rules or the augmentation silently does nothing:++ - The module name in `declare module "..."` must be the package that declares the interface you're merging into — here `@medusajs/types`, the owner of `UpstreamProductDTO`, **not** `@mercurjs/types` (which only aliases it).+ - The file must be a module. Add an `import "@medusajs/types"` (or a trailing `export {}`) so TypeScript treats it as one.+</Warning>++### Now the whole SDK is typed++With that one file in place, no cast is needed anywhere:++```ts title="Every product endpoint carries the field"+const { products } = await sdk.vendor.products.query()+products[0].custom_fields?.is_featured // ✅ typed, no cast++const { product } = await sdk.vendor.products.$id.query({ $id: id })+product.custom_fields?.is_featured // ✅ typed everywhere ProductDTO flows+```++<Tip>+ Types and runtime are separate concerns: this `.d.ts` makes the field *typed*, but it only *arrives* if the fetch asks for it. Let the [custom-fields `link` / registry merge](/rc/resources/best-practices/custom-fields#the-extension-api-link-property) add the fields to the built-in panel fetches rather than hand-adding `+field.*` — the vendor product query in particular rejects arbitrary `*`-relation overrides.+</Tip>++## Linked data resolves the same way++The augmentation isn't limited to a custom field's own value — it's how you make **linked-module data** typed too. When a [custom-fields config](/rc/resources/best-practices/custom-fields#the-extension-api-link-property) declares a `link`, the panel fetches that module's data alongside the entity ([SPEC-021](/rc/references/panel-extension-api)): `link: "brand"` merges `brand.*` into the built-in product fetch for you — no hand-written field list.++Pair that one config line with a matching augmentation, and the linked data is both **present at runtime** and **typed everywhere `ProductDTO` is imported**:++```ts title="src/custom-fields/product.tsx — declare the link (runtime)"+export default defineCustomFieldsConfig({+ model: "product",+ link: "brand", // brand.* is fetched with every product+ list: {+ columns: [+ { id: "brand_name", header: "Brand", component: ({ row }) => row.brand?.name },+ ],+ },+})+```++```ts title="src/types/brand.d.ts — declare the shape (types)"+import "@medusajs/types"++declare module "@medusajs/types" {+ interface ProductDTO {+ brand?: { id: string; name: string }+ }+}+```++Now any code that imports `ProductDTO` — a page, a hook, a column renderer — sees `product.brand` resolved, with the data already fetched by the `link`:++```ts+const { product } = await sdk.vendor.products.$id.query({ $id: id })+product.brand?.name // ✅ present (via link) and typed (via augmentation)+```++<Tip>+ The `link` does the fetching, the `.d.ts` does the typing — you write each once, per model, and every product-returning endpoint in the panel is covered. This is the payoff of augmentation: register the relationship in one place, consume it as a plain typed property everywhere.+</Tip>++## Where each type goes++| You're adding… | Put it in |+| --- | --- |+| A field your API now returns on an entity | A panel `.d.ts` merging into the framework DTO (`declare module "@medusajs/types"`) |+| A one-off request/response shape for a custom route | Infer it from the Zod validator (`z.infer<typeof Schema>`) and export it |+| A brand-new Mercur/domain DTO | The domain folder in `@mercurjs/types`, re-exported from `index.ts` |++<Warning>+ DTOs and enums the platform already ships (`ProductDTO`, `SellerStatus`, `MercurModules`, `HttpTypes`) are imported from `@mercurjs/types` — never redeclared. In the dashboards, `HttpTypes` comes from `@mercurjs/types` too, which is what keeps request/response types aligned with Mercur's extended routes.+</Warning>++## Checklist++- No `any`, and no per-call-site casts for extended data.+- Backend additions typed in the panel via a `.d.ts` merging into the **framework** interface that owns the DTO.+- Augmentation files name the correct package and are real modules (`import`/`export {}`).+- Extended fields are requested with `+field.*` so they actually arrive.+- Shipped types imported from `@mercurjs/types`; one-off shapes inferred from Zod.diff --git a/apps/docs/rc/resources/best-practices/workflows.mdx b/apps/docs/rc/resources/best-practices/workflows.mdxnew file mode 100644index 000000000..3780b4f61--- /dev/null+++ b/apps/docs/rc/resources/best-practices/workflows.mdx@@ -0,0 +1,173 @@+---+title: "Workflows"+description: "Where all business logic and mutations live — composition-function constraints, one-mutation-per-step with compensation, reusing built-in steps, and the query engine."+---++A workflow is the orchestration layer: it coordinates a business operation across one or more modules as a series of **steps**, with automatic rollback (**compensation**) if any step fails. Every mutation in Mercur runs inside a workflow — this is the single most important rule in the [architecture](/rc/resources/best-practices/overview).++<Warning>+ **All mutations go through a workflow.** API routes, subscribers, and scheduled jobs never write to the database directly — they *run a workflow*. That is what gives every mutation validation, event emission, and rollback.+</Warning>++<Note>+ Workflows are a [Medusa framework primitive](https://docs.medusajs.com/learn/fundamentals/workflows). This page focuses on the constraints and conventions that trip people (and agents) up.+</Note>++## The composition function is not normal JavaScript++The function you pass to `createWorkflow` is a **composition function**. It runs once at build time to wire steps together — it does **not** execute your business logic at request time. Because of that, it has hard constraints:++<Warning>+ Inside a `createWorkflow` composition function you must **not**:++ - use `async` / `await`+ - use arrow functions for the composition body (use a named `function`)+ - use `if` / `else`, `for`, `while`, or `try/catch`+ - use `new Date()`, `Math.random()`, or any non-deterministic call+ - access properties of a step's output directly (e.g. `result.id`)++ These run at composition time, not execution time, so they either do nothing useful or break replay/rollback.+</Warning>++Anything that looks like normal logic goes into a **step** (for side effects) or a **`transform`** (for shaping data between steps):++```ts title="src/workflows/create-brands.ts"+import {+ createWorkflow,+ transform,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { createBrandsStep } from "./steps"++export const createBrandsWorkflow = createWorkflow(+ "create-brands",+ function (input: CreateBrandsWorkflowInput) {+ // ✅ shape data with transform, not inline expressions+ const toCreate = transform(input, ({ brands }) =>+ brands.map((b) => ({ ...b, is_active: b.is_active ?? true }))+ )++ const brands = createBrandsStep(toCreate)++ return new WorkflowResponse(brands)+ }+)+```++<Tip>+ Need a conditional or a computed value? Use `transform` to derive data, `when` to run a step conditionally, and put date/random/id generation **inside a step**. Never branch in the composition body itself.+</Tip>++## One mutation per step + compensation++A step is the unit of work and the unit of rollback. The rule: **each step performs a single mutation and defines how to undo it.** `createStep` takes an invoke function and a compensation function; the invoke returns a `StepResponse` whose second argument is the data the compensation needs.++```ts title="src/workflows/steps/create-brands.ts"+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"+import BrandModuleService from "../../modules/brand/service"+import { BRAND_MODULE } from "../../modules/brand"++export const createBrandsStep = createStep(+ "create-brands",+ async (data: CreateBrandInput[], { container }) => {+ const service = container.resolve<BrandModuleService>(BRAND_MODULE)+ const brands = await service.createBrands(data)+ // 2nd arg → passed to the compensation function below+ return new StepResponse(brands, brands.map((b) => b.id))+ },+ async (ids: string[] | undefined, { container }) => {+ if (!ids?.length) {+ return+ }+ const service = container.resolve<BrandModuleService>(BRAND_MODULE)+ await service.deleteBrands(ids)+ }+)+```++If a later step in the workflow throws, Medusa runs the compensation functions of the already-completed steps in reverse — the `createBrands` above is undone by `deleteBrands`. Splitting mutations one-per-step is what makes this reliable: a step that does two writes can only half-compensate.++## Reuse built-in steps++Don't hand-roll what the framework already ships. Medusa's `core-flows` exports composable steps you should reuse instead of writing your own:++| Need | Built-in step |+| --- | --- |+| Create/remove module links | `createRemoteLinkStep` / `dismissRemoteLinkStep` |+| Emit a domain event | `emitEventStep` |+| Call another workflow as a step | `otherWorkflow.runAsStep({ input })` |++```ts title="Composing built-in steps + a sub-workflow"+import { emitEventStep } from "@medusajs/medusa/core-flows"++export const createBrandsWorkflow = createWorkflow(+ "create-brands",+ function (input: CreateBrandsWorkflowInput) {+ const brands = createBrandsStep(input.brands)++ // reuse a whole workflow as one step+ notifyOwnersWorkflow.runAsStep({ input: { brands } })++ // reuse the built-in event step+ emitEventStep({ eventName: "brand.created", data: { ids: brands } })++ return new WorkflowResponse(brands)+ }+)+```++<Tip>+ Prefer `runAsStep` over duplicating logic. If two workflows need the same sequence, extract it into its own workflow and call it as a step from both — you get one place to maintain and correct compensation for free.+</Tip>++## Hooks — let others extend your workflow++Expose extension points with `createHook` so consumers can inject behaviour (validation, side effects) without forking the workflow. Add a `validate` hook before the mutation and a `brandsCreated` hook after it:++```ts+const validate = createHook("validate", { input })++const brands = createBrandsStep(input.brands)++const brandsCreated = createHook("brandsCreated", {+ brands,+ additional_data: input.additional_data,+})++return new WorkflowResponse(brands, {+ hooks: [validate, brandsCreated],+})+```++Consumers register a handler on the hook to run custom logic at that point. This is the sanctioned way to extend a workflow — see [Extend a workflow](/rc/resources/customization/extend-a-workflow).++## The query engine++Reads inside a step (and anywhere else) go through **Query** — the graph engine that resolves data across modules and links. Resolve it from the container and call `query.graph`:++```ts title="Reading across modules inside a step"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++const query = container.resolve(ContainerRegistrationKeys.QUERY)++const { data: brands } = await query.graph({+ entity: "brand",+ fields: ["id", "name", "products.*"], // follows the product ↔ brand link+ filters: { is_active: true },+})+```++<Warning>+ Query is for **reads**. Never try to mutate through it, and never resolve another module's service inside a step to read its data — go through Query so module isolation and links are respected.+</Warning>++## Checklist for a workflow++- Composition function is a named `function`, with no `async`/`await`, `if`, loops, `try/catch`, `new Date()`, or step-output property access.+- Data shaping between steps uses `transform`; conditional steps use `when`.+- Each step does exactly one mutation and defines a compensation function.+- `StepResponse` passes the compensation the data it needs to undo the work.+- Built-in steps (`createRemoteLinkStep`, `emitEventStep`) and `runAsStep` are reused instead of reimplemented.+- Reads use `query.graph`; no cross-module service calls.+- Extension points are exposed as hooks, not by forking.