Add to Cart

Adds an item to cart

Description

The addToCart() action adds a specific product or variant to the user’s active shopping cart inside the app.
It works seamlessly with the native Vajro cart and triggers a cartUpdated event once the item is added successfully.
You can use this action from any custom block, PDP extension, or embedded web view to provide a smooth “Add to Cart” experience without reloading the page.

Function Signature

VajroSDK.actions.addToCart([
    {
      variantId: "12345",
      quantity: 1,
      sellingPlanId: "1234234342", // Optional
      attributes: [{ "key":"custom_key","value":"custom_value"}] // Optional
    },
  ])
ParameterTypeRequiredDescription
varinatIdStringYesThe unique ID of the variant of the product
QuantityNumberYesThe number of items of product added to cart
sellingPlanIdStringNoUnique ID incase of subscription enabled
attributesObjectNoCustom Key Value Pairs to pass any additional info about the product

Structure of Response

StatusResponse
Success{ "status": "success", "message": "Line items added to cart" }
Invalid Params{ "status": "error", "errorId": 400, "errorHandle": "invalid-params", "message": "Invalid params" }
Unexpected Error{ "status": "error", "errorId": 500, "errorHandle": "unknown-error", "message": "Something unexpected happened" }

Example Usage

const product_data = VajroSDK.variables.product;
const variant_id= product_data.selectedVariant.id;
const quantity = 1;
const prod_metafield = product_data.metafields["product_height"];
const customAttributes = [
  { key: "product_height", value: prod_metafield },
  { key: "delivery_info", value: "Est. delivery 5 working days" }
];
function addItemToCartWithAttributes(variantId, quantity, customAttributes) {
  VajroSDK.actions.addToCart([
    {
      variantId: variantId,
      quantity: quantity,
      attributes: customAttributes
    }
  ])
    .then(() => {
      console.log("Item added to cart with attributes");
    })
    .catch(err => {
      console.error("Error adding item to cart:", err);
    });
}
function addToCart()
{
addItemToCartWithAttributes(variant_id, quantity, customAttributes);
}


Best Practices

  1. Use variantId when products have multiple options like size or color.
  2. Provide feedback to the user with showToast() or showAlert().
  3. Combine with the cartUpdated listener to refresh cart UI or item counts dynamically.
  4. Validate stock availability before adding to the cart (if using custom logic).

Caveats

  1. If the product requires variant selection, variantId must be specified.
  2. Does not open the cart automatically — use Vajro.actions.openCart() if needed.
  3. Adding out-of-stock items may fail silently; handle this with proper validation.
  4. The cartUpdated event is triggered asynchronously after the update.