When trying to add products to cart page using the /cart/add
API from theme app extension, the products are getting added to cart for single product or variants of same product.
When comes to variants of different products, say variant V1 of product A and variant V2 of product B need to be added to cart, it is throwing error 422 Cannot find variant
.
Code I have written:
const items = [{
id: formData.get('id'),
quantity: parseInt(formData.get('quantity') || 1)
}];
// Add each gift product with free gift properties
giftProducts.forEach(gift => {
// Extract numeric variant ID from Shopify GID
const variantId = gift.giftProductVariantId.split('/ProductVariant/')[1];
// Add gift product with proper properties
items.push({
id: variantId,
quantity: 1,
properties: {
'_is_free_gift': 'true',
}
});
});
console.log("Adding to cart:", JSON.stringify(items, null, 2));
// Single request to add all items
const response = await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ items })
});
const result = await response.json();
if (!response.ok) {
console.error("Cart addition failed:", result);
throw new Error(`Cart addition failed: ${result.description}`);
}
Browser log:
Adding to cart: [
{
“id”: “49484105187640”,
“quantity”: 1
},
{
“id”: “49373657530680”,
“quantity”: 1,
“properties”: {
“_is_free_gift”: “true”
}
},
{
“id”: “49373657497912”,
“quantity”: 1,
“properties”: {
“_is_free_gift”: “true”
}
}
]
So as per the syntax of input, I’m passing the input correctly. This same code is used when adding single product, multiple variants of same product and different variants of different products.
In the last case alone, which is “Adding multiple variants of different products” is not working i.e., products are not added to cart.
What is the actual issue causing the products to not getting added to cart??
Did anyone face this??
@Liam-Shopify Hope you can provide some inputs…