Skip to content

Search is only available in production builds. Try building and previewing the site to test it out locally.

Checkout utility functions

This topic provides details and instructions for using the utility functions available in the checkout drop-in component. These functions were moved from the integration layer and are now publicly accessible within the checkout block from @dropins/storefront-checkout/lib/utils.js.

Quick imports

import {
setAddressOnCart,
estimateShippingCost,
isVirtualCart,
isEmptyCart,
getCartShippingMethod,
getCartAddress,
getCartPaymentMethod,
createFragment,
createScopedSelector,
validateForm,
createMetaTag,
setMetaTags,
scrollToElement,
transformAddressFormValuesToCartAddressInput,
transformCartAddressToFormValues,
} from '@dropins/storefront-checkout/lib/utils.js';

API Functions

setAddressOnCart

The setAddressOnCart function creates a debounced handler for setting shipping or billing addresses on the cart, preventing excessive API calls when address data changes frequently.

export function setAddressOnCart({
type = 'shipping',
debounceMs = 0,
placeOrderBtn,
}: {
type?: 'shipping' | 'billing';
debounceMs?: number;
placeOrderBtn?: RenderAPI;
}): (change: AddressFormChange) => void;
Parameter Type Req? Description
typestringNo Address type: "shipping" or "billing". Defaults to "shipping".
debounceMsnumberNo Milliseconds to debounce API calls. Defaults to 0.
placeOrderBtnRenderAPINo Place order button API to manage disabled state.

Returns

Returns a function that accepts address form changes and updates the cart accordingly.

Usage

import { setAddressOnCart } from '@dropins/storefront-checkout/lib/utils.js';
// Set up debounced shipping address handler
const handleShippingChange = setAddressOnCart({
type: 'shipping',
debounceMs: 500,
placeOrderBtn: placeOrderButtonAPI
});
// Use with form change events
shippingForm.addEventListener('input', (event) => {
const formData = getFormValues(event.target.form);
const isValid = validateForm(event.target.form);
handleShippingChange({
data: formData,
isDataValid: isValid
});
});

estimateShippingCost

The estimateShippingCost function creates a debounced handler for estimating shipping costs based on address information.

export function estimateShippingCost({ debounceMs = 0 }): (change: AddressFormChange) => void;
Parameter Type Req? Description
debounceMsnumberNo Milliseconds to debounce API calls. Defaults to 0.

Returns

Returns a function that estimates shipping costs when address data changes.

Usage

import { estimateShippingCost } from '@dropins/storefront-checkout/lib/utils.js';
// Set up shipping cost estimation
const handleEstimateShipping = estimateShippingCost({ debounceMs: 300 });
// Use with address form changes
addressForm.addEventListener('input', (event) => {
const formData = getFormValues(event.target.form);
const isValid = validateForm(event.target.form);
handleEstimateShipping({
data: formData,
isDataValid: isValid
});
});

Cart Data Functions

isVirtualCart

The isVirtualCart function checks if a cart contains only virtual products (no shipping required). If no argument is provided, it reads the latest checkout data.

export function isVirtualCart(data?: Cart | null): boolean;
Parameter Type Req? Description
dataCart | nullYes The cart data object to check.

Returns

Returns true if the cart is virtual, false otherwise.

Usage

import { isVirtualCart } from '@dropins/storefront-checkout/lib/utils.js';
// Check if shipping is required using explicit data
const cartData = await getCart();
const skipShipping = isVirtualCart(cartData);
// Or check using the latest checkout data
const skipShippingFromState = isVirtualCart();
if (skipShipping) {
// Hide shipping-related UI
document.querySelector('.shipping-section').style.display = 'none';
}

isEmptyCart

The isEmptyCart function checks if a cart is empty or null.

export function isEmptyCart(data: Cart | null): boolean;
Parameter Type Req? Description
dataCart | nullYes The cart data object to check.

Returns

Returns true if the cart is empty or null, false otherwise.

Usage

import { isEmptyCart } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();
if (isEmptyCart(cartData)) {
// Show empty cart message
showEmptyCartMessage();
return;
}
// Proceed with checkout
proceedToCheckout(cartData);

getCartShippingMethod

The getCartShippingMethod function retrieves the selected shipping method from cart data.

export function getCartShippingMethod(data: Cart | null): ShippingMethod | null;
Parameter Type Req? Description
dataCart | nullYes The cart data object.

Returns

Returns the selected shipping method object or null if none is selected.

Usage

