Skip to main content

ThemeApi reference

SPZ.themeApi is the JavaScript interface a theme provides to app blocks on storefront pages. Through it, an app block reads the data of a product detail area, listens for changes to that data, locates theme elements such as the add-to-cart button and the price, and validates or edits line items before Add to cart, Buy now, or express checkout submits. Without ThemeApi, apps have to adapt to each theme's DOM structure and events separately, and that work can break when the theme updates; with ThemeApi, the same block code runs on every supported theme.

ThemeApi doesn't provide styling or layout. To make your block's appearance follow the theme, use theme CSS variables. It also doesn't replace the store's cart and order APIs: the final price and contents after checkout follow the server-side order. Pages outside a product detail area, such as the cart page and the checkout page, are out of ThemeApi's scope.

For the complete steps to add your block to the quick add modal, see Add your app block to the quick add modal.

Quick start​

The example below places an engraving input on the product detail page: it refreshes a tip when the buyer switches variants, and writes the engraving text into the line item's properties on submit.

javascript
(async () => {
// 1. Wait for ThemeApi to be ready
await SPZ.themeApi.whenReady();

// 2. Pass the block's own node to find the product detail area it sits in
const card = document.querySelector('#my-engraving-card');
const detail = await SPZ.themeApi.productDetail.get({ el: card });
if (!detail) return; // The theme isn't supported, or the block isn't in a product detail area

// 3. Read the current data
const data = detail.getData();
if (data) console.log(data.product.title, data.variant && data.variant.id, data.quantity);

// 4. Listen for variant changes
detail.onVariantChange((data) => renderTip(data.variant));

// 5. Write the engraving text into the line item before submit
detail.onBeforeSubmit((payload, context, abort) => {
const text = card.querySelector('input').value.trim();
if (!text) return abort('Please enter engraving text.');
payload.updateItems((item, index) =>
index === 0 ? { properties: { Engraving: text } } : undefined
);
}, { id: 'my-engraving-card' });
})();

Once your block is on the page, always pass el when you call productDetail.get(). Taking Reformia as an example, the quick add modal is already rendered into the page when the page loads, even while it's closed, so a product detail page has two product detail areas at the same time: the product detail page itself and the quick add modal. Without el, get() returns the product detail page's area, and a block placed in the modal gets the wrong one. When you pass the block's own node, ThemeApi walks up from that node to the area the block is in.

If your block's node isn't on the page yet, for example when a script inserts content before the add-to-cart button, you can call get() without el: it returns the product detail page's area, and you then locate the button with getElement('atc-button') and insert your content.

The image below shows an app block added to the Reformia quick add modal: the block sits below the quantity selector, and the lines under it are ThemeApi notifications the block prints.

An app block added to the quick add modal

Theme support​

ThemeApi picks its adapter by the theme the store currently uses. For themes not listed below, productDetail.get() returns null.

ThemeMinimum versionRead data and change notificationsElement lookupsetQuantitysetVariantinvokeAddToCart / invokeBuyNowonBeforeSubmit
Reformiav26.54.17✓✓✓✓✓✓
Nova 2023v26.19.0✓✓✓✓✓✓
Faridav26.13.0✓✓✓✓✓✓
Herov26.13.0✓✓✓✓✓✓
Geekv26.18.0✓✓✓✓✓✓
Flashv26.6.0✓✓✓✓✓✓
Windv26.13.0✓✓✓✓✓✓
Evav26.12.27✓✓✓✓✕✕
OnePagev26.7.0✓Partial✓✕✕✕
  • Eva: you can read data, listen for changes, and set the variant and quantity. Registered before-submit handlers don't run, and invokeAddToCart and invokeBuyNow fail.
  • OnePage: the product detail page selects by variant row and has no add-to-cart button, express checkout buttons, or variant selector, so those elements can't be found. Before-submit handlers don't run.
  • In the quick add modal, some themes have no gallery or price, and getElement returns null for them. For example, the gallery can't be found in Reformia's quick add modal.

whenReady​

Waits for ThemeApi to finish loading.

typescript
whenReady(): Promise<void>

