Trouble with Adding a Product to Cart using Shopify GraphQL API

Hello, Shopify developers! I’m struggling with an issue related to the Shopify GraphQL API, specifically when trying to add a product variant to a cart. I was hoping someone here might have encountered a similar issue and could offer some guidance.

The Task:
I’m trying to create a shopping cart and then add a specific product variant to it.

The Code:
Here’s the function I’ve written to handle this:

const axios = require('axios');
const shopifyDomain = 'your-shopify-domain';
const storefrontAccessToken = 'your-access-token';

const createCartAndAddProduct = async () => {
try {
// Step 1: Create the cart
const createCartResponse = await axios.post(
`https://${shopifyDomain}/api/2023-10/graphql.json`,
{
query: `
mutation {
cartCreate(input: {}) {
cart {
id
}
userErrors {
field
message
}
}
}
`,
},
{
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': storefrontAccessToken,
},
}
);

const { cart, userErrors } = createCartResponse.data.data.cartCreate;

if (userErrors && userErrors.length > 0) {
console.error("User Errors (Cart Creation):", userErrors);
return;
}

console.log("Cart created:", cart.id);

// Step 2: Add the product to the cart
const productId = "gid://shopify/ProductVariant/44707067461897";
const addToCartResponse = await axios.post(
`https://${shopifyDomain}/api/2023-10/graphql.json`,
{
query: `
mutation AddToCart($cartId: ID!, $variantId: ID!) {
cartLinesAdd(cartId: $cartId, lines: [{ quantity: 1, merchandiseId: $variantId}]) {
cart {
lines(first: 100) {
edges {
node {
id
quantity
merchandise {
... on ProductVariant {
product {
title
}
}
}
}
}
}
}
userErrors {
field
message
}
}
}
`,
variables: {
cartId: cart.id,
variantId: productId
}
},
{
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': storefrontAccessToken,
},
}
);

const { cart: updatedCart, userErrors: addToCartErrors } = addToCartResponse.data.data.cartLinesAdd;

if (addToCartErrors && addToCartErrors.length > 0) {
console.error("User Errors (Add To Cart):", addToCartErrors);
return;
}

console.log("Product added to cart:", updatedCart.lines.edges);
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
};

createCartAndAddProduct();

The Problem:
I’ve recently added a new product to my Shopify store, and here is the response I got:

{
"product": {
"id": 8338361549065,
"title": "tester",
// Other product details
"variants": [
{
"id": 44707067461897,
"title": "Default Title",
// Other variant details
}
],
// Other product details
}
}

However, when I run the createCartAndAddProduct function, I get the following error:

User Errors (Add To Cart): [
{
"field": ["lines", "0", "merchandiseId"],
"message": "The merchandise with id gid://shopify/ProductVariant/44707067461897 does not exist."
}
]

I’ve double-checked the product variant ID, and it matches exactly with what’s in the Shopify response. I’m not sure what’s going wrong here.

The Question
Has anyone encountered a similar issue or can spot what I might be doing wrong? Any help or suggestions would be greatly appreciated!

Thank you in advance for your time and help! :folded_hands:

full script:

const axios = require('axios');

const shopifyDomain = '4aeb95-2.myshopify.com';
const storefrontAccessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';

const createCartAndAddProduct = async () => {
    try {
        // Step 1: Create the cart
        const createCartResponse = await axios.post(
            `https://${shopifyDomain}/api/2023-10/graphql.json`,
            {
                query: `
                    mutation {
                        cartCreate(input: {}) {
                            cart {
                                id
                            }
                            userErrors {
                                field
                                message
                            }
                        }
                    }
                `
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Shopify-Storefront-Access-Token': storefrontAccessToken,
                },
            }
        );

        const { cart, userErrors } = createCartResponse.data.data.cartCreate;

        if (userErrors && userErrors.length > 0) {
            console.error("User Errors (Cart Creation):", userErrors);
            return;
        }

        console.log("Cart created:", cart.id);

        // Step 2: Add the product to the cart
        const productId = "gid://shopify/ProductVariant/44707067461897";
        const addToCartResponse = await axios.post(
            `https://${shopifyDomain}/api/2023-10/graphql.json`,
            {
                query: `
                    mutation AddToCart($cartId: ID!, $variantId: ID!) {
                        cartLinesAdd(cartId: $cartId, lines: [{ quantity: 1, merchandiseId: $variantId}]) {
                            cart {
                                lines(first: 100) {
                                    edges {
                                        node {
                                            id
                                            quantity
                                            merchandise {
                                                ... on ProductVariant {
                                                    product {
                                                        title
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            userErrors {
                                field
                                message
                            }
                        }
                    }
                `,
                variables: {
                    cartId: cart.id,
                    variantId: productId
                }
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Shopify-Storefront-Access-Token': storefrontAccessToken,
                },
            }
        );

        const { cart: updatedCart, userErrors: addToCartErrors } = addToCartResponse.data.data.cartLinesAdd;

        if (addToCartErrors && addToCartErrors.length > 0) {
            console.error("User Errors (Add To Cart):", addToCartErrors);
            return;
        }

        console.log("Product added to cart:", updatedCart.lines.edges);
    } catch (error) {
        console.error('Error:', error.response ? error.response.data : error.message);
    }
};

createCartAndAddProduct();

message: ‘The merchandise with id gid://shopify/ProductVariant/44707067461897 does not exist.’

I’m facing the same issue. Can we get someone from Shopify to help out in this regard?

Hi @dyon42

I came across the same problem and later found that storefront API related to cart and checkout would need the products (item whose variant ID is used in the query) to be assigned to the sales channel (basically created with the same name as your private or public app) else it does not recognize the merchandise ID. It does not make sense to me but it was probably intended for headless solutions only.

1 Like

This was exactly what my problem was – thank you for your contribution.