Cart Error: Cannot Find Variant

I am trying to add a variant to the cart using ajax api.

const addToCart = async ({
  variantId,
  quantity,
  shop,
}: {
  product: number;
  quantity: number;
  shop: string;
}) => {
  const response = await axios.post(
    "https://" + shop + "/cart/add.js",
    JSON.stringify({
      items: [
        {
          id: variantId
          quantity: quantity,
        },
      ],
    }),
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
  );
};

But I get this error when the function is called
{"status":422,"message":"Cart Error","description":"Cannot find variant"}
When i try to call the addToCart function with a product variant I created from the admin page, it works fine. but when I use graphql api to create the product and variant, and add it to cart, the addToCart function did not work.

Hi Dipesh,

Is the product published on the online store? If not the Ajax API won’t be able to add it to a cart. You can check like this:

query {
  product(id: "gid://shopify/Product/PRODUCT_ID") {
    id
    title
    publishedOnPublication(publicationId: "gid://shopify/Publication/ONLINE_STORE_PUBLICATION_ID")
  }
}

What could be happening here is that when you create a product or variant via the Admin API, it is not automatically published to all sales channels, including the Online Store. So after creating your product and variant, you must publish them to the Online Store channel using the Admin GraphQL API.

Hi @Dipesh_Shrestha1 - can you confirm if the issue was related to not being published on the online store?

Sorry for the late reply.
can i add the product to cart without publishing it to the online store or other sales channels?

If the product is not added to the Online Store channel, the Ajax API can’t add the product to the cart.