How to build self-service exchanges with Commerce Layer.
Customers pick another size or another product and see the price difference up front. Customer care approves with one click, and the new item ships right away. A five-step recipe built on SKUs, returns, webhooks, order copies, adjustments and promotions.
An exchange is a request every fashion brand knows, and one of the easiest to get wrong. The jacket fits well but runs a size small, or the colour looked different on screen. The customer doesn't want a refund. They want the right item, quickly, without paying twice or waiting for a refund to clear.
In this article we show how we built that experience into a fork of My Account, Commerce Layer's open-source customer area, on top of the open-source Commerce Layer Demo Store.
Every part of it is built from Commerce Layer resources that already exist: SKUs, returns, webhooks, order copies, adjustments and promotions. Each is a flexible primitive, so the business rules live where you want them, and most of the effort goes into what the customer sees.
By the end you'll have a five-step recipe you can adapt to your own catalog and your own exchange policy. Keep in mind that what follows is only one way to do it: every brand handles exchanges differently, shaped by its internal policy and by the customer making the request. Commerce Layer gives you the flexibility to build the experience that fits your business, and we're happy to help you design it.
Three roles, as little work as possible.
We started from the experience, not the data model.
Customer · My Account
Picks the new item
Opens a shipped order, chooses Exchange an item, then picks another size or searches for another product. The price difference shows before sending.
Customer care · Dashboard
Approves the return
Sees the request tagged
exchange, with the customer's reason, and approves it like any other return.Commerce Layer + webhook
Ships the new item
Creates the exchange order, charges any extra on the payment method on file, and refunds any difference once the return arrives.
Every part maps to a resource that already exists.
Each part of the experience maps onto a Commerce Layer resource that already does most of the work. Metadata is the glue: it lets us add the meaning of an exchange to standard resources without changing their behaviour.
Building block | Commerce Layer resource | Role in the exchange |
|---|---|---|
Sizes of one product |
| Finds the other sizes of the same style and colour |
Return reasons | Organization config, set in the Dashboard | The reasons customers can choose from |
The request |
| Carries the items, the reason and the chosen replacements |
Request type |
| Tells an exchange apart from a refund return |
The triggers |
| Run your logic when the customer asks, when customer care approves and when the items are back |
The new order |
| Clones customer, market, addresses, shipping and the saved payment method in one call |
Credit for returned items |
| A negative line worth what the customer paid for the returned items |
Free shipping |
| Takes shipping off orders tagged |
Refund of a difference |
| Refunds the gap on the original order once the return is received |
Visibility |
| Makes exchanges easy to filter in the dashboard |
Teach the catalog what a size is.
To offer "the same t-shirt in an L", My Account needs to know which SKUs are sizes of the same item. Two standard SKU fields cover it:
metadata.styleholds the style and colour code shared by every size of that item. Catalogs that keep it inreferencework too: My Account falls back to it.metadata.sizeholds the size label shown to the customer (S,M,36…).Umarks a one-size item, which can still be exchanged for another product.
{
"code": "TSHIRT-LOGO-BLK-M",
"metadata": { "style": "TSHIRT-LOGO-BLK", "size": "M" }
}
A short script adds these fields to an existing catalog: it reads each SKU and patches its metadata, and it's safe to run more than once. That's the whole data model: no new resources and no schema changes.
Offer the right replacements in My Account.
The exchange form is where the experience is won or lost. It should offer only replacements that can ship, and say what the exchange will cost before the customer sends it.
First, My Account decides whether the order can be exchanged at all, using data it already has with the customer token:
- The order has shipped (
fulfillment_statusisin_progressorfulfilled). - It was placed within the return window (30 days in the demo).
- Some quantity is still left to return, once earlier active returns are counted.
- It isn't itself an exchange order, so exchanges don't chain.
- The organization has return reasons set up in the Dashboard. My Account offers only those, read from the organization config. Without any, it tells the customer to contact customer care.

