- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
Menu
- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
Manage Cart's Items in Storefront
In this document, 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 this guide.
For example:
1const addToCart = (variant_id: string) => {2 const cartId = localStorage.getItem("cart_id")3 4 if (!cartId) {5 return6 }7 8 fetch(`http://localhost:9000/store/carts/${cartId}/line-items`, {9 credentials: "include",10 method: "POST",11 headers: {12 "Content-Type": "application/json",13 "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "temp",14 },15 body: JSON.stringify({16 variant_id,17 quantity: 1,18 }),19 })20 .then((res) => res.json())21 .then(({ cart }) => {22 // use cart23 console.log(cart)24 alert("Product added to cart")25 })26}
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:
1const updateQuantity = (2 itemId: string,3 quantity: number4) => {5 const cartId = localStorage.getItem("cart_id")6 7 if (!cartId) {8 return9 }10 11 fetch(`http://localhost:9000/store/carts/${cartId}/line-items/${12 itemId13 }`, {14 credentials: "include",15 method: "POST",16 headers: {17 "Content-Type": "application/json",18 "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "temp",19 },20 body: JSON.stringify({21 quantity,22 }),23 })24 .then((res) => res.json())25 .then(({ cart }) => {26 // use cart27 console.log(cart)28 })29}
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:
1const removeItem = (itemId: string) => {2 const cartId = localStorage.getItem("cart_id")3 4 if (!cartId) {5 return6 }7 8 fetch(`http://localhost:9000/store/carts/${cartId}/line-items/${9 itemId10 }`, {11 credentials: "include",12 headers: {13 "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "temp",14 },15 method: "DELETE",16 })17 .then((res) => res.json())18 .then(({ parent: cart }) => {19 // use cart20 console.log(cart)21 })22}
The Delete Line Item API route returns the updated cart object as the parent
field.
Was this page helpful?