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 oldcdn.sparklayer.io/spark.latest.jsandspark.1.x.jsfiles 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 whenwindow.sparkOptionsisn'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 (checkawait 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 withgetVariantand callcalculatePricingForVariantData(variant, qty). - Cart:
updateCart({ products: [{ sku, adjustQuantity }] })adds or removes relative to what's in the cart (alsocustomAttributes: [{ key, value }],clearCart: true). It resolves to the results, ornullafter 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) andonCheckoutValidation(cart, cartUiState)(return[{ message }]to block checkout, ornull). 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
| Option | What it does |
|---|---|
siteId | Your site ID. Required. |
sparkDomain | The domain of the SparkLayer API. |
platform | Sets the default options for your ecommerce platform. |
rootUrl | Prefixes the URLs SparkLayer creates, generally for i18n. |
wordpressSiteUrl | The WordPress site URL, on WooCommerce. |
shopify | Shopify options: whether to use the app proxy. |
bigcommerce | BigCommerce options: your app client ID. |
Links and redirects
| Option | What it does |
|---|---|
accountRedirect | Sends logged-in users from matching paths to a page with the account drawer open. |
cartRedirect | Sends logged-in users from matching paths to a page with the cart drawer open. |
termsAndConditionsLink | Link to your terms and conditions. |
productLink | The link to a product page, built from the product's slug. |
Button selectors
| Option | What it does |
|---|---|
accountButtonSelectors | CSS selectors for the account button. |
logoutButtonSelectors | CSS selectors for the logout button. |
cartButtonSelectors | CSS selectors for the cart button. |
loginButtonSelectors | CSS selectors for the login button. |
Display, language and translations
| Option | What it does |
|---|---|
display | Display options, such as the dark theme, SKUs and My Account sections. |
language | The language SparkLayer uses. |
locale | The locale for formatting dates. |
translations | Overrides SparkLayer's text, by language. |
showTranslations | Shows translation keys instead of text, for debugging. |
Checkout and account
| Option | What it does |
|---|---|
checkoutCustomElements | Standard and custom fields to show in checkout. |
paymentMethodsOrder | The order of the payment methods. |
saveToAddressBookDefault | Whether new addresses are saved to the address book by default. |
customAccountDetails | Extra details to show on a customer's My Details panel. |
igniteCheckoutContext | Checkout context data to pass to Ignite. |
Authentication and analytics
| Option | What it does |
|---|---|
auth | The user and token for SparkLayer auth. |
authLogoutUri | Where SparkLayer redirects after logging out. |
analytics | The analytics providers and events to send. |
Hooks
Functions you set on window.sparkOptions, which SparkLayer calls.
| Hook | When it runs |
|---|---|
onReady | When SparkLayer has initialised and the page's DOM has loaded. |
onLoad | Once while SparkLayer initialises, before onReady. |
onLogout | When the user logs out. |
onCartLoad | When the cart is loaded. |
onCartUpdate | Each time the cart is updated. |
preCartUpdateListener | Just before SparkLayer's add to cart updates the cart, to change the update. |
onCheckoutValidation | Each 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
| Method | What it does | Returns |
|---|---|---|
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
| Method | What it does | Returns |
|---|---|---|
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
| Method | What it does | Returns |
|---|---|---|
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
| Method | What it does | Returns |
|---|---|---|
openDrawer(initialTab) | Opens the drawer, on the Cart tab unless you pass another. | void |
closeDrawer() | Closes the drawer. | void |
Files and GraphQL
| Method | What it does | Returns |
|---|---|---|
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
| Name | What it is |
|---|---|
spark-variant-change | Event: the customer selects a variant in spark-pdp or spark-product-card. |
spark-file-attachment-changed | Event: the files in a spark-file-upload-field change. |
spark-file-attachment-failed | Event: a file fails to upload. |
view-update | Event 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.
/// <reference path="./spark.d.ts" />
export async function countCartLines() {
const cart = await window.spark.getCart(); // Cart | null
return cart?.items.length ?? 0;
}Next steps
Last updated