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
const addToCart = (variant_id: string) => {
  const cartId = localStorage.getItem("cart_id")

  if (!cartId) {
    return
  }

  sdk.store.cart.createLineItem(cartId, {
    variant_id,
    quantity: 1,
  })
  .then(({ cart }) => {
    // use cart
    console.log(cart)
    alert("Product added to cart")
  })
}

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
const updateQuantity = (
  itemId: string,
  quantity: number
) => {
  const cartId = localStorage.getItem("cart_id")

  if (!cartId) {
    return
  }

  sdk.store.cart.updateLineItem(cartId, itemId, {
    quantity,
  })
  .then(({ cart }) => {
    // use cart
    console.log(cart)
  })
}

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
const removeItem = (itemId: string) => {
  const cartId = localStorage.getItem("cart_id")

  if (!cartId) {
    return
  }

  sdk.store.cart.deleteLineItem(cartId, itemId)
  .then(({ parent: cart }) => {
    // use cart
    console.log(cart)
  })
}

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

Found a problem with this page?Report Issue
Edited Nov 14·Edit this page