Manage Cart's Items in Storefront

In this guide, you'll learn how to manage a cart's line items, including adding, updating, and removing them.

Add Product Variant to Cart#

To add a product variant to a cart, use the Add Line Item API route.

Tip: To retrieve a variant's available quantity and check if it's in stock, refer to the Retrieve Product Variant's Inventory guide.

For example:

Tip: Learn how to install and configure the JS SDK in the JS SDK documentation.
Code
1const addToCart = (variant_id: string) => {2  const cartId = localStorage.getItem("cart_id")3
4  if (!cartId) {5    return6  }7
8  sdk.store.cart.createLineItem(cartId, {9    variant_id,10    quantity: 1,11  })12  .then(({ cart }) => {13    // use cart14    console.log(cart)15    alert("Product added to cart")16  })17}

The Add Line Item API route requires two request body parameters:

  • variant_id: The ID of the product variant to add to the cart. This is the variant selected by the customer.
  • quantity: The quantity to add to cart.

The API route returns the updated cart object.


Update Line Item in Cart#

You can update the quantity of a line item in the cart using the Update Line Item API route.

For example:

Code
1const updateQuantity = (2  itemId: string,3  quantity: number4) => {5  const cartId = localStorage.getItem("cart_id")6
7  if (!cartId) {8    return9  }10
11  sdk.store.cart.updateLineItem(cartId, itemId, {12    quantity,13  })14  .then(({ cart }) => {15    // use cart16    console.log(cart)17  })18}

The Update Line Item API route requires:

  • The line item's ID to be passed as a path parameter.
  • The quantity request body parameter, which is the new quantity of the item.

The API route returns the updated cart object.


Remove Line Item from Cart#

To remove a line item from the cart, send a request to the Remove Line Item API route.

For example:

Code
1const removeItem = (itemId: string) => {2  const cartId = localStorage.getItem("cart_id")3
4  if (!cartId) {5    return6  }7
8  sdk.store.cart.deleteLineItem(cartId, itemId)9  .then(({ parent: cart }) => {10    // use cart11    console.log(cart)12  })13}

The Delete Line Item API route returns the updated cart object as the parent field.

Was this page helpful?
Ask Anything
Ask any questions about Medusa. Get help with your development.
You can also use the Medusa MCP server in Cursor, VSCode, etc...
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