Resolves after the ThemeApi script has loaded; only then can you access SPZ.themeApi.productDetail. Storefront pages provide whenReady before the theme script loads, so your script can call it directly whether it loads before or after the theme.

ProductDetail object​

A ProductDetail object represents one product detail area on the page. A product detail area is a region of the page that shows one product and lets the buyer pick a variant and submit. ThemeApi data, change notifications, element lookup, and before-submit handling all work per product detail area.

Get it with SPZ.themeApi.productDetail.get():

typescript
get(options?: { el?: Element | string }): Promise<ProductDetail | null>
ParameterTypeDescription
elElement | stringYour block's own node or a selector. When passed, ThemeApi walks up from this node to find the product detail area it's in. Without it, the first product detail area on the page is used, with the product detail page preferred

Returns: a ProductDetail object, or null when the current theme isn't supported or no product detail area is found.

In the quick add modal, get() returns the area object as soon as the page has loaded, before the modal opens; at that point getData() returns null. When the buyer opens the modal, you receive the product through change notifications.

Product detail areas appear in these scenarios:

ScenarioDescriptionWhen calling get()
Product detail pageThe main area of the product detail pageel is optional; without it, this area is preferred
Quick add modalThe window that pops up when a buyer clicks the add-to-cart button on a product image in a product list, such as on the home page, a collection page, or the search page. The buyer can pick a variant and add to cart right there. When the modal switches products, the area object stays the same and its data updatesPassing el is recommended
Single-product sections on the home page and other pagesA standalone section with a product form. Flash, Wind, and Eva don't support this scenarioel is required

Calling get() several times for the same product detail area returns the same object. The product detail page and the quick add modal are two different product detail areas, each with its own data, change notifications, and before-submit handlers, and they don't affect each other.

A ProductDetail object provides the following methods.

getData​

Reads the current data of the product detail area.

typescript
getData(): ProductDetailData | null

Each call reads the current page state, so you never get stale values. Returns null while the quick add modal has no product.

Here is an example of what it returns (fields trimmed; call getData() in the console on a storefront page to see every field):

javascript
{
product: {
id: '12e38433-1fa1-4be6-b88d-88ea184cd031',
title: 'Engraved Ring',
handle: 'engraved-ring',
url: '/products/engraved-ring',
price: '29.00',
compare_at_price: '0',
available: true,
options: [
{ id: 'af3efa09-ebb0-425f-a1ee-f5648bdc5c1f', name: 'Size', position: 1, values: ['S', 'M'], selectedValue: 'M' },
],
variants: [/* all variants, same structure as variant */],
images: [/* product images */],
// other fields omitted
},
variant: {
id: '7c1a73ef-23b8-40a9-a357-59088a107acf',
product_id: '12e38433-1fa1-4be6-b88d-88ea184cd031',
title: 'M',
sku: 'RING-M',
price: '29.00',
compare_at_price: '0',
available: true,
option1: 'M',
options: [{ name: 'Size', value: 'M' }],
// other fields omitted
},
quantity: 1,
selectedOptions: { Size: ['M'] },
properties: {},
}
  • Product and variant ids are strings.
  • Prices are strings, for example '29.00'.
FieldTypeDescription
productobjectThe current product; see the example above for common fields. options[].selectedValue is the value currently selected for that option. Metafields aren't included
variantobject | nullThe selected variant. null until every option is selected
quantitynumberThe quantity
selectedOptionsRecord<string, string[]>The selected option values, for example { Size: ['M'] }. {} when nothing is selected
propertiesRecord<string, string>The current values of every properties[...] field in the product detail area, including the fields in your block. Properties written by before-submit handlers aren't included

onChange and other change notifications​

Listens for data changes in the product detail area.

