Converting SKU to Variant ID before doing cart.push

We have built a JS config file that is a collection of items that make up a completed product. This file is included into the AddItem JS file. Each item has to have Variant ID, but since we have multiple sites, that Variant ID changes from site to site. I want to use SKU to simplify across all sites when building the JS config file.

Is there a way to convert SKU to Product ID just before submitting the cart.push command in the AddItem JS file?

I was thinking that we could query a collection and get the Variant ID based on the SKU. Then assign the Variant ID in the cart.push instead of the SKU.

Any thoughts on this?

Hi,

Hope this will help

-Add JavaScript function to get Variant ID using SKU

Code example

async function getVariantIdBySKU(sku) {
  const response = await fetch('/products.json');
  const data = await response.json();

  for (const product of data.products) {
    for (const variant of product.variants) {
      if (variant.sku === sku) {
        return variant.id;
      }
    }
  }

  return null; // Not found
}

-Update your cart.push logic