JavaScript SDK API

The JS API allows you to retrieve relevant information about the current Snipcart session and apply certain operations to the cart.

The JS API exposes multiple services:

All async methods return promises and throw an SDKError in case of failure. If you are not familiar with the concept of promises, consider reading this introduction.

Cart

update

The update method updates the current cart's data with the provided payload argument. The payload is an object of type UpdateCartPayload.

Updates can be partial, i.e. they can contain only a subset of the fields defined in the UpdateCartPayload interface.

You can also update cart metadata with this method.

It's important to note that it's not currently possible to partially update the billing and shipping addresses, all required properties must be provided.

try {
    await Snipcart.api.cart.update({
        email: 'john.doe@example.com',
        metadata: {
            customMetadataKey: 'value'
        },
        billingAddress:{
            name: 'John Doe',
            address1: '3671 Garfield Road',
            city: 'Neponset',
            country: 'US',
            province: 'IL',
            postalCode: '61345'
        }
    });
} catch (error) {
    console.log(error);
}

applyDiscount

The applyDiscount method applies a discount to the cart. It takes a discount code as an argument and returns a promise of type DiscountAppliedResponse.

try {
    await Snipcart.api.cart.applyDiscount('{discountCode}');
} catch (error) {
    console.log(error);
}

removeDiscount

The removeDiscount method removes a discount from the cart. It takes the discount code as an argument and returns a promise of type DiscountRemovedResponse.

try {
    await Snipcart.api.cart.removeDiscount('{discountCode}');
} catch (error) {
    console.log(error);
}

fetchShippingRates

The fetchShippingRates method retrieves a list of available shipping rates for the cart and returns a promise of type ShippingRatesResponse.

try {
    const response = await Snipcart.api.cart.fetchShippingRates();
} catch (error) {
    console.log(error);
}

setShippingInformation

The setShippingInformation method provides the shipping information for the cart. It takes an argument of type ShippingInformation and returns a promise.

try {
    await Snipcart.api.cart.setShippingInformation({
        method: '{shippingMethod}',
        cost: 0,
    });
} catch (error) {
    console.log(error)
}

Items

add

The add method adds an item to the cart. It can take a ProductDefinition or multiple ProductDefinition separated by a comma as an argument and returns a promise of type CartItemAddedResponse.

try {
    await Snipcart.api.cart.items.add({
        id: 'PRODUCT_ID',
        name: 'Product 1',
        price: 1.11,
        url: '/',
        quantity: 1,
    },{
        id: 'PRODUCT2_ID',
        name: 'Product 2',
        price: 1.11,
        url: '/',
        quantity: 1,
    });
} catch (error) {
    console.log(error)
}

If you use alternate price discounts, you'll need to define these prices when adding item via our JavaScript SDK, this can be done via a property named alternatePrices. Let's say you have an alternate price list discount named: vip:

try {
    await Snipcart.api.cart.items.add({
        id: 'PRODUCT_ID',
        name: 'Product 1',
        price: 20.00,
        alternatePrices: {
            vip: 10.00
        },
        url: '/',
        quantity: 1,
    });
} catch (error) {
    console.log(error)
}

remove

The remove method removes an item from the cart. It takes the item's unique ID as a parameter and returns a promise of type CartItemRemovedResponse.

try {
    await Snipcart.api.cart.items.remove('{itemUniqueId}');
} catch (error) {
    console.log(error)
}

update

The update method updates an item in the cart. It takes an argument of type CartItem and returns a promise of type CartItemUpdatedResponse.

Please note that to update an item, the parameter uniqueId is required, this is how we'll find which product needs to be updated. The uniqueId is a guid generated on our site when an item is added to a cart.

try {
    await Snipcart.api.cart.items.update({
      uniqueId: '70f3899b-9f2b-47fa-9eb5-648f2c2ae216',
      name: 'Updated name'
    });
} catch (error) {
    console.log(error)
}

Customer

fetchOrders

The fetchOrders method retrieves a customer's order. It takes the order's token as a parameter and returns a promise of type CartResponse.