Then, for each item, the customer chooses between two kinds of replacement:
- Another size
The SKUs that share the item's style, sorted the way people expect (XS, S, M, L… or numerically for shoes). - Another product
A search over the catalog by name or code.
// src/utils/returns.ts
// another size: same style, from metadata (or reference)
const siblings = await cl.skus.list({
filters: { metadata_jcont: JSON.stringify({ style: item.styleReference }) },
fields: { skus: ["id", "code", "name", "image_url", "metadata"] },
})
// another product: search by name or code
const skus = await cl.skus.list({
filters: { name_or_code_i_cont: query },
pageSize: 12,
})
With a PIM, the form asks it for the sibling SKU codes, and their localized size labels, and then asks Commerce Layer for price and stock. Product data stays in one place, and commerce data stays in Commerce Layer. The PIM can also add a size-guide link or suggest similar items for another product.
Both lists go through the same two checks:
- A price in the customer's market
The customer token only sees its market's prices, so anything without one is left out. - In stock
Each SKU'sinventoryis checked. Out-of-stock options stay visible but disabled, so the customer understands why a size is missing.
With the price known, each row shows its difference as soon as the customer picks: costs $4.00 more, costs $4.00 less or same price, plus a total for the whole request. No surprises on either side.


Send the exchange request.
When the customer confirms, My Account creates a standard return on the order, straight from the browser with the customer's token. Two pieces of metadata make it an exchange:
- On the return,
metadata.type = "exchange". - On each return line item, the replacement the customer picked.
// src/utils/returns.ts
const ret = await cl.returns.create({
order: cl.orders.relationship(orderId),
metadata: { type: "exchange" },
})
for (const s of selections) {
await cl.return_line_items.create({
quantity: s.quantity,
return_reason: { Customer: s.reason },
metadata: {
replacement_sku_code: s.replacement.code,
replacement_name: s.replacement.name,
replacement_size: s.replacement.size,
original_size: s.replacement.fromSize,
},
return: cl.returns.relationship(ret.id),
line_item: cl.line_items.relationship(s.lineItemId),
})
}
await cl.returns.update({ id: ret.id, _request: true })
The reason is stored the same way the Dashboard stores it, so customer care reads Customer: Too small on the return. The same code serves plain returns too: without type: "exchange" and the replacement metadata, it's a regular refund return. One form, two outcomes.
Turn an approved request into an exchange order.
When customer care approves the return, Commerce Layer fires the returns.approve webhook. A serverless function (about 450 lines, hosted on Vercel in the demo) builds the exchange order. The rule: the returned items are credited at the price the customer paid.
- Copy the original order
Oneorder_copiescall clones the customer, market, addresses, shipping and the payment method saved in the customer's wallet. The copy runs asynchronously, so the function polls it until it'scompleted.
// api/returns-webhook.ts
await cl.post("/order_copies", {
type: "order_copies",
attributes: { place_target_order: false, reuse_wallet: true, cancel_source_order: false },
relationships: { source_order: rel("orders", order.id) },
})
- Swap the items
Delete the copied product line items, add the replacements, and set the original shipping method on the rebuilt shipments. Adding a line item fails for a product with no price in the order's market, so nothing unsellable slips through. - Tag and link it
The order gets theexchangetag and metadata pointing at the original order and the return. The tag comes first for a reason: a free-shipping promotion for orders taggedexchangenow applies. - Credit the returned items
A negative adjustment worth what the customer paid for them, capped at the value of the new items. The function then refreshes the order and checks the total is exactly what's due. If anything is still owed, such as shipping, it stops and hands the exchange to customer care.
// api/returns-webhook.ts
const applied = Math.min(credit, value) // paid for returned items vs. new items
const adj = await cl.post("/adjustments", {
type: "adjustments",
attributes: {
name: `Exchange of order #${orderNumber} (return #${returnNumber})`,
currency_code,
amount_cents: -applied,
},
})
// then attach it to the order as a line item
- Charge any extra, then place and approve
If the new items cost more, the order keeps the payment method copied from the wallet (or gets a new wire transfer when the original was paid that way), and_placeauthorizes the difference._approvereleases the order to fulfilment straight away. - Link the return
The return stores the exchange order's number and the price difference, which My Account shows to the customer.

If the new items cost less, the exchange order is free and the difference is refunded later. Commerce Layer refunds a return only once it's received, so the same function listens to returns.receive and refunds the gap on the original order:
// api/returns-webhook.ts
await cl.patch(`/returns/${returnId}`, {
type: "returns",
id: returnId,
attributes: { _refund: true, _refund_amount_cents: amount },
})
Before any of this, the function checks the webhook signature against the secrets of the organization named in its URL.
Keep everyone in the loop.
A good exchange experience is mostly about knowing what happens next. Two small additions take care of that.
For customer care: tags. The same function also listens to returns.request. As soon as a customer sends an exchange request, the return gets the exchange tag, and so does the exchange order when it's created. The tag sets exchanges apart from plain returns, for filters, reports and integrations. On the return itself, customer care reads the reason each item came back for, the same reasons the customer picked from.

