Add to your cart
Let the widget add products to the storefront cart instead of linking out.
Without a cart bridge the widget runs in link-out mode: product cards link to the product page and the shopper buys through your normal checkout. That is the default, and it works everywhere.
Give the widget a bridge and product cards gain an Add to cart button.
The bridge
import ShopAssist from "@shopassist/js";
ShopAssist({
shopDomain: "your-shop.com",
cart: {
async add(variantId, quantity, properties) {
await myStorefront.addToCart(variantId, quantity, properties);
},
open() {
myStorefront.openCartDrawer();
},
},
});| Field | Required | What it does |
|---|---|---|
add | Yes | Adds a variant to your cart. May return a promise, which the widget waits for. |
open | No | Called after a successful add, to open your cart drawer. |
The widget decides between link-out and add-to-cart by whether add is a
function, so a bridge that is present but broken is worse than no bridge.
Attribution properties
properties is:
{ _attribution: "shopassist", _session_id: "<session id>" }Attach it as line-item properties or cart attributes. Ignore it and add-to-cart still works, but the resulting order is not linked to ShopAssist. See attribution.
Errors
If add throws or rejects, the widget shows the error to the shopper. Reject with
a message a shopper can act on:
async add(variantId, quantity, properties) {
const res = await fetch("/api/cart", {
method: "POST",
body: JSON.stringify({ variantId, quantity, properties }),
});
if (!res.ok) throw new Error("That size just sold out.");
}Changing the bridge later
If your cart code is only available after some setup, install the bridge when it is ready:
import { setCart } from "@shopassist/js";
setCart({ add: myStorefront.addToCart });The change applies to the next add.
In React
Pass the bridge in the provider's configuration. The provider compares configuration by value and ignores the bridge in that comparison, so a new function identity on each render does not reload the widget.
<ShopAssistProvider
config={{
shopDomain: "your-shop.com",
cart: { add: addToCart },
}}
>For Hydrogen, see the Hydrogen page, which has a worked example against Hydrogen's cart.
Last updated on