---
description: "Learn how to implement a create swap flow in a storefront."
addHowToData: true
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# How to Create a Swap in the Storefront

In this document, you’ll learn how to implement a create swap flow in a storefront.

## Overview

Swaps allow customers to exchange items they ordered with new ones. This can be helpful if the customer ordered and received an item they didn’t like, if they ordered an incorrect size, or something similar.

The Medusa backend allows automating the process of exchanging an item with another by providing the necessary mechanism that allows customers to create the swap request themselves. This guide illustrates how you can implement that mechanism in your storefront.

The process of creating a swap is as follows:

- Ask the customer to select the items they want to replace, and which items they want to replace them with. You can also allow customers to select the return shipping option to use to return the item.
- Create the swap in the Medusa backend.
- Show a checkout flow using the swap’s cart. This allows the customer to provide their shipping details and authorize payment in a flow similar to that of placing an order.

---

## Prerequisites

### Medusa Components

It's assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.

It's also assumed you already have a storefront set up. It can be a custom storefront or one of Medusa’s storefronts. If you don’t have a storefront set up, you can install the [Next.js Starter Template](../../../starters/nextjs-medusa-starter.mdx).

### JS Client

This guide includes code snippets to send requests to your Medusa backend using Medusa’s JS Client and JavaScript’s Fetch API.

If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).

### Medusa React

This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.

If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.mdx) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.mdx#usage).

---

## Step 1: Collecting Swap Details

When a customer wants to create a swap, they must choose the items they want to return or replace and the items they want to receive instead.

To display the items in the order, you can retrieve the order as explained in [this guide](./retrieve-order-details.mdx). You can then display the items in an order using `order.items`, which is an array of items.

To allow the customers to choose other items to replace the items from the order, you can show them the available products in your store to choose from them. You can learn how to retrieve products in your storefront using [this guide](../../products/storefront/show-products.mdx).

You can optionally allow customers to choose a return shipping option that they’ll use to return the items. You can learn how to retrieve return shipping options in [this guide](./create-return.mdx#showing-return-shipping-options).

---

## Step 2: Create the Swap

After collecting the swap details in step 1, you can create a swap in the Medusa backend by sending a request to the [Create Swap endpoint](https://docs.medusajs.com/api/store#swaps_postswaps):

<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>

```ts
medusa.swaps.create({
  order_id,
  return_items: [
    {
      item_id,
      quantity: 1,
    },
  ],
  additional_items: [
    {
      variant_id,
      quantity: 1,
    },
  ],
  return_shipping_option,
})
.then(({ swap }) => {
  console.log(swap.id)
})
```

</TabItem>
<TabItem value="medusa-react" label="Medusa React">

```tsx
import { useCreateSwap } from "medusa-react"

const CreateSwap = () => {
  const createSwap = useCreateSwap()
  // ...

  const handleCreate = () => {
    createSwap.mutate({
      order_id,
      return_items: [
        {
          item_id,
          quantity: 1,
        },
      ],
      additional_items: [
        {
          variant_id,
          quantity: 1,
        },
      ],
      return_shipping_option,
    })
  }

  // ...
}

export default CreateSwap
```

</TabItem>
<TabItem value="fetch" label="Fetch API">

```ts
fetch(`<BACKEND_URL>/store/swaps`, {
  credentials: "include",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    order_id,
    return_items: [
      {
        item_id,
        quantity: 1,
      },
    ],
    additional_items: [
      {
        variant_id,
        quantity: 1,
      },
    ],
    return_shipping_option,
  }),
})
.then((response) => response.json())
.then(({ swap }) => {
  console.log(swap.id)
})
```

</TabItem>
</Tabs>

This endpoint requires the following request body parameters:

- `order_id`: a string indicating the ID of the order that this swap is created for.
- `return_items`: an array of objects, each object being the item to return. Each object should have the following properties:
    - `item_id`: a string indicating the ID of the item in the order.
    - `quantity`: a number indicating the quantity to return.
- `additional_items`: an array of objects, each object being the new item to receive. Each object should have the following properties:
    - `variant_id`: a string indicating the ID of the product variant.
    - `quantity`: a number indicating the quantity to add.

You can optionally pass the `return_shipping_option` body parameter, which is a string indicating the ID of the shipping option.

The request returns the swap as an object.

---

## Step 3: Complete Swap with Checkout Flow

The swap can be completed in the same flow as a checkout flow. Since a swap is associated with a cart, you can implement the checkout flow using the cart of the swap. You can access the cart of a swap in the swap object using `swap.cart`.

Since the Medusa backend knows the cart is associated with the swap, it will ensure that the flow is performed in the context of a swap. You can learn how to implement a checkout flow in your storefront using [this guide](../../carts-and-checkout/storefront/implement-checkout-flow.mdx).

:::note

When you complete the cart, the returned `type` field can be used to indicate the context of the checkout flow. In the case of a swap, the value of `type` will be `swap`.

:::

### Retrieve Swap by Cart ID

During your checkout flow, you might need to retrieve the swap using the cart’s ID. For example, if you want to display the swap’s details after the cart is successfully completed. You can do that using the [Get by Cart ID endpoint](https://docs.medusajs.com/api/store#swaps_getswapsswapcartid):

<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>

```ts
medusa.swaps.retrieveByCartId(cartId)
.then(({ swap }) => {
  console.log(swap.id)
})
```

</TabItem>
<TabItem value="medusa-react" label="Medusa React">

```tsx
import { useCartSwap } from "medusa-react"

const Swap = () => {
  const { 
    swap, 
    isLoading, 
  } = useCartSwap(cartId)
 
  return (
    <div>
      {isLoading && <span>Loading...</span>}
      {swap && <span>{swap.id}</span>}
      
    </div>
  )
}

export default Swap
```

</TabItem>
<TabItem value="fetch" label="Fetch API">

```ts
fetch(`<BACKEND_URL>/store/swaps/${cartId}`, {
  credentials: "include",
})
.then((response) => response.json())
.then(({ swap }) => {
  console.log(swap.id)
})
```

</TabItem>
</Tabs>

This endpoint requires the ID of the cart as a path parameter.

The request returns the swap as an object.

---

## See Also

- [How to implement a create return flow in a storefront](./create-return.mdx)
- [How to retrieve order details in a storefront](./retrieve-order-details.mdx)
