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: rewrite architecture page around layers and extension zones (#1412)
Viktor Holik89bcd2af3ff2
diff --git a/apps/docs/learn/architecture.mdx b/apps/docs/learn/architecture.mdxindex 41b6facfb..92649ecdd 100644--- a/apps/docs/learn/architecture.mdx+++ b/apps/docs/learn/architecture.mdx@@ -1,286 +1,336 @@---title: "Architecture"-description: "How the Mercur enterprise marketplace platform is built: its layers, building blocks, and how the pieces fit together."+description: "How Mercur is put together: the runtime layers, the boundary between the marketplace platform and your own code, and the zones you extend."----Mercur is the open-source enterprise marketplace platform, built on-[Medusa](https://medusajs.com). It is composable, API-first, and AI-native, and-it runs on infrastructure you own.+Mercur is an open-source marketplace platform. It gives you a multi-vendor+commerce backend, an admin panel, and a vendor portal that you deploy on your own+infrastructure and change at the source level.-Mercur is not a standalone application, and it is not something you assemble from-scratch. Medusa provides the commerce engine, such as products, pricing, carts,-orders, payments, and fulfillment. Mercur adds the marketplace layer on top:-sellers, commissions, order splitting, payouts, and a governed change pipeline,-along with an admin panel and a vendor portal. Operators run the marketplace with-role-based access control and an auditable change history, on a codebase they own-outright.+It is not a hosted service you integrate with, and it is not a starter kit you+finish yourself. Mercur is a running system on day one, with defined seams for+the parts every marketplace does differently: onboarding rules, commission logic,+approval policy, back-office integrations, and the screens your teams work in.-This page explains how the platform is structured and how its parts fit together.+This page describes those layers and those seams. If you are evaluating Mercur,+the two questions it answers are **what runs where** and **where does my code go**.-## High-level architecture+## Design principles-Mercur is layered. Each layer owns one responsibility and talks only to the layer-beneath it, so you can reason about, extend, or replace any layer on its own.+Everything below follows from four decisions.-```mermaid-graph TD- subgraph Frontend Layer- A[Admin Panel]- B[Vendor Portal]- C[Storefront]- end+- **You run it.** MIT-licensed, PostgreSQL, Node. No vendor in the request path, no GMV fee, no proprietary runtime. Self-host, or deploy to any cloud that runs a Node process and a database.+- **Extension over configuration.** Instead of hundreds of settings, the platform exposes typed extension zones: workflow hooks, API routes, modules, custom fields, pages, and widgets. When a zone isn't enough, the source is yours to change.+- **Marketplace on top of commerce, not instead of it.** Products, carts, orders, payments, and fulfillment are handled by [Medusa](https://medusajs.com), a mature commerce engine. Mercur adds only what multi-vendor requires: sellers, offers, order splitting, commissions, payouts, and governance.+- **Governance is structural.** Role scoping, the product change pipeline, and exact-precision money arithmetic are properties of the architecture, not features you enable.- subgraph API Layer- D["/admin/*"]- E["/vendor/*"]- F["/store/*"]- end+## The layers++Mercur is a single deployable backend with three API surfaces, plus two panel+applications that are ordinary clients of those APIs.- subgraph Marketplace Layer - Mercur- G[Modules · Workflows · Links · Subscribers · Events]+```mermaid+graph TD+ subgraph Clients+ A[Admin Panel<br/>React]+ B[Vendor Portal<br/>React]+ C[Storefront<br/>any framework]+ D[Your services<br/>ERP · PIM · agents]end- subgraph Commerce Layer - Medusa- H[Products · Orders · Carts · Payments · Fulfillment]+ subgraph "Backend — one Node process"+ E["/admin/*"]+ F["/vendor/*"]+ G["/store/*"]+ H[Marketplace domain<br/>sellers · offers · commissions · payouts · governance]+ I[Commerce domain<br/>products · carts · orders · payments · fulfillment]end- I[(PostgreSQL)]+ J[(PostgreSQL)]+ K[Redis · event bus, workflow engine, cache]+ L[Providers<br/>payment · payout · fulfillment · notification · search]- A --> D- B --> E- C --> F- D --> G- E --> G- F --> G+ A --> E+ B --> F+ C --> G+ D --> E+ E --> H+ F --> HG --> HH --> I+ I --> J+ H --> J+ H --> K+ H --> L```-### Commerce layer+### Data++One PostgreSQL database. Every domain owns its own tables and never reaches into+another's; relationships across domains are declared explicitly as links (see+[Links](#links)). That isolation is what makes a domain replaceable, and what+keeps a schema change local instead of platform-wide.-Medusa provides the core commerce engine: products, pricing, carts, orders,-payments, fulfillment, promotions, and inventory. Mercur does not replace any of-it. Mercur builds on top through Medusa's extension model, using custom modules,-links, workflows, and API routes. This is the one place the word framework-applies. Medusa is the commerce framework, and Mercur is the platform you run on-it.+Redis backs the event bus, the workflow engine, and caching in production. In+development both fall back to in-memory implementations, so a laptop needs+nothing but Postgres.-### Marketplace layer+### Domain-This is where Mercur's own code lives, packaged as the `@mercurjs/core` plugin. It-adds marketplace modules such as Seller, Commission, Offer, Payout, Product-Attribute, and Product Edit, plus the workflows that coordinate marketplace-operations like order splitting, product approvals, and commission calculation.-Links connect these modules to Medusa's core entities without modifying the-original models.+The domain layer is where marketplace behaviour lives: seller accounts and+members, offers against a shared product catalog, commission rules and their+resolution, payout accounts and transfers, order groups, the product change+pipeline. It calls into the commerce domain for anything commerce already does.-### API layer+Two things about this layer matter to an architect:-Mercur exposes three sets of HTTP endpoints, one per audience.+- **It is not a wrapper.** Mercur does not proxy or re-implement commerce endpoints. Marketplace concepts are first-class records with their own lifecycle, joined to commerce records through links.+- **Your own domains sit beside it.** A module you write, a module Mercur ships, and a module Medusa ships are the same kind of object, registered the same way, with the same access to the container, the event bus, and the workflow engine. There is no privileged inner ring.-| API | Path | Purpose |-| ---------- | ----------- | -------------------------------------------------------------------------- |-| **Admin** | `/admin/*` | Platform administration: manage sellers, configure commission rates, view payouts. |-| **Vendor** | `/vendor/*` | Seller operations: manage products, orders, fulfillment, shipping, inventory, payouts. |-| **Store** | `/store/*` | Storefront: browse sellers, manage carts, check out with order splitting. |+### API-Each route is composed of a request handler, middleware, query configuration, and-Zod validators. The middleware is where access control lives, so every vendor-request is scoped to its own seller's data before the handler runs. See the-[API conventions](/references/api/conventions) for authentication and scoping.+Three HTTP surfaces, one per audience, separated because their authorization+models differ, not because their data does.-### Panels and clients+| Surface | Path | Audience | Scoping |+| ---------- | ----------- | --------------------- | ------------------------------------------------------------------ |+| **Admin** | `/admin/*` | Marketplace operators | Platform-wide, gated by role |+| **Vendor** | `/vendor/*` | Sellers | Every request is narrowed to the caller's seller before the handler |+| **Store** | `/store/*` | Customers, storefront | Public catalog and the caller's own cart, orders, and account |-Three interfaces consume the APIs.+A route is a thin adapter: middleware authenticates and scopes, a Zod validator+checks the payload, and the handler runs a workflow for writes or the query+engine for reads. Business logic does not live in routes, which is why adding+one is cheap and overriding one is safe. See the+[API conventions](/references/api/conventions).-- **Admin Panel:** a React application on Medusa UI. Operators approve sellers, set commission rates, and monitor payouts across the whole marketplace.-- **Vendor Portal:** a React application for sellers to manage products, orders, fulfillment, and payouts, scoped to their own store.-- **Storefront:** the customer-facing application. Build it with any frontend that consumes the Store API.+### Clients-Both panels talk to the API through `@mercurjs/client`, a fully typed fetch-wrapper generated from the real route definitions, so requests and responses stay-in sync with the backend.+The admin panel and the vendor portal are separate React applications, not a+templated back office. They talk to the backend through `@mercurjs/client`, a+typed fetch wrapper generated from the real route definitions — including routes+you add — so a backend change that breaks a caller fails at `tsc`, not in+production.-## Building blocks of the marketplace layer+The storefront is deliberately not shipped as a fixed application. Anything that+speaks HTTP consumes the Store API; a reference Next.js storefront is available+to start from.-The marketplace layer is assembled from four Medusa-native primitives. Together-they keep the platform composable: each piece is small, explicit, and replaceable.+## The building blocks++Four primitives compose the domain layer. You use the same four to extend it.### Modules-A module encapsulates the data models and business logic for one domain, such as-Seller or Commission. Each module is self-contained, with its own models, service,-and migrations. Modules never reference each other directly. They communicate-through links and workflows, which keeps domains decoupled.-[Learn about modules](/resources/best-practices/modules).+A module owns one domain: its data models, its service, its migrations. Modules+never import each other. That constraint is what lets you swap Mercur's+commission logic for your own, or drop a module you don't use, without a+refactor rippling outward. [Modules →](/resources/best-practices/modules)### Links-A link defines a relationship between a Mercur module and a Medusa core entity-without modifying either model. For example, the product-seller link connects a-Medusa `Product` to a Mercur `Seller` and acts as the allowlist of who may sell-what. Dozens of links wire the marketplace layer into the commerce layer.-[Learn about module links](/resources/best-practices/module-links).+A link declares a relationship between records in two modules without either+module knowing about the other. The product–seller link, for example, is what+allowlists which sellers may sell a given product — expressed as a link rather+than a foreign key, so neither the product model nor the seller model is+modified. Your modules link to built-in entities exactly the same way.+[Links →](/resources/best-practices/module-links)### Workflows-A workflow orchestrates a multi-step operation that spans modules. Workflows-support compensation, which rolls back automatically on failure, and hooks, which-are the extension points you inject custom logic into. The central one is-`completeCartWithSplitOrdersWorkflow`, which validates a cart, splits it by-seller, creates an order for each, allocates payment, and calculates commissions.-[Learn about workflows](/resources/best-practices/workflows).+A workflow is a multi-step operation with automatic compensation: if step five+fails, steps one through four roll back. Anything that crosses domains or must+not half-happen is a workflow — seller approval, payout transfer, and above all+cart completion, which validates the cart, splits it by seller, creates an order+each, allocates payment, and computes commission lines as one atomic unit.++Workflows also expose **hooks**, which is the primary backend extension zone.+[Workflows →](/resources/best-practices/workflows)++### Events and subscribers-### Subscribers and events+Workflows emit events; subscribers react asynchronously. Notifications, webhooks+to your systems, search indexing, and payout side effects all hang off this,+which keeps the transactional path short and lets you add behaviour without+touching the workflow that triggered it.+[Subscribers and jobs →](/resources/best-practices/subscribers-and-jobs)-Workflows emit events. Subscribers listen and run asynchronous side effects, such-as sending notifications, calling webhooks, or transferring payouts. This keeps-the core workflows focused while the platform reacts to change.-[Learn about subscribers and jobs](/resources/best-practices/subscribers-and-jobs).+## Extension zones-## Enterprise governance by design+This is the part that determines what a build actually costs. Mercur exposes six+zones. Each one is typed, each one is additive, and none of them require forking+or patching platform code.-Governance lives in the architecture, not in a bolt-on. The same primitives that-make the platform composable also make it governable.+```mermaid+graph LR+ subgraph Backend+ A[Workflow hooks<br/>inject steps into existing flows]+ B[API routes<br/>add or override endpoints]+ C[Modules and links<br/>add domains]+ D[Custom fields<br/>extra data on built-in entities]+ end+ subgraph Panels+ E[Pages<br/>new routes]+ F[Widgets<br/>components in named zones]+ G[Custom field UI<br/>forms · rows · columns]+ H[Navigation<br/>reorder · relabel · hide]+ end+```-- **Role-based access control.** `withMercur()` registers a roles module, so vendor requests are scoped to their own seller by default. Operators and sellers each see only what their role permits.-- **An auditable change pipeline.** Every product edit is captured as an immutable `ProductChange` record: who changed what, and who approved it. Low-risk edits auto-confirm, and the rest wait for operator review.-- **Financial accuracy.** All commission arithmetic uses BigNumber with arbitrary precision, so split payments and payouts stay exact to the cent.-- **A governed surface for AI agents.** The typed client, exposed workflows, and `llms.txt` give AI agents structured contracts to build against, inside the same role and review guardrails as human users. Agents extend the platform. They do not bypass its governance.-- **You own the deployment.** Mercur is MIT-licensed and runs on infrastructure you control. Blocks ship as source code, so you own every line, with no hosted vendor in the request path and no commission on gross merchandise value.+### 1. Workflow hooks — change what happens+The default way to change platform behaviour. A hook is a declared point inside+an existing workflow where you register your own step. Your step runs inside the+original transaction and participates in its rollback, so you are not+reimplementing the flow to add one rule.-## How a multi-vendor order flows+```ts src/workflows/hooks/seller-approved.ts+import { approveSellerWorkflow } from "@mercurjs/core/workflows"++approveSellerWorkflow.hooks.sellerApproved(+ async ({ seller_id }, { container }) => {+ await container.resolve("erp").createVendorAccount(seller_id)+ }+)+```-A single customer cart can hold items from many sellers. Order splitting is where-the marketplace, commerce, commission, and payout layers work together.--1. **Customer adds items** from multiple sellers to one cart (Store API).-2. **Cart completion** triggers the split-order workflow (marketplace layer).-3. Items are **grouped by seller**, and a separate order is created for each (commerce and marketplace layers).-4. **Commission lines** are calculated per order from the matching rates (Commission module).-5. **Payment is split** proportionally across the seller orders (commerce layer).-6. Each seller's order is **credited to its payout account** after commission (Payout module).-7. **Events are emitted**, triggering notifications, webhook calls, and other side effects (subscribers).-8. Sellers **manage their orders** through the Vendor Portal (Vendor API).-9. The operator **monitors everything** through the Admin Panel (Admin API).--## Technology stack--| Layer | Technology |-| -------------------- | --------------------------------------------------- |-| Runtime | Node.js 20+, TypeScript |-| Commerce framework | Medusa v2 |-| Database | PostgreSQL |-| Frontend | React 18, React Router, Vite |-| Data fetching | TanStack React Query |-| UI components | Medusa UI, Radix UI |-| Form handling | React Hook Form, Zod |-| Tables | TanStack React Table |-| Build | Turborepo (monorepo), Bun (package manager), tsup |-| Internationalization | i18next |--## Core plugin layout--`@mercurjs/core` is the package that holds all marketplace logic. It is structured-as a standard Medusa plugin.+Reach for a hook when the answer is "the standard flow, plus something."+[Extend a workflow →](/resources/customization/extend-a-workflow)++### 2. API routes — add endpoints++Drop a `route.ts` under `src/api/**` and the endpoint exists. Routes nest under+the built-in ones, so a new resource can hang off an existing entity rather than+living off to the side.```-core/src/-├── modules/ # Data models and services-│ ├── seller/ # Seller registration, profiles, members, order groups-│ ├── commission/ # Commission rates, rules, calculation-│ ├── offer/ # Seller listings against the shared product catalog-│ ├── payout/ # Payout accounts, onboarding, payouts-│ ├── product-attribute/ # Typed attribute catalog and values-│ ├── product-edit/ # Product change requests and audit trail-│ └── ... # Media, custom fields, and more-├── links/ # Relationships between modules-├── workflows/ # Multi-step business processes-│ ├── seller/ # Seller lifecycle workflows-│ ├── cart/ # Cart completion with order splitting-│ ├── commission/ # Commission rate and line management-│ ├── payout/ # Payout processing and crediting-│ ├── offer/ # Offer lifecycle-│ ├── product/ # Product approval and seller linking-│ ├── product-edit/ # Change-request lifecycle-│ ├── order-group/ # Order group operations-│ └── ... # Attributes, shipping, inventory, promotions-├── api/ # HTTP route handlers-│ ├── admin/ # Admin API routes-│ ├── vendor/ # Vendor API routes-│ ├── store/ # Store API routes-│ └── hooks/ # Webhook handlers-├── subscribers/ # Event listeners-├── providers/ # Third-party provider integrations-└── jobs/ # Scheduled background tasks+src/api/vendor/sellers/documents/route.ts → GET/POST /vendor/sellers/documents+src/api/vendor/sellers/documents/[id]/route.ts → GET/DELETE /vendor/sellers/documents/:id```-## Distribution: blocks you own+Your routes get the same treatment as the built-in ones: vendor requests are+already scoped to the caller's seller by the surrounding middleware, and codegen+picks the route up so it appears on the typed client with real request and+response types.++[Create an API route →](/resources/best-practices/api-routes)-Mercur ships features as blocks, not as an opaque dependency. The CLI copies-source code directly into your project, so a block is a self-contained piece of-functionality: a module, a workflow, an API route, or a UI extension.+### 3. Modules and links — add domains-This is what code ownership means in practice.+When the data has its own lifecycle — subscriptions, RMAs, contracts, quotas —+it is a module, not a field. You define the models and service, link the module+to the built-in entities it relates to, and it becomes queryable in the same+graph as everything else. This is how substantial vertical features get built,+and it is the same mechanism Mercur's own domains use.-- **You own every line** of code in your project.-- **You can modify any block** to fit your business requirements.-- **There are no hidden abstractions** or version conflicts.-- **Updates are explicit.** You diff against the registry and apply the changes you want.+### 4. Custom fields — add data to built-in entities-The CLI (`@mercurjs/cli@latest`) scaffolds projects, installs blocks, searches the-registry, and compares local changes against upstream.+For one plain property on an existing record — `is_featured` on a product,+`tier` on a customer — you declare the field in configuration and the storage,+link, and migration are generated for you.-## Workflow example+```ts medusa-config.ts+{+ resolve: "@mercurjs/core/modules/custom-fields",+ options: {+ customFields: {+ Product: { is_featured: { type: "boolean", nullable: true } },+ },+ },+}+```-Workflows coordinate multi-step operations with automatic rollback on failure.-Here is a simplified example.+One row per parent, no lifecycle of its own; anything more is a module.+[Custom fields →](/resources/best-practices/custom-fields)-```typescript-import {- createWorkflow,- createStep,- StepResponse,- WorkflowResponse,-} from "@medusajs/framework/workflows-sdk"-import { MercurModules } from "@mercurjs/types"+### 5. Panel pages and widgets — change what teams see-const validateSellerStep = createStep(- "validate-seller",- async ({ seller_id }: { seller_id: string }, { container }) => {- const sellerService = container.resolve(MercurModules.SELLER)- const seller = await sellerService.retrieveSeller(seller_id)+The panels are extended by file convention. A file's folder decides what it does,+and there is no manifest to maintain.- if (seller.status !== "open") {- throw new Error("Seller is not active")- }+| Path | Adds |+| ------------------------ | ------------------------------------- |+| `src/routes/**/page.tsx` | A new page and its route |+| `src/widgets/**` | A component in a named zone on a built-in page |+| `src/custom-fields/**` | Form fields, detail rows, and list columns on a built-in model |+| `src/_navigation.ts` | Sidebar order, labels, and visibility |- return new StepResponse(seller)- }-)+A widget targets a slot on an existing page, which is how you put a payout+summary on the order detail screen without owning that screen:-const createProductForSellerWorkflow = createWorkflow(- "create-product-for-seller",- (input: { seller_id: string }) => {- const seller = validateSellerStep({ seller_id: input.seller_id })+```tsx apps/vendor/src/widgets/payout-summary.tsx+export const config = defineWidgetConfig({ zone: "orders.detail.side.after" })+```- // Additional steps: create product, link to seller, and so on.+Zone ids, model names, and field ids are generated per panel into+`extension-targets.d.ts`, so a mistargeted extension fails type-checking instead+of silently not rendering.+[Panel extensions →](/references/panel-extensions/overview)- return new WorkflowResponse({ seller })- }-)+### 6. Blocks — install features as source++Larger features ship as blocks. The CLI copies the source into your project+rather than adding a dependency, so a block is yours from the moment it lands:+readable, debuggable, and modifiable without waiting on an upstream release.+Updates are explicit — `diff` against the registry and take what you want.++```bash+bunx @mercurjs/cli@latest add reviews```-## Design principles+[Blocks →](/learn/blocks)++### Choosing a zone++| You want to… | Use |+| --------------------------------------------------- | ----------------------- |+| Add a rule or side effect to an existing operation | Workflow hook |+| Expose new data or a new operation over HTTP | API route |+| Model something with its own lifecycle | Module and link |+| Store one extra property on a built-in entity | Custom field |+| Show or capture something in the panels | Page, widget, or custom-field UI |+| Adopt a whole feature and own it | Block |++## Governance-These principles explain why the architecture looks the way it does.+Multi-vendor means untrusted writers, so the guarantees operators need are built+into the layers rather than layered on.-- **Enterprise is the noun, composable is the how.** Mercur is a marketplace platform first. Composability, open source, and AI-nativeness are how it becomes a better enterprise choice than a closed platform, not a step down from one.-- **Modular over monolithic.** Each marketplace feature is a separate module you can install, modify, or replace on its own. You do not need all of Mercur to benefit from it.-- **Explicit over implicit.** Relationships are declared through links, not buried in service code. Workflows make multi-step operations visible and debuggable. API routes are file-based and predictable.-- **Extensible over configurable.** Instead of hundreds of config flags, Mercur gives you extension points. Workflows have hooks, providers are pluggable, and models extend through Medusa. When configuration is not enough, you change the source you own.-- **Commerce-aware.** Mercur does not reinvent commerce. It delegates products, pricing, orders, payments, and fulfillment to Medusa and focuses on the marketplace logic that multi-vendor systems need.+- **Scoping before handling.** Vendor requests are narrowed to the caller's seller in middleware, ahead of any handler. A route cannot accidentally leak across sellers, including a route you add.+- **An immutable change pipeline.** Product edits are recorded as `ProductChange` entries — who changed what, who approved it, when. Low-risk edits auto-confirm; the rest queue for review. The audit trail is the mechanism, not a log written beside it.+- **Exact money.** Commission and payout arithmetic uses arbitrary-precision numbers throughout, so splitting a payment across sellers stays exact.+- **Agents inside the same guardrails.** The typed client, exposed workflows, `llms.txt`, and the MCP server give AI agents structured contracts — subject to the same roles and the same review pipeline as human users.++## How a multi-vendor order flows++One cart, several sellers. This is the path that touches every layer.++1. The customer adds items from multiple sellers to a single cart (Store API).+2. Cart completion starts the split-order workflow.+3. Items are grouped by seller and an order is created per seller, all under one order group.+4. Commission lines are computed per order from the matching rules.+5. Payment is allocated proportionally across the seller orders.+6. Each seller's share is credited to its payout account, net of commission.+7. Events fire: notifications, webhooks, indexing, and any hook you registered.+8. Sellers fulfill their own orders in the vendor portal; the operator sees all of it in the admin panel.++Steps 2 through 6 are a single workflow. If any of it fails, none of it happened.++## Stack++| Concern | Technology |+| ------------------ | -------------------------------------------- |+| Runtime | Node.js 20+, TypeScript |+| Commerce engine | Medusa v2 |+| Database | PostgreSQL |+| Events, cache | Redis (in-memory fallback in development) |+| Panels | React 18, Vite, Medusa UI, TanStack Query |+| Validation, forms | Zod, React Hook Form |+| Build | Turborepo, Bun, tsup |++Mercur's own code is distributed as `@mercurjs/core`, a Medusa plugin registered+by `withMercur()` in your `medusa-config.ts`. That packaging matters when you+upgrade; it does not change any of the above.## Next steps@@ -288,13 +338,13 @@ These principles explain why the architecture looks the way it does.<Card title="Platform modules" href="/platform/store/overview">Data models, workflows, and events for each marketplace domain.</Card>- <Card title="Blocks" href="/learn/blocks">- How features ship as source code you own, not an opaque dependency.+ <Card title="Panel extensions" href="/references/panel-extensions/overview">+ Pages, widgets, custom fields, and navigation.+ </Card>+ <Card title="Extend a workflow" href="/resources/customization/extend-a-workflow">+ Inject a step into an existing flow through a hook.</Card><Card title="API reference" href="/references/api/conventions">- Authentication, seller scoping, and the Admin, Vendor, and Store APIs.- </Card>- <Card title="Panel extensions" href="/references/panel-extensions/overview">- Extend the admin and vendor panels without forking them.+ Authentication, seller scoping, and the three API surfaces.</Card></CardGroup>