# SDK reference

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

Look up every sparkOptions setting, hook, window.spark method, DOM event and web component in the SparkLayer JavaScript SDK, and download its types.

> **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.

You set [`window.sparkOptions`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md) before the Core Script loads, and SparkLayer then sets [`window.spark`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md), the object with every method. On a [headless storefront](https://docs.sparklayer.io/developers/javascript-sdk/headless.md), 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](https://docs.sparklayer.io/developers/javascript-sdk/setup.md).

## Options

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

**Site and platform**

| Option | What it does |
| --- | --- |
| [`siteId`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | Your site ID. Required. |
| [`sparkDomain`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | The domain of the SparkLayer API. |
| [`platform`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | Sets the default options for your ecommerce platform. |
| [`rootUrl`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | Prefixes the URLs SparkLayer creates, generally for i18n. |
| [`wordpressSiteUrl`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | The WordPress site URL, on WooCommerce. |
| [`shopify`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | Shopify options: whether to use the app proxy. |
| [`bigcommerce`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#site-and-platform) | BigCommerce options: your app client ID. |

**Links and redirects**

| Option | What it does |
| --- | --- |
| [`accountRedirect`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#links-and-redirects) | Sends logged-in users from matching paths to a page with the account drawer open. |
| [`cartRedirect`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#links-and-redirects) | Sends logged-in users from matching paths to a page with the cart drawer open. |
| [`termsAndConditionsLink`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#links-and-redirects) | Link to your terms and conditions. |
| [`productLink`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#links-and-redirects) | The link to a product page, built from the product's slug. |

**Button selectors**

| Option | What it does |
| --- | --- |
| [`accountButtonSelectors`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#button-selectors) | CSS selectors for the account button. |
| [`logoutButtonSelectors`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#button-selectors) | CSS selectors for the logout button. |
| [`cartButtonSelectors`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#button-selectors) | CSS selectors for the cart button. |
| [`loginButtonSelectors`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#button-selectors) | CSS selectors for the login button. |

**Display, language and translations**

| Option | What it does |
| --- | --- |
| [`display`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#display-language-and-translations) | Display options, such as the dark theme, SKUs and My Account sections. |
| [`language`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#display-language-and-translations) | The language SparkLayer uses. |
| [`locale`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#display-language-and-translations) | The locale for formatting dates. |
| [`translations`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#display-language-and-translations) | Overrides SparkLayer's text, by language. |
| [`showTranslations`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#display-language-and-translations) | Shows translation keys instead of text, for debugging. |

**Checkout and account**

| Option | What it does |
| --- | --- |
| [`checkoutCustomElements`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#checkout-and-account) | Standard and custom fields to show in checkout. |
| [`paymentMethodsOrder`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#checkout-and-account) | The order of the payment methods. |
| [`saveToAddressBookDefault`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#checkout-and-account) | Whether new addresses are saved to the address book by default. |
| [`customAccountDetails`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#checkout-and-account) | Extra details to show on a customer's My Details panel. |
| [`igniteCheckoutContext`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#checkout-and-account) | Checkout context data to pass to Ignite. |

**Authentication and analytics**

| Option | What it does |
| --- | --- |
| [`auth`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#authentication-and-analytics) | The user and token for SparkLayer auth. |
| [`authLogoutUri`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#authentication-and-analytics) | Where SparkLayer redirects after logging out. |
| [`analytics`](https://docs.sparklayer.io/developers/javascript-sdk/reference/options.md#authentication-and-analytics) | The analytics providers and events to send. |

## Hooks

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

| Hook | When it runs |
| --- | --- |
| [`onReady`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#onready) | When SparkLayer has initialised and the page's DOM has loaded. |
| [`onLoad`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#onload) | Once while SparkLayer initialises, before `onReady`. |
| [`onLogout`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#onlogout) | When the user logs out. |
| [`onCartLoad`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#oncartload) | When the cart is loaded. |
| [`onCartUpdate`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#oncartupdate) | Each time the cart is updated. |
| [`preCartUpdateListener`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#precartupdatelistener) | Just before SparkLayer's add to cart updates the cart, to change the update. |
| [`onCheckoutValidation`](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#oncheckoutvalidation) | Each time the cart loads or changes, to block checkout. |

If a hook throws, SparkLayer shows a [hook error code](https://docs.sparklayer.io/developers/javascript-sdk/reference/hooks.md#hook-error-codes).

## Methods

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

**Customers and session**

| Method | What it does | Returns |
| --- | --- | --- |
| [`isLoggedIn()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#isloggedin) | Checks whether the user is logged in. | `Promise<boolean>` |
| [`switchImpersonatingCustomer(customerId)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#switchimpersonatingcustomer) | Switches the customer a sales agent acts for, or ends it with `null`. | `Promise<UserData \| null>` |
| [`refreshGlobalData()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#refreshglobaldata) | Refetches the active customer and site configuration. | `Promise<UserData \| null>` |
| [`getActiveCustomerVerificationToken()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getactivecustomerverificationtoken) | Gets a fresh form customer verification token. | `Promise<string \| null>` |
| [`setActiveCompanySection(sectionId)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#setactivecompanysection) | Selects the company section to buy for, then reloads. | `Promise<boolean>` |

**Products and pricing**

| Method | What it does | Returns |
| --- | --- | --- |
| [`getProduct(parentProductId)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getproduct) | Fetches a product by its parent product ID. | `Promise<Product>` |
| [`getProductBySlug(slug)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getproductbyslug) | Fetches a product by its slug. | `Promise<Product>` |
| [`getVariant(parentProductId, variantSku)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getvariant) | Fetches a variant. | `Promise<ProductVariant>` |
| [`getPriceForProduct(parentProductId)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getpriceforproduct) | Gets a product's "from" price and how many prices it has. | `Promise<SimplifiedProductPrice>` |
| [`getPricingForVariant(parentProductId, variantSku)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getpricingforvariant) | Gets a variant's price, RRP and price breaks. | `Promise<{ price, rrp, … }>` |
| [`getRrpPriceForVariant(parentProductId, variantSku)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getrrppriceforvariant) | Gets a variant's RRP. | `Promise<{ rrp, currencyCode }>` |
| [`getPackSizeForVariant(parentProductId, variantSku)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getpacksizeforvariant) | Gets a variant's pack size. | `Promise<number>` |
| [`calculatePricingForVariant(parentProductId, variantSku, qty)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#calculatepricingforvariant) | Prices a quantity of a variant. | `Promise<ProductVariantPricing>` |
| [`calculatePricingForVariantData(variant, qty)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#calculatepricingforvariantdata) | Prices a quantity from variant data you have, without a request. | `ProductVariantPricing` |

**Cart**

| Method | What it does | Returns |
| --- | --- | --- |
| [`getCart()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getcart) | Fetches the cart. | `Promise<Cart \| null>` |
| [`getCartCache()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#getcartcache) | Gets the cached cart, without a request. | `Cart \| null` |
| [`updateCart(input)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#updatecart) | Adds, updates or removes items and sets cart fields. | `Promise<CartResults[] \| null>` |
| [`addCustomLineItem(customItem)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#addcustomlineitem) | Adds a line not tied to a SKU. | `Promise<Cart \| null>` |
| [`externalClearBasket()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#externalclearbasket) | Clears the cart, for your order confirmation page. | `Promise<void>` |

**Drawer**

| Method | What it does | Returns |
| --- | --- | --- |
| [`openDrawer(initialTab)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#opendrawer) | Opens the drawer, on the Cart tab unless you pass another. | `void` |
| [`closeDrawer()`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#closedrawer) | Closes the drawer. | `void` |

**Files and GraphQL**

| Method | What it does | Returns |
| --- | --- | --- |
| [`uploadFile(fileName, fileData)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#uploadfile) | Uploads a file to attach to a cart line. | `Promise<string>` |
| [`fetch(query, variables)`](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#fetch) | Runs a GraphQL query or mutation as the user. | `Promise<FetchResponse>` |

`window.spark.options` holds the [options](https://docs.sparklayer.io/developers/javascript-sdk/reference/methods.md#options) SparkLayer is running with.

## Events and components

| Name | What it is |
| --- | --- |
| [`spark-variant-change`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#spark-variant-change) | Event: the customer selects a variant in `spark-pdp` or `spark-product-card`. |
| [`spark-file-attachment-changed`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#spark-file-attachment-changed) | Event: the files in a `spark-file-upload-field` change. |
| [`spark-file-attachment-failed`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#spark-file-attachment-failed) | Event: a file fails to upload. |
| [`view-update`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#view-update) | Event you dispatch to switch an open drawer to a tab. |
| [`<spark-pdp>`, `<spark-product-card>`, `<spark-product-matrix>`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#web-components) | Components: the product detail, product card and product matrix interfaces. |
| [`<spark-product-price>`, `<spark-product-rrp>`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#web-components) | Components: the customer's price or the RRP for a product, anywhere on the page. |
| [`<spark-file-upload-field>`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#web-components) | Component: a file upload field for the product page. |
| [`<spark-drawer>`](https://docs.sparklayer.io/developers/javascript-sdk/reference/events-and-components.md#web-components) | Component: the drawer, which SparkLayer adds when needed. |

## TypeScript types

Download [spark.d.ts](https://docs.sparklayer.io/developers/javascript-sdk/spark.d.ts) for autocomplete and type checking in your editor, or point your AI assistant at it. It's generated from the [Types](https://docs.sparklayer.io/developers/javascript-sdk/reference/types.md) page.

```typescript title="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

- [Set up the SDK](https://docs.sparklayer.io/developers/javascript-sdk/setup.md): How the SDK loads, how to add your options and hooks, and how to wait for it.
- [Cart](https://docs.sparklayer.io/developers/javascript-sdk/cart.md): Add, update and remove items with updateCart, and attach custom attributes and files.
- [Headless and React](https://docs.sparklayer.io/developers/javascript-sdk/headless.md): Initialise SparkLayer yourself and use it from React.