import { getCartShippingMethod } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();
const shippingMethod = getCartShippingMethod(cartData);
if (shippingMethod) {
console.log(`Shipping: ${shippingMethod.title} - $${shippingMethod.amount.value}`);
}

getCartAddress

The getCartAddress function retrieves shipping or billing address from cart data.

export function getCartAddress(
data: Cart | null,
type: 'shipping' | 'billing' = 'shipping'
): Record<string, any> | null;
Parameter Type Req? Description
dataCart | nullYes The cart data object.
typestringNo Address type: "shipping" or "billing". Defaults to "shipping".

Returns

Returns the address object or null if no address is set.

Usage

import { getCartAddress } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();
const shippingAddress = getCartAddress(cartData, 'shipping');
const billingAddress = getCartAddress(cartData, 'billing');
if (shippingAddress) {
populateAddressForm(shippingAddress);
}

getCartPaymentMethod

The getCartPaymentMethod function retrieves the selected payment method from cart data.

export function getCartPaymentMethod(data: Cart | null): PaymentMethod | null;
Parameter Type Req? Description
dataCart | nullYes The cart data object.

Returns

Returns the selected payment method object or null if none is selected.

Usage

import { getCartPaymentMethod } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();
const paymentMethod = getCartPaymentMethod(cartData);
if (paymentMethod) {
console.log(`Payment method: ${paymentMethod.code}`);
}

DOM and Fragment Functions

createFragment

The createFragment function creates a DocumentFragment from an HTML string.

export function createFragment(html: string): DocumentFragment;
Parameter Type Req? Description
htmlstringYes The HTML string to convert to a DocumentFragment.

Returns

Returns a DocumentFragment containing the parsed HTML.

Usage

import { createFragment } from '@dropins/storefront-checkout/lib/utils.js';
const html = `
<div class="checkout-step">
<h2>Payment Information</h2>
<form class="payment-form">
<!-- form fields -->
</form>
</div>
`;
const fragment = createFragment(html);
document.querySelector('.checkout-container').appendChild(fragment);

createScopedSelector

The createScopedSelector function creates a scoped querySelector function for a DocumentFragment.

export function createScopedSelector(
fragment: DocumentFragment
): (selector: string) => HTMLElement | null;
Parameter Type Req? Description
fragmentDocumentFragmentYes The DocumentFragment to scope the selector to.

Returns

Returns a function that queries elements within the given fragment.

Usage

import { createFragment, createScopedSelector } from '@dropins/storefront-checkout/lib/utils.js';
const html = `
<div class="checkout-step">
<button class="next-btn">Next</button>
<button class="prev-btn">Previous</button>
</div>
`;
const fragment = createFragment(html);
const $ = createScopedSelector(fragment);
// Query within the fragment only
const nextButton = $('.next-btn');
const prevButton = $('.prev-btn');
nextButton?.addEventListener('click', handleNext);

Form Functions

validateForm

The validateForm function validates a form by name using form references.

export function validateForm(
formName: string,
formRef: RefObject<FormRef>
): boolean;
Parameter Type Req? Description
formNamestringYes The name attribute of the form to validate.
formRefRefObject<FormRef>Yes Reference object to the form component.

Returns

Returns true if the form is valid, false otherwise.

Usage

import { validateForm } from '@dropins/storefront-checkout/lib/utils.js';
// Validate checkout form before submission
const isShippingValid = validateForm('shipping-form', shippingFormRef);
const isBillingValid = validateForm('billing-form', billingFormRef);
if (isShippingValid && isBillingValid) {
proceedToPayment();
} else {
showValidationErrors();
}

Meta Functions

createMetaTag

The createMetaTag function creates or updates meta tags in the document head.

export function createMetaTag(property: string, content: string, type: string): void;
Parameter Type Req? Description
propertystringYes The property/name of the meta tag.
contentstringYes The content value for the meta tag.
typestringYes The type of meta tag: "name" or "property".

Returns

The function does not return a value; it modifies the document head.

Usage

import { createMetaTag } from '@dropins/storefront-checkout/lib/utils.js';
// Set checkout-specific meta tags
createMetaTag('description', 'Complete your purchase securely', 'name');
createMetaTag('og:title', 'Checkout - Your Store', 'property');

setMetaTags

The setMetaTags function sets standard meta tags for a drop-in component.

export function setMetaTags(dropin: string): void;
Parameter Type Req? Description
dropinstringYes The name of the dropin component.

Returns

The function does not return a value; it sets multiple meta tags.

Usage

