cartLinesAdd Mutation Returns Different Cart ID When Adding Products.

Topic summary

A developer is encountering an unexpected behavior with Shopify’s Storefront API cartLinesAdd mutation in a NextJS application.

The Problem:

  • When adding products to an existing cart (using a cart ID stored in localStorage), the mutation returns a different cart ID than expected
  • The workflow: if no cart ID exists, createCart() is called and the ID is saved to localStorage; if a cart ID exists, addToCart() should use that ID to add products
  • Console logging reveals the returned cart ID doesn’t match the one in localStorage

Code Structure:

  • Uses Apollo Client mutations (CREATE_CART_MUTATION and ADD_TO_CART_MUTATION)
  • Implements error handling with Result types (Ok/Err pattern)
  • The code snippets show GraphQL mutation definitions and the cart handling logic

Current Status:

  • The issue remains unresolved
  • A second user confirmed experiencing the same problem
  • No solutions or explanations have been provided yet
  • The developer is seeking guidance on how to properly add products using the existing localStorage cart ID
Summarized with AI on November 5. AI used: claude-sonnet-4-5-20250929.

I am implementing a feature using NextJS and the Shopify Storefront API, specifically working with cart mutations.

In src/hooks/cart/useAddCart.ts, I have defined hooks for adding products to the cart.

If there is no cart ID, I execute createCart() and add the cart ID to local storage.

If a cart ID exists in local storage, my intention is to use it to add products with addToCart().

However, when I checked console.log(addToCartResponse.data.cartLinesAdd.cart.id),

I found that the ID returned was not the cart ID existing in local storage, as shown below.

Please advise on how to add products to the cart using the cart ID that exists in local storage.

(src/hooks/cart/useAddCart.ts)

import { useMutation } from '@apollo/client'
import {
  CREATE_CART_MUTATION,
  ADD_TO_CART_MUTATION,
} from '@/graphql/mutations/cart'
import { Result, Ok, Err } from 'oxide.ts'
import { CartError, CartErrorEnum } from '@/const/cart'

export const useAddCart = (productVariantId: string) => {
  const [createCart] = useMutation(CREATE_CART_MUTATION)
  const [addToCart] = useMutation(ADD_TO_CART_MUTATION)

  const handleAddToCart = async (
    quantity: number,
  ): Promise<Result<undefined, CartError>> => {
    let cartId = localStorage.getItem('cartId') ?? ''

    if (!cartId) {
      try {
        const response = await createCart()
        if (response.data && response.data.cartCreate) {
          cartId = response.data.cartCreate.cart.id
          localStorage.setItem('cartId', cartId)
        }
      } catch (error) {
        return Err(CartErrorEnum.addToCartFailure)
      }
    }

    try {
      const lines = [
        {
          quantity: quantity,
          merchandiseId: productVariantId,
        },
      ]
      console.log(cartId)
      // cartId: gid://shopify/Cart/c1-011f596002781b30443f9e29b449e52d

      const addToCartResponse = await addToCart({
        variables: { cartId, lines },
      })

      console.log(addToCartResponse.data.cartLinesAdd.cart.id) // gid://shopify/Cart/c1-fc44819d7ce6c6cfd8cd292b253a629d

      if (addToCartResponse.data && addToCartResponse.data.cartLinesAdd) {
        return Ok(undefined)
      }
    } catch (error) {
      console.error('failed error', error)
      return Err(CartErrorEnum.addProductFailure)
    }
    return Err(CartErrorEnum.unknownError)
  }

  return { handleAddToCart }
}

(src/graphql/mutations/cart.ts)

import { gql } from '@apollo/client'

export const CREATE_CART_MUTATION = gql`
  mutation {
    cartCreate(
      input: {
        lines: [
          {
            quantity: 2
            merchandiseId: "gid://shopify/ProductVariant/45756804596016"
          }
        ]
        attributes: { key: "cart_attribute", value: "This is a cart attribute" }
      }
    ) {
      cart {
        id
        createdAt
        updatedAt
        lines(first: 10) {
          edges {
            node {
              id
              merchandise {
                ... on ProductVariant {
                  id
                }
              }
            }
          }
        }
      }
    }
  }
`

export const ADD_TO_CART_MUTATION = gql`
  mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
    cartLinesAdd(cartId: $cartId, lines: $lines) {
      cart {
        id
        lines(first: 10) {
          edges {
            node {
              id
              merchandise {
                ... on ProductVariant {
                  id
                }
              }
            }
          }
        }
      }
    }
  }
`

Hey there. I am also experiencing this issue. Any updates on solutions @y_metro ?