typescript
onChange(fn: (data: ProductDetailData | null, meta: { type: ProductDetailChangeType }) => void): Unsubscribe
onProductChange(fn: (data: ProductDetailData | null) => void): Unsubscribe
onVariantChange(fn: (data: ProductDetailData) => void): Unsubscribe
onQuantityChange(fn: (data: ProductDetailData) => void): Unsubscribe
MethodWhen it fires
onChangeAny of the changes below; meta.type tells which: product (product switched), variant (variant switched), quantity (quantity changed), properties (the value of a properties[...] field in the product detail area changed)
onProductChangeProduct switched
onVariantChangeVariant switched
onQuantityChangeQuantity changed
  • Changes to properties fields are only reported through onChange; there's no dedicated method.
  • The data that onChange and onProductChange receive can be null, meaning there's no product at the moment; handle it as having no product.
  • Multiple changes in the same tick are merged into one notification.
  • The return value is a function that removes the listener.
  • A callback that throws doesn't stop the other callbacks.
javascript
const off = detail.onVariantChange((data) => {
updatePrice(data.variant);
});

// Remove the listener when you no longer need it
off();

getElement / getElements​

Gets theme elements in the product detail area, such as the add-to-cart button, the price, or the gallery, so you can insert your block's content next to them.

typescript
getElement(name: ProductDetailElementName): ThemeElement | null
getElements(name: ProductDetailElementName): ThemeElement[]

getElement returns the one at the main position, or the first one when there's no main; it returns null when nothing is found. getElements returns every occurrence of the element in the product detail area, or [] when nothing is found. Each item is { el, position }.

nameElement
atc-buttonAdd-to-cart button
buy-buttonBuy-now button
express-checkoutExpress checkout button area
quantityQuantity selector
variantVariant selector
pricePrice area
galleryGallery. The returned item also provides getImages(), which returns the node of each image

The same element can appear more than once on the page; for example, the sticky bar at the bottom of the product detail page has its own add-to-cart button. position tells which occurrence it is:

positionMeaning
mainThe main position. When the product detail area has only one occurrence, it's this one
sticky-barThe sticky bar at the bottom
zoom-panelThe sticky bar in the image zoom panel
unnamed-NWhen there are several occurrences that can't be named, numbered in order of appearance starting from 1
javascript
const atc = detail.getElement('atc-button');
if (atc) atc.el.before(card);

The theme may replace elements when it re-renders. If you need an element over time, look it up again when you use it instead of holding on to an old el.

setVariant / setQuantity​

Selects a variant or sets the quantity on the buyer's behalf.

typescript
setVariant(variantId: string): Promise<ProductDetailData>
setQuantity(quantity: number): Promise<ProductDetailData>

These go through the theme's own variant selector and quantity selector, with the same effect as the buyer doing it by hand, and fire the matching change notifications. They resolve with the data after the change.

  • When the value doesn't change, they resolve with the current data right away.
  • quantity must be a positive integer. When it exceeds the stock, the theme may cap the quantity at the stock, and the call still resolves.
  • On failure they return a rejected Promise; see Error messages for the reasons.
javascript
try {
const data = await detail.setVariant(variantId);
console.log(data.variant.id);
} catch (error) {
console.warn(error.message); // For example: variant not found
}

invokeAddToCart / invokeBuyNow​

Triggers the theme's own Add to cart and Buy now flows.

typescript
invokeAddToCart(): Promise<void>
invokeBuyNow(): Promise<void>

The effect is the same as the buyer clicking the theme's button: the before-submit handlers and the success prompt or redirect all run as usual. Use these to replace the theme's buttons with your own while keeping the theme's add-to-cart experience. Eva and OnePage don't support these two methods.

The call returns a rejected Promise in these cases:

  • Not every option is selected: message is Please select all options.. Before-submit handlers don't run, and no request is sent.
  • A before-submit handler aborts: message is the text passed to abort.
  • The theme doesn't complete the submission, for example when stock is insufficient or the request fails.

onBeforeSubmit​

Registers a before-submit handler.

typescript
onBeforeSubmit(fn: SubmitHandler, options?: SubmitHandlerOptions): SubmitHandle

When the buyer clicks Add to cart, Buy now, or an express checkout button, or when you call invokeAddToCart() or invokeBuyNow(), the following happens in order:

  1. The theme assembles the line items to submit.
  2. The before-submit handlers registered on this product detail area run in order.
  3. The theme sends the request with the line items as the handlers left them.

If any handler calls abort or throws, the submission stops, the remaining handlers don't run, and the theme sends no request. Handlers can return a Promise; all handlers run one after another.

Handler parameters