try {
    const response = await Snipcart.api.customer.fetchOrders('{orderToken}');
} catch (error) {
    console.log(error)
}

signout

The signout method will sign out the currently signed-in customer. It returns a promise of type void.

try {
    await Snipcart.api.customer.signout();
} catch (error) {
    console.log(error)
}

Theme

cart.open

The cart.open method opens the cart.

Snipcart.api.theme.cart.open()

customization.registerPaymentFormCustomization

To customize the payment form, you can use the customization.registerPaymentFormCustomization method.

  • This has to be done before the payment form is loaded.
Snipcart.api.theme.customization.registerPaymentFormCustomization({
  input: {
    backgroundColor: 'red',
    color: '#303030',
    border: '1px solid black',
    fontSize: '16px',
    placeholder: {
      color: 'blue',
    },
  },
  label: {
    color: '#fff',
    fontSize: '20px',
  }
});

cart.close

The cart.close method closes the cart.

Snipcart.api.theme.cart.close()

Withdrawal

validate

Validates a withdrawal request against an existing order without persisting anything. Use this when you want to surface validation errors before showing the customer a confirmation step.

Signature

validate(request: WithdrawalValidateRequest): Promise

Request

Field Type Required Description
orderInvoiceNumber string yes The customer-facing invoice number.
email string yes The email used at checkout (must match exactly).
customerName string no The customer's full name. Optional at validate time.

Response — success

{
    valid: true,
    orderInvoiceNumber: string,
    orderDate: string,            // ISO 8601
    orderTotal: number,
    currency: string,             // 3-letter code
    withdrawalDeadline: string,   // ISO 8601 — 14 days after orderDate
    isOutsideWithdrawalPeriod: boolean,
    items: [
        {
            uniqueId: string,
            name: string,
            quantity: number,
            unitPrice: number,
            totalPrice: number,
        },
        // ...
    ]
}

Response — failure

{ valid: false }

For security reasons, the failure response contains no error details — Snipcart deliberately does not differentiate between "order not found", "wrong email", "already withdrawn", and other rejection reasons over the wire. The specific cause is logged server-side for support diagnostics. Render your own user-facing error string when valid is false.

confirm

Submits a previously validated withdrawal request. On success, the customer's confirmation email is queued and the merchant is notified.

Signature

confirm(request: WithdrawalConfirmRequest): Promise

Request

Field Type Required Description
orderInvoiceNumber string yes The customer-facing invoice number.
email string yes The customer's email.
customerName string yes Required at confirm time (the EU "unequivocal statement").
withdrawAll boolean yes true for full-order withdrawal; false to use items[] for a partial withdrawal.
items array only when withdrawAll === false The items to withdraw — see below.

items[] element

Field Type Description
itemUniqueId string (GUID) Matches the uniqueId returned by validate().
quantity number Quantity to withdraw.

Response — success

{
    success: true,
    withdrawalId: string,         // GUID
    confirmationNumber: string,   // WD-YYYYMMDD-XXXXXXXX
    submittedAt: string,          // ISO 8601
}

Response — failure

{ success: false }

Same convention as validate(): a failure carries no error details over the wire.

openConfirmation

Validates the request server-side, then opens the cart on the withdrawal confirmation step (item selection / final confirm). On validation failure, opens the cart on the withdrawal form with the error pre-populated. The customer never sees the form on the success path — they land directly on the confirmation step.

Signature

openConfirmation(request: WithdrawalValidateRequest): Promise

Takes the same request shape as validate(). Returns a Promise<void> that resolves once the validation completes and the navigation event is published — actual route navigation happens inside the cart widget listening for the event.

Intended use case: merchant overrides on the customer dashboard, where the customer is already signed in and re-typing the order number / email / name is unnecessary. See Customizing the customer dashboard for the full pattern.

You don't need to handle the validation outcome yourself — the cart widget shows either the confirmation step (success) or the form with an error (failure) automatically.

Was this article helpful?