For the customer: a Returns page. My Account lists every return and exchange with its progress: requested, approved, shipped, received. Exchanges also show what each item is being swapped for, the exchange order once it exists, and the money side: $4.00 charged to your payment method on file, or $4.00 will be refunded once your items reach our warehouse, then refunded. All of it is read from the return's metadata, so the frontend needs no extra service.

The order page reflects it too. The original order shows its exchange with the same progress, an item already in an active return can't be requested twice, and a fully exchanged order no longer offers the option.

Make it your own, forking My Account.
The frontend half of this feature lives in My Account, Commerce Layer's open-source customer area. Out of the box it covers order history, order details with parcel tracking, addresses, subscriptions and the customer wallet, in 11 languages.
You can use it in two ways:
- Hosted
Every Commerce Layer organization gets it athttps://<your-slug>.commercelayer.app/my-account, branded with your logo, favicon and primary colour. - Forked
When you need new features, like exchanges, fork the repository and deploy it wherever you like. It's MIT-licensed, so the code is yours to change.
How it works
My Account is a React single-page app built with Vite, TypeScript and Tailwind CSS. It talks to Commerce Layer through the JS SDK and React Components.
Your storefront opens it with the signed-in customer's access token in the URL. In the Demo Store, the account link in the header does exactly that:
https://account.yourbrand.com/?accessToken=<customer-token>&lang=en&returnUrl=<storefront-url>
Every call then runs with that customer's permissions, in the market the token is scoped to. That's why the exchange request needs no backend of its own: the customer is allowed to create returns on their own orders, and only sees prices for their market. Commerce Layer enforces both.
Where things live
Folder | What's in it | What we added for exchanges |
|---|---|---|
| Routes and the pages they load |
|
| One folder per page |
|
| Building blocks of each page |
|
| Data access with the SDK |
|
| One | The labels for the new screens |
| Serverless functions deployed with the app |
|
Keep the fork easy to update
The upstream app keeps improving, and you'll want those updates. A few habits keep merges painless:
- Add, don't rewrite
New behaviour goes in new files. Existing files only get the line that plugs it in: the order page gained a single<OrderReturns />line, the menu a new entry, and the order summary anAdjustmentAmountrow so an exchange order shows its credit. - Configure at build time
A small build script writes the allowed organizations from an environment variable intopublic/config.local.js. One deployment can serve several organizations: the app reads the organization from the customer's token, and the webhook reads it from its own URL (?org=<slug>). - Track upstream
Keep the original repository as a remote and merge it regularly.
git remote add upstream https://github.com/commercelayer/mfe-my-account.git
git fetch upstream && git merge upstream/main
The exchange feature added about 2,000 lines across 18 files. Most of them sit in the five new files the steps above walk through; the existing ones changed by a few lines each.
Small decisions that make it reliable.
Each one is a line or two of code.
Credit at the price paid
The returned items are worth what the customer paid, discounts included. The difference is the new items minus that credit, so promotions on the original order are never lost or paid twice.
Refund only on receipt
A cheaper replacement ships right away, but the money goes back only when the original item is back. That's how Commerce Layer handles return refunds, and it protects the merchant.
Free shipping with a promotion
An adjustment can cancel the items, not the shipping. A free-shipping promotion with the rule
tags_name_in: ["exchange"]covers it, with no code.Idempotent webhook
The function writes
exchange_status: "processing"on the return before it starts. A repeated delivery sees it and stops, so an approval never creates two orders.Failures are recorded, not retried
If a size sells out, shipping isn't free or there's no saved payment method, retrying won't help. The function stores the reason on the return, answers 200, and customer care picks it up. My Account tells the customer that customer care will contact them.
No half-built orders
If anything fails after the copy, the function deletes the draft order, so a broken exchange never reaches the customer.
Where to take it next.
The same building blocks stretch further:
- Return labels
Generate a shipping label when the request is approved and show it on the Returns page. - Policy per market
The 30-day window is a constant in the demo. Return windows and exchange rules can come from market metadata instead. - Store credit
Instead of refunding a cheaper exchange, issue the difference as a gift card the customer can spend later.
Self-service exchanges come down to good data in the catalog, a clear request from the frontend, and a small piece of logic on approval.
Commerce Layer provides the primitives: SKUs with metadata, returns, webhooks, order copies, adjustments and promotions. Your team decides how they come together, and spends its time on the experience customers notice.
Everything here fits in a fork of the open-source My Account app. Our demo runs it on the open-source Demo Store, and the same recipe works with any storefront.