Update Cart in Storefront

In this document, you'll learn how to update different details of a cart.

NoteAll cart updates are performed using the Update Cart API route.

Update Cart's Region#

If a customer changes their region, you must update their cart to be associated with that region.

For example:

Code
1fetch(`http://localhost:9000/store/carts/${cartId}`, {2  credentials: "include",3  method: "POST",4  headers: {5    "Content-Type": "application/json",6    headers: {7      "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "temp",8    },9  },10  body: JSON.stringify({11    region_id: "new_id",12  }),13})14.then((res) => res.json())15.then(({ cart }) => {16  // use cart...17  console.log(cart)18})

The Update Cart API route accepts a region_id request body parameter, whose value is the new region to associate with the cart.


Set Cart's Customer#

You might need to change the cart's customer in two cases:

  • You created the cart for the customer as a guest, then they logged-in, so you want to associate the cart with them as a registered customer.
  • You're transfering the cart from one customer to another, which is useful in company setups, such as when implementing B2B commerce applicatons.

To set or change the cart's customer, send an authenticated POST request to the Set Cart's Customer API route:

NoteThis API route is only available after Medusa v2.0.5.
Code
1fetch(`http://localhost:9000/store/carts/${cartId}/customer`, {2  credentials: "include",3  method: "POST",4  headers: {5    "Content-Type": "application/json",6    "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "temp",7  },8})9.then((res) => res.json())10.then(({ cart }) => {11  // use cart...12  console.log(cart)13})

To send an authenticated request, either use credentials: include if the customer is already authenticated with a cookie session, or pass the Authorization Bearer token in the request's header.

TipLearn more about authenticating customers in this guide.

The cart is now associated with the logged-in customer.

Was this page helpful?
Edit this page
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break