JavaScript SDK
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.
The JavaScript SDK lets your own code work with SparkLayer on your storefront. Your theme can read the same data SparkLayer's own screens use, such as a customer's prices and cart, take the same actions, such as adding to the cart, and run code at key moments, such as just before checkout.
In code, the SDK is the window.spark object, which SparkLayer's Core Script adds to every page.
What you can build
- Custom pricing displays: show a customer's price, RRP or price breaks anywhere in your theme. See Products and pricing.
- Your own add to cart: add products, quantities and custom attributes (including files) to the cart. See Cart.
- Checkout rules: block checkout with your own validation, such as a product quota checked against your API. See Checkout.
- Customer and sales agent tools: check who's logged in, switch the customer a sales agent orders for, or query their data. See Customers and accounts.
- Theme integration: swap variant images, open the cart drawer or send events to your analytics. See Events and analytics.
- Headless storefronts: load and initialise SparkLayer yourself in a custom frontend. See Headless and React.
Choose the most stable way to customise
You can build around SparkLayer's own components, and change them too. Prefer the ways that keep working when SparkLayer updates:
- An option or hook in the SDK.
- A CSS variable for the look, or a custom slot to add your own content.
- Only if neither does the job, change a component's HTML. Keep the change small, and check it after each SparkLayer update.
Planning something bigger? Talk to our team first.
Build it with AI
Most SDK customisations are a few dozen lines of code, which suits an AI assistant well. Describe what you want, and the prompt below gives your assistant the SDK reference and the rules to follow. Review the code it writes, and test it on an unpublished theme or a test store before it goes live.
For work with the SparkLayer APIs, see Build with AI.
Ask your AI assistant
Describe the customisation and your assistant writes the code. The prompt gives it the SDK reference and how SparkLayer code is best written.
See the prompt, or copy it for another assistant
I want to customise SparkLayer's B2B storefront with its JavaScript SDK (window.spark). Before writing code, read the SDK reference: https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md, https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md, https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md and https://docs.sparklayer.io/developers/javascript-sdk/reference/types.md (also as a TypeScript file: https://docs.sparklayer.io/developers/javascript-sdk/spark.d.ts), and https://docs.sparklayer.io/developers/javascript-sdk/setup.md (how to load SparkLayer and wait for it), plus the guide for the area I'm working on (https://docs.sparklayer.io/developers/javascript-sdk.md links to them). Follow these rules: extend window.sparkOptions instead of replacing it (window.sparkOptions = { ...window.sparkOptions, … }) and set it before the SparkLayer Core Script loads; only call window.spark after the onReady hook; use only the options, hooks, methods and events in the reference, and tell me if something isn't documented; prefer documented options, hooks, CSS variables and custom slots where they fit, and if you change the HTML of SparkLayer's own components, keep it targeted and tell me what to check after SparkLayer updates; keep hooks fast. If you're connected to the SparkLayer MCP (the SparkLayer connector), use it to read my store's real data, such as SKUs and customer groups. It can also make changes, but don't make any unless I ask. Tell me exactly where each snippet goes in my theme, give me complete code, and explain how to test it on an unpublished theme first.
What I want to build:How the SDK loads
The SDK comes with the Core Script, so there's nothing extra to install. On Shopify, the SparkLayer app embed loads it. On other platforms, you add the Core Script to your theme's <head> from the SparkLayer Dashboard.
Two rules apply to all SDK code:
- Set your options first. You configure the SDK with
window.sparkOptions, which must be set before the Core Script loads. - Wait until SparkLayer is ready.
window.sparkonly works once SparkLayer has started, so run your code from theonReadyhook.
Set up the SDK covers both in detail.
Try it: show a customer's price
Add this to your theme's <head>, before the Core Script. When SparkLayer is ready, it checks whether a customer is logged in and, if they are, writes their price for one product to the browser console:
<script>
window.sparkOptions = {
...window.sparkOptions,
onReady: async (spark) => {
if (!(await spark.isLoggedIn())) {
return;
}
// Use a parent product ID and variant SKU from your store
const pricing = await spark.getPricingForVariant('6660191387839', 'MUG-MOM');
console.log(pricing.price, pricing.currencyCode, pricing.priceBreaks);
},
};
</script>Open a product page as a logged-in B2B customer and check the browser console. The ...window.sparkOptions line keeps the options already set by the Core Script or other snippets: see Add your own options and hooks.
If one of your hooks throws an error, SparkLayer shows a system error with a code such as OPTIONS:HOOK:OR. See Hook error codes.
Next steps
Load the Core Script, add your own options and hooks, and wait for SparkLayer to be ready.
Show trade prices, live quantity pricing and the right image for each variant.
Add and remove items, set cart fields, attach attributes and files, and open the drawer.
Block checkout until your own rules are met.
Check the login, work as a sales agent, switch company sections and run GraphQL queries.
Hooks, DOM events and sending B2B events to Google Analytics or your own tools.
Load and initialise SparkLayer yourself, with Next.js and React examples.
Every sparkOptions setting, hook, window.spark method, type, DOM event and web component.
Last updated