Skip to content

SDK reference

For AI assistants: what to know before writing SparkLayer SDK code
  • What it is: window.spark, added to the storefront by the SparkLayer Core Script (version 4.x). On Shopify the SparkLayer app embed loads it; elsewhere it's <script async src="https://sparkcdn.io/sparkjs/<SITE_ID>/<live|test>"></script> in the theme's <head>. The old cdn.sparklayer.io/spark.latest.js and spark.1.x.js files are legacy: never use them.
  • Options: Configure it with window.sparkOptions, set before the Core Script loads. Extend the object rather than replacing it: window.sparkOptions = { ...window.sparkOptions, … }, or the Site ID and other snippets' hooks are lost. Headless only: window.initSpark(options) is defined when window.sparkOptions isn't set.
  • When to call it: Only after SparkLayer is ready: inside the onReady(spark) hook, or after a promise resolved from it. Most methods are async; prices and the cart are only available to signed-in B2B customers (check await spark.isLoggedIn()).
  • Products and prices: Products are looked up by the platform's parent product ID (on Shopify, product.id) and variants by SKU: getPricingForVariant(parentProductId, sku), calculatePricingForVariant(parentProductId, sku, qty), getPackSizeForVariant(parentProductId, sku). For instant recalculation, fetch once with getVariant and call calculatePricingForVariantData(variant, qty).
  • Cart: updateCart({ products: [{ sku, adjustQuantity }] }) adds or removes relative to what's in the cart (also customAttributes: [{ key, value }], clearCart: true). It resolves to the results, or null after showing its own error message; it doesn't throw. getCart() reads the cart; openDrawer('cart') opens it.
  • Hooks: onCartUpdate(cart, results), onCartLoad(cart), onLogout(), preCartUpdateListener(input) (async: return the possibly changed input) and onCheckoutValidation(cart, cartUiState) (return [{ message }] to block checkout, or null). When adding a hook, call any existing one first.
  • Customising: Build around SparkLayer or customise its own components, including their HTML. Prefer documented options, hooks, CSS variables and custom slots where they fit; keep direct HTML changes targeted and re-check them after SparkLayer updates.
  • Docs: The reference: methods docs.sparklayer.io/developers/javascript-sdk/reference/methods.md, hooks docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md, options docs.sparklayer.io/developers/javascript-sdk/reference/options.md, types docs.sparklayer.io/developers/javascript-sdk/reference/types.md (or the same types as a file: docs.sparklayer.io/developers/javascript-sdk/spark.d.ts). Setup and waiting for SparkLayer: docs.sparklayer.io/developers/javascript-sdk/setup.md. Use only what the reference documents.

You set window.sparkOptions before the Core Script loads, and SparkLayer then sets window.spark, the object with every method. On a headless storefront, leave window.sparkOptions unset and call window.initSpark(options) yourself: it takes the same options and returns the same object.

For worked examples, start with Set up the SDK.

Options

The settings on window.sparkOptions. Only siteId is required.

Site and platform

OptionWhat it does
siteIdYour site ID. Required.
sparkDomainThe domain of the SparkLayer API.
platformSets the default options for your ecommerce platform.
rootUrlPrefixes the URLs SparkLayer creates, generally for i18n.
wordpressSiteUrlThe WordPress site URL, on WooCommerce.
shopifyShopify options: whether to use the app proxy.
bigcommerceBigCommerce options: your app client ID.

Links and redirects

OptionWhat it does
accountRedirectSends logged-in users from matching paths to a page with the account drawer open.
cartRedirectSends logged-in users from matching paths to a page with the cart drawer open.
termsAndConditionsLinkLink to your terms and conditions.
productLinkThe link to a product page, built from the product's slug.

Button selectors

OptionWhat it does
accountButtonSelectorsCSS selectors for the account button.
logoutButtonSelectorsCSS selectors for the logout button.
cartButtonSelectorsCSS selectors for the cart button.
loginButtonSelectorsCSS selectors for the login button.

Display, language and translations

OptionWhat it does
displayDisplay options, such as the dark theme, SKUs and My Account sections.
languageThe language SparkLayer uses.
localeThe locale for formatting dates.
translationsOverrides SparkLayer's text, by language.
showTranslationsShows translation keys instead of text, for debugging.

Checkout and account

OptionWhat it does
checkoutCustomElementsStandard and custom fields to show in checkout.
paymentMethodsOrderThe order of the payment methods.
saveToAddressBookDefaultWhether new addresses are saved to the address book by default.
customAccountDetailsExtra details to show on a customer's My Details panel.
igniteCheckoutContextCheckout context data to pass to Ignite.

