Manage Cart

Add, update, and remove line items.

On this page

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

On Next.js, these are server actions in src/lib/data/cart.ts. Call getOrSetCart(storeCode, countryCode) so a cart exists, then mutate line items. Read the cart ID from _aiminaabee_cart_id, not localStorage. After each mutation, revalidateTag for carts (and fulfillment when shipping options can change).

ts

tsCopy
"use server"
export async function addToCart({
storeCode,
variantId,
quantity,
countryCode,
}: {
storeCode: string
variantId: string
quantity: number
countryCode: string
}) {
const cart = await getOrSetCart(storeCode, countryCode)
const headers = { ...(await getAuthHeaders()) }
await sdk.store.cart.createLineItem(
storeCode,
cart.id,
{ variant_id: variantId, quantity },
{},
headers
)
revalidateTag(await getCacheTag("carts"))
revalidateTag(await getCacheTag("fulfillment"))
}

See Create Cart and Build a Next.js Storefront.

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 Getting started guide.

ts

tsCopy
const addToCart = (variant_id: string, cartId: string) => {
if (!cartId) {
return
}
sdk.store.cart.createLineItem(storeCode, 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:

ts

tsCopy
const updateQuantity = (
itemId: string,
quantity: number,
cartId: string
) => {
if (!cartId) {
return
}
sdk.store.cart.updateLineItem(storeCode, 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:

ts

tsCopy
const removeItem = (itemId: string, cartId: string) => {
if (!cartId) {
return
}
sdk.store.cart.deleteLineItem(storeCode, 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.