import { setMetaTags } from '@dropins/storefront-checkout/lib/utils.js';
// Set meta tags for checkout page
setMetaTags('Checkout');

Utility Functions

scrollToElement

The scrollToElement function smoothly scrolls to and focuses on an HTML element.

export function scrollToElement(element: HTMLElement): void;
Parameter Type Req? Description
elementHTMLElementYes The element to scroll to and focus.

Returns

The function does not return a value; it performs scrolling and focusing.

Usage

import { scrollToElement } from '@dropins/storefront-checkout/lib/utils.js';
// Scroll to error field
const errorField = document.querySelector('.field-error');
if (errorField) {
scrollToElement(errorField);
}
// Scroll to next checkout step
const nextStep = document.querySelector('.checkout-step.active');
scrollToElement(nextStep);

Data Transformer Functions

transformAddressFormValuesToCartAddressInput

The transformAddressFormValuesToCartAddressInput function converts form data to cart address input format.

export const transformAddressFormValuesToCartAddressInput = (
data: Record<string, any>
): ShippingAddressInput | BillingAddressInput;
Parameter Type Req? Description
dataRecord<string, any>Yes Form data object containing address information.

Returns

Returns a formatted address input object for cart API calls.

Usage

import { transformAddressFormValuesToCartAddressInput } from '@dropins/storefront-checkout/lib/utils.js';
// Transform form data for API
const formData = getFormValues(addressForm);
const addressInput = transformAddressFormValuesToCartAddressInput(formData);
// Send to cart API
await setShippingAddress(addressInput);

transformCartAddressToFormValues

The transformCartAddressToFormValues function converts cart address data to the form values format.

export const transformCartAddressToFormValues = (
address: CartAddress
): Record<string, any>;
Parameter Type Req? Description
addressCartAddressYes Cart address object to transform.

Returns

Returns a form-compatible object with address data.

Usage

import { transformCartAddressToFormValues, getCartAddress } from '@dropins/storefront-checkout/lib/utils.js';
// Pre-populate form with existing address
const cartData = await getCart();
const shippingAddress = getCartAddress(cartData, 'shipping');
if (shippingAddress) {
const formValues = transformCartAddressToFormValues(shippingAddress);
populateForm(shippingForm, formValues);
}

Common Usage Patterns

These utility functions work together to create robust checkout experiences:

Complete Address Handling

import {
setAddressOnCart,
transformAddressFormValuesToCartAddressInput,
transformCartAddressToFormValues,
getCartAddress,
validateForm
} from '@dropins/storefront-checkout/lib/utils.js';
// Set up address form handling
const handleAddressChange = setAddressOnCart({
type: 'shipping',
debounceMs: 500,
placeOrderBtn: placeOrderAPI
});
// Pre-populate form with existing data
const cartData = await getCart();
const existingAddress = getCartAddress(cartData, 'shipping');
if (existingAddress) {
const formValues = transformCartAddressToFormValues(existingAddress);
populateAddressForm(formValues);
}
// Handle form changes
addressForm.addEventListener('input', (event) => {
const formData = getFormValues(event.target.form);
const isValid = validateForm('shipping-address', formRef);
handleAddressChange({ data: formData, isDataValid: isValid });
});

Cart State Management

import {
isVirtualCart,
isEmptyCart,
getCartShippingMethod,
getCartPaymentMethod
} from '@dropins/storefront-checkout/lib/utils.js';
function updateCheckoutUI(cartData) {
// Handle empty cart
if (isEmptyCart(cartData)) {
showEmptyCartMessage();
return;
}
// Handle virtual cart (no shipping)
if (isVirtualCart(cartData)) {
hideShippingSection();
} else {
const shippingMethod = getCartShippingMethod(cartData);
updateShippingDisplay(shippingMethod);
}
// Update payment display
const paymentMethod = getCartPaymentMethod(cartData);
updatePaymentDisplay(paymentMethod);
}

Dynamic Content Creation

import {
createFragment,
createScopedSelector,
scrollToElement
} from '@dropins/storefront-checkout/lib/utils.js';
function createCheckoutStep(stepHtml, stepName) {
const fragment = createFragment(stepHtml);
const $ = createScopedSelector(fragment);
// Set up step-specific interactions
const nextButton = $('.next-step');
const prevButton = $('.prev-step');
nextButton?.addEventListener('click', () => {
if (validateCurrentStep()) {
proceedToNextStep();
} else {
const errorField = $('.field-error');
if (errorField) scrollToElement(errorField);
}
});
return fragment;
}