Authentication and analytics

OptionWhat it does
authThe user and token for SparkLayer auth.
authLogoutUriWhere SparkLayer redirects after logging out.
analyticsThe analytics providers and events to send.

Hooks

Functions you set on window.sparkOptions, which SparkLayer calls.

HookWhen it runs
onReadyWhen SparkLayer has initialised and the page's DOM has loaded.
onLoadOnce while SparkLayer initialises, before onReady.
onLogoutWhen the user logs out.
onCartLoadWhen the cart is loaded.
onCartUpdateEach time the cart is updated.
preCartUpdateListenerJust before SparkLayer's add to cart updates the cart, to change the update.
onCheckoutValidationEach time the cart loads or changes, to block checkout.

If a hook throws, SparkLayer shows a hook error code.

Methods

The methods on window.spark. Call them once SparkLayer is ready.

Customers and session

MethodWhat it doesReturns
isLoggedIn()Checks whether the user is logged in.Promise<boolean>
switchImpersonatingCustomer(customerId)Switches the customer a sales agent acts for, or ends it with null.Promise<UserData | null>
refreshGlobalData()Refetches the active customer and site configuration.Promise<UserData | null>
getActiveCustomerVerificationToken()Gets a fresh form customer verification token.Promise<string | null>
setActiveCompanySection(sectionId)Selects the company section to buy for, then reloads.Promise<boolean>

Products and pricing

MethodWhat it doesReturns
getProduct(parentProductId)Fetches a product by its parent product ID.Promise<Product>
getProductBySlug(slug)Fetches a product by its slug.Promise<Product>
getVariant(parentProductId, variantSku)Fetches a variant.Promise<ProductVariant>
getPriceForProduct(parentProductId)Gets a product's "from" price and how many prices it has.Promise<SimplifiedProductPrice>
getPricingForVariant(parentProductId, variantSku)Gets a variant's price, RRP and price breaks.Promise<{ price, rrp, … }>
getRrpPriceForVariant(parentProductId, variantSku)Gets a variant's RRP.Promise<{ rrp, currencyCode }>
getPackSizeForVariant(parentProductId, variantSku)Gets a variant's pack size.Promise<number>
calculatePricingForVariant(parentProductId, variantSku, qty)Prices a quantity of a variant.Promise<ProductVariantPricing>
calculatePricingForVariantData(variant, qty)Prices a quantity from variant data you have, without a request.ProductVariantPricing

Cart

MethodWhat it doesReturns
getCart()Fetches the cart.Promise<Cart | null>
getCartCache()Gets the cached cart, without a request.Cart | null
updateCart(input)Adds, updates or removes items and sets cart fields.Promise<CartResults[] | null>
addCustomLineItem(customItem)Adds a line not tied to a SKU.Promise<Cart | null>
externalClearBasket()Clears the cart, for your order confirmation page.Promise<void>

Drawer

MethodWhat it doesReturns
openDrawer(initialTab)Opens the drawer, on the Cart tab unless you pass another.void
closeDrawer()Closes the drawer.void

Files and GraphQL

MethodWhat it doesReturns
uploadFile(fileName, fileData)Uploads a file to attach to a cart line.Promise<string>
fetch(query, variables)Runs a GraphQL query or mutation as the user.Promise<FetchResponse>

window.spark.options holds the options SparkLayer is running with.

Events and components

NameWhat it is
spark-variant-changeEvent: the customer selects a variant in spark-pdp or spark-product-card.
spark-file-attachment-changedEvent: the files in a spark-file-upload-field change.
spark-file-attachment-failedEvent: a file fails to upload.
view-updateEvent you dispatch to switch an open drawer to a tab.
<spark-pdp>, <spark-product-card>, <spark-product-matrix>Components: the product detail, product card and product matrix interfaces.
<spark-product-price>, <spark-product-rrp>Components: the customer's price or the RRP for a product, anywhere on the page.
<spark-file-upload-field>Component: a file upload field for the product page.
<spark-drawer>Component: the drawer, which SparkLayer adds when needed.

TypeScript types

Download spark.d.ts for autocomplete and type checking in your editor, or point your AI assistant at it. It's generated from the Types page.

cart.ts
/// <reference path="./spark.d.ts" />

export async function countCartLines() {
  const cart = await window.spark.getCart(); // Cart | null
  return cart?.items.length ?? 0;
}

Next steps

Was this page helpful?

Last updated