ParameterDescription
payloadThe data of this submission and the methods to change it; see the table below
contextAn object shared by all handlers in this submission, new and empty for every submission. Values written by an earlier handler are visible to later ones, so you can use it to pass information between apps
abortStops this submission. The text you pass is the reason, and it's also the rejection reason { message } of invokeAddToCart() and invokeBuyNow(). Write return abort(...), and don't modify line items after aborting

payload

MemberDescription
sourceWhere the submission came from: add-to-cart (Add to cart), buy-now (Buy now), or express-checkout (express checkout)
lineItemsThe line items about to be submitted, read-only. The first one is the product selected on the page, and its properties are the values of the properties[...] fields in the product detail area
addItems(items)Appends line items. After you append, the theme submits all line items in one request
updateItems(updater)Changes line items one by one. updater(item, index) returns the fields to change; when it returns nothing, that line item stays as it is. properties are merged by key, and the results of repeated calls are merged together
removeItems(match)Removes the line items for which match(item, index) returns true

See LineItem under Types for the line item fields. Every change is validated; when a change is invalid, addItems or updateItems throws right away and the submission fails:

CaseError message
quantity isn't a positive integerline item N: quantity must be a positive integer
A properties value isn't a stringline item N: properties.<key> must be a string
No line items are left after all handlers runline items cannot be empty

N is the line item's index, starting from 0.

options

OptionDescription
priorityHigher numbers run first; defaults to 0. Handlers with the same priority run in registration order
idAn identifier for the handler, used for troubleshooting and for moveTo. Recommended. Registering again with the same id doesn't replace the earlier handler; both stay registered, so call off() when you no longer need one

When apps have a fixed order dependency, fix the order with priority and don't call moveTo on top of it.

Return value: SubmitHandle

MethodDescription
off()Unregisters this handler
moveTo(position)Moves this handler within the queue. position can be 'first', 'last', { before: id }, or { after: id }, or a function (queue) => position | undefined where queue is the current queue and each item is { id, priority, self }. When the function returns undefined or the target id doesn't exist, the handler doesn't move
javascript
// Add a free gift
detail.onBeforeSubmit((payload) => {
payload.addItems([{
product_id: giftProductId,
variant_id: giftVariantId,
quantity: 1,
properties: { _gift: 'true' },
}]);
}, { id: 'gift-plugin', priority: 10 });

// Stop the submission when validation fails
const handle = detail.onBeforeSubmit(async (payload, context, abort) => {
const ok = await validateDesign();
if (!ok) abort('Please finish your design first.');
}, { id: 'my-design-card' });

// Unregister when the block unmounts
handle.off();

Before-submit rules​

  • Handlers must be idempotent. The buyer may click more than once, and Add to cart, Buy now, and express checkout all trigger the handlers. Each run gets line items freshly assembled by the theme, and the same page state must produce the same result. Don't rely on running only once, and avoid cumulative side effects such as creating a new server-side record on every run.
  • Line items can't be empty. When no line items are left after all handlers run, the submission fails.
  • You're responsible for changes to the selected product. A handler can change or remove the line item of the product selected on the page, but this logs a warning to the console. The page display and the express checkout amount may then differ from the actual order.
  • To change only the variant or quantity, don't edit line items. Change the page state with setVariant or setQuantity before submit instead.
  • Prices follow the order. Final prices, discounts, and other results follow the server-side order; don't calculate them in the frontend and write them into line items.
  • Handlers are registered per product detail area. A handler only applies to the product detail area it was registered on. Register separately for the product detail page and the quick add modal.
  • The theme may check the variant first. Reformia, for example, prompts the buyer to select an option when not every option is selected, and before-submit handlers don't run.
  • The theme decides how the abort message is shown. abort only stops the submission; how the text you pass is displayed depends on the theme. Reformia, for example, shows it as a prompt. Your block should also show the problem in its own UI rather than relying on the theme alone.
  • Quantity inputs in your block. If your block contains a quantity input, add the app-plugin-area-scope attribute to the block's outermost element. ThemeApi then skips that region when reading and setting the quantity, so it isn't mistaken for the theme's quantity selector.

Error messages​

