# JavaScript SDK

URL: https://docs.sparklayer.io/developers/javascript-sdk

What the SparkLayer JavaScript SDK is, what you can build with it, how it loads with the Core Script, and a first example that fetches a customer's price.

> **For AI assistants:** what to know before writing SparkLayer JavaScript 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 https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md, hooks https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md, options https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md, types https://docs.sparklayer.io/developers/javascript-sdk/reference/types.md (or the same types as a file: https://docs.sparklayer.io/developers/javascript-sdk/spark.d.ts). Setup and waiting for SparkLayer: https://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](https://docs.sparklayer.io/help/glossary.md#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](https://docs.sparklayer.io/developers/javascript-sdk/products-and-pricing.md).
- **Your own add to cart**: add products, quantities and custom attributes (including files) to the cart. See [Cart](https://docs.sparklayer.io/developers/javascript-sdk/cart.md).
- **Checkout rules**: block checkout with your own validation, such as a product quota checked against your API. See [Checkout](https://docs.sparklayer.io/developers/javascript-sdk/checkout.md).
- **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](https://docs.sparklayer.io/developers/javascript-sdk/customers-and-accounts.md).
- **Theme integration**: swap variant images, open the cart drawer or send events to your analytics. See [Events and analytics](https://docs.sparklayer.io/developers/javascript-sdk/events-and-analytics.md).
- **Headless storefronts**: load and initialise SparkLayer yourself in a custom frontend. See [Headless and React](https://docs.sparklayer.io/developers/javascript-sdk/headless.md).

### 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:

1. An **option** or **hook** in the SDK.
2. A [CSS variable](https://docs.sparklayer.io/help/storefront/customising-design.md) for the look, or a [custom slot](https://docs.sparklayer.io/help/storefront/interfaces/custom-slots.md) to add your own content.
3. 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](https://docs.sparklayer.io/help/support.md) 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](https://docs.sparklayer.io/developers/build-with-ai.md).

## 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.spark` only works once SparkLayer has started, so run your code from the `onReady` hook.

[Set up the SDK](https://docs.sparklayer.io/developers/javascript-sdk/setup.md) 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:

```html title="theme.liquid or your theme's <head>"
<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](https://docs.sparklayer.io/developers/javascript-sdk/setup.md#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](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#hook-error-codes).

## Next steps

- [Set up the SDK](https://docs.sparklayer.io/developers/javascript-sdk/setup.md): Load the Core Script, add your own options and hooks, and wait for SparkLayer to be ready.
- [Products and pricing](https://docs.sparklayer.io/developers/javascript-sdk/products-and-pricing.md): Show trade prices, live quantity pricing and the right image for each variant.
- [Cart](https://docs.sparklayer.io/developers/javascript-sdk/cart.md): Add and remove items, set cart fields, attach attributes and files, and open the drawer.
- [Checkout](https://docs.sparklayer.io/developers/javascript-sdk/checkout.md): Block checkout until your own rules are met.
- [Customers and accounts](https://docs.sparklayer.io/developers/javascript-sdk/customers-and-accounts.md): Check the login, work as a sales agent, switch company sections and run GraphQL queries.
- [Events and analytics](https://docs.sparklayer.io/developers/javascript-sdk/events-and-analytics.md): Hooks, DOM events and sending B2B events to Google Analytics or your own tools.
- [Headless and React](https://docs.sparklayer.io/developers/javascript-sdk/headless.md): Load and initialise SparkLayer yourself, with Next.js and React examples.
- [SDK reference](https://docs.sparklayer.io/developers/javascript-sdk/reference.md): Every sparkOptions setting, hook, window\.spark method, type, DOM event and web component.