When a method fails, it returns a rejected Promise whose value is { message }.

messageWhereReason
product is switchingsetQuantity, setVariantThe quick add modal is switching products
quantity must be a positive integersetQuantityThe quantity isn't a positive integer
quantity selector not foundsetQuantityThe product detail area has no quantity selector
quantity not applied by themesetQuantityThe theme didn't accept the new quantity
variant not foundsetVariantThe current product has no such variant
variant selector not foundsetVariantThe product detail area has no usable variant selector
variant not applied by themesetVariantThe theme didn't switch to the target variant, for example because it can't be selected
theme does not support addToCart / theme does not support buyNowinvokeAddToCart, invokeBuyNowThe current theme or scenario isn't supported
Please select all options.invokeAddToCart, invokeBuyNowNot every option is selected. This error also carries code: 'variant_required'
line items cannot be emptySubmissionNo line items are left after the handlers run
line item N: …SubmissionA field of line item N is invalid; N starts from 0
The text passed to abortSubmissionA handler aborted the submission
The error message thrown by a handlerSubmissionA handler threw

Types​

The full TypeScript declarations, ready to copy into your project.

typescript
type ProductDetailElementName =
'atc-button' | 'buy-button' | 'express-checkout' | 'quantity' | 'variant' | 'price' | 'gallery';

type ThemeElementPosition = 'main' | 'sticky-bar' | 'zoom-panel' | `unnamed-${number}`;

interface ThemeElement { el: Element; position: ThemeElementPosition; }
interface GalleryElement extends ThemeElement { getImages(): Element[]; }

interface ProductDetailData {
product: Record<string, any>;
variant: Record<string, any> | null;
quantity: number;
selectedOptions: Record<string, string[]>;
properties: Record<string, string>;
}

type ProductDetailChangeType = 'product' | 'variant' | 'quantity' | 'properties';
type Unsubscribe = () => void;

interface ProductDetail {
getData(): ProductDetailData | null;
onProductChange(fn: (data: ProductDetailData | null) => void): Unsubscribe;
onVariantChange(fn: (data: ProductDetailData) => void): Unsubscribe;
onQuantityChange(fn: (data: ProductDetailData) => void): Unsubscribe;
onChange(fn: (data: ProductDetailData | null, meta: { type: ProductDetailChangeType }) => void): Unsubscribe;
getElement(name: 'gallery'): GalleryElement | null;
getElement(name: ProductDetailElementName): ThemeElement | null;
getElements(name: 'gallery'): GalleryElement[];
getElements(name: ProductDetailElementName): ThemeElement[];
setQuantity(quantity: number): Promise<ProductDetailData>;
setVariant(variantId: string): Promise<ProductDetailData>;
invokeAddToCart(): Promise<void>;
invokeBuyNow(): Promise<void>;
onBeforeSubmit(fn: SubmitHandler, options?: SubmitHandlerOptions): SubmitHandle;
}

type SubmitSource = 'add-to-cart' | 'buy-now' | 'express-checkout';

interface LineItem {
product_id: string;
variant_id: string;
quantity: number;
properties?: Record<string, string>;
}

interface SubmitPayload {
source: SubmitSource;
readonly lineItems: readonly LineItem[];
addItems(items: LineItem[]): void;
updateItems(updater: (item: LineItem, index: number) => Partial<LineItem> | void): void;
removeItems(match: (item: LineItem, index: number) => boolean): void;
}

type SubmitHandler = (
payload: SubmitPayload,
context: Record<string, any>,
abort: (message: string) => never
) => void | Promise<void>;

interface SubmitHandlerOptions { priority?: number; id?: string; }

type SubmitQueuePosition = 'first' | 'last' | { before: string } | { after: string };
interface SubmitQueueItem { id?: string; priority: number; self: boolean; }

interface SubmitHandle {
off(): void;
moveTo(position: SubmitQueuePosition
| ((queue: readonly SubmitQueueItem[]) => SubmitQueuePosition | undefined)): void;
}

interface ThemeApi {
whenReady(): Promise<void>;
productDetail?: {
get(options?: { el?: Element | string }): Promise<ProductDetail | null>;
};
}