Skip to content

Latest commit

 

History

History
796 lines (632 loc) · 30.8 KB

README.md

File metadata and controls

796 lines (632 loc) · 30.8 KB

Shopify Checkout Kit - Web

GitHub license npm

gradients

Shopify Checkout Kit is a web component library that enables any website to present the world's highest converting, customizable, one-page checkout. The presented experience is a fully-featured checkout that preserves all of the store customizations: Checkout UI extensions, Functions, branding, and more. It also provides web idiomatic defaults such as opening checkout in a popup or new tab, a transient overlay scrim while the popup is open, and convenient developer APIs to embed, customize, and follow the lifecycle of the checkout experience through typed Checkout Kit events.

Check out our blog to learn how and why we built the Shopify Checkout Kit.

Platform Requirements

  • Browsers — Chrome, Android Chrome, Edge, Firefox, and Android Firefox 111+, plus Safari and iOS Safari 16.4+. This policy is enforced for source compatibility and build output. The component relies on <dialog>, native customElements, and AbortController — all stable in every supported browser.
  • TypeScript (optional) — 5.0+ for consumers using the bundled type definitions.
  • Bundler (optional) — works with Vite, Rollup, esbuild, webpack, or no bundler at all via <script type="module">.

Getting Started

Shopify Checkout Kit for the web is an open-source npm package.

Use the following steps to get started with adding it to your web application:

Installation

Install Checkout Kit for Web 4.0.0:

pnpm add @shopify/checkout-kit@4.0.0

# or using npm
npm install @shopify/checkout-kit@4.0.0

Stable releases are published under the latest dist-tag. Omit the version specifier to install the latest stable release.

CDN

If you'd rather not use a package manager, load Checkout Kit from Shopify's CDN as an ES module and register the component you need:

<script type="module">
  import {loadComponents} from 'https://cdn.shopify.com/checkout-kit/v4/checkout-kit.js';
  await loadComponents(['shopify-checkout']);
</script>

The URL is evergreen within a major version: compatible updates are delivered automatically, and a breaking change ships under a new major path. The loader also exports version, the Checkout Kit release it was built from.

Basic Usage

Import the component once anywhere in your application. This entry registers only <shopify-checkout> with customElements:

import '@shopify/checkout-kit/shopify-checkout';

Components use separate entry points within the same npm package. Import only the components you need. The package root (@shopify/checkout-kit) exports the classes, events, and types without registering anything; see manual registration.

Each component entry supplies tag-name typings for that component only. The package root exposes all component types, but types alone never register an element: import its registration entry or call its class's register() method.

Important

import '@shopify/checkout-kit' no longer registers <shopify-checkout>. Import @shopify/checkout-kit/shopify-checkout instead, or call ShopifyCheckout.register(). Without either, <shopify-checkout> elements stay unregistered and checkout won't open.

Then render the element anywhere in your HTML and call open() to present checkout:

<shopify-checkout
  id="checkout"
  src="https://your-store.myshopify.com/checkouts/cn/abc123"
  target="popup"
></shopify-checkout>

<button id="buy-now">Buy now</button>

<script type="module">
  import '@shopify/checkout-kit/shopify-checkout';

  const checkout = document.getElementById('checkout');
  document.getElementById('buy-now').addEventListener('click', () => {
    checkout.open();
  });
</script>

The element has no visible layout of its own beyond a transient <dialog> scrim that appears over the host page while the popup is open. It can sit anywhere in your DOM.

See usage with the Storefront API below for details on how to obtain a checkout URL.

Universal Checkout

Use <shopify-universal-checkout> to present a Universal Checkout session spanning multiple shops. Register it with import '@shopify/checkout-kit/shopify-universal-checkout', or import ShopifyUniversalCheckout from @shopify/checkout-kit for manual registration. The CDN loader accepts loadComponents(['shopify-universal-checkout']).

Universal Checkout takes a session URL created by your server, not a cart permalink, and emits batched lifecycle events. Events are its only state surface: attach listeners before open() and keep any aggregate state in your host. Standard checkout keeps its existing single-checkout event and state contract. See the Universal Checkout guide and sample for session setup, event handling, and presentation controls. For an overview, see Universal Checkout on Shopify.dev.

Shop Pay

Use <shop-pay> to present a Universal session with Shop Pay. Add the button attribute to show Shop Pay's button, which opens checkout when tapped, or call open() from your own control. Register it with import '@shopify/checkout-kit/shop-pay', or import ShopPay from @shopify/checkout-kit for manual registration. The CDN loader accepts loadComponents(['shop-pay']).

Like Universal Checkout, <shop-pay> takes a session URL created by your server and reports each shop's checkout through batched lifecycle events, its only state surface. See the Shop Pay guide and sample.

Programmatic Usage

If you'd rather not declare the element in HTML, create one from JavaScript:

import '@shopify/checkout-kit/shopify-checkout';
import type {ShopifyCheckout} from '@shopify/checkout-kit';

const checkout = document.createElement('shopify-checkout') as ShopifyCheckout;
checkout.src = 'https://your-store.myshopify.com/checkouts/cn/abc123';
checkout.target = 'popup';
document.body.append(checkout);

checkout.addEventListener('complete', (event) => {
  console.log('Order complete', event.detail.checkout.order?.id);
});

checkout.open();
// Later:
checkout.close();

Manual registration and custom tag names

The package root exports the ShopifyCheckout class without registering it. Call ShopifyCheckout.register() to register <shopify-checkout> yourself, for example to control when registration happens:

import {ShopifyCheckout} from '@shopify/checkout-kit';

ShopifyCheckout.register();

const checkout = new ShopifyCheckout();
checkout.src = 'https://your-store.myshopify.com/checkouts/cn/abc123';
document.body.append(checkout);

Pass a tag name to register the element under a different name. register() returns the registered class: each custom name gets its own subclass of ShopifyCheckout, because the browser accepts each constructor only once.

import {ShopifyCheckout} from '@shopify/checkout-kit';

const AcmeCheckout = ShopifyCheckout.register('acme-checkout');

const checkout = document.querySelector('acme-checkout') as InstanceType<typeof AcmeCheckout>;
checkout.open();
  • Calling register() again for a name this class already registered returns the existing class, so it's safe to call more than once.
  • It throws if another element already uses the name, including a separate copy of Checkout Kit. The component entry instead leaves an existing <shopify-checkout> in place, so loading Checkout Kit twice doesn't fail.
  • Importing @shopify/checkout-kit/shopify-checkout registers <shopify-checkout>. It also works alongside custom names: the page then has both tags.
  • TypeScript only knows the default tag: document.createElement('shopify-checkout') returns a ShopifyCheckout. Custom tags return a plain HTMLElement, so use the class register() returns or a cast.

Usage with other frameworks

React

React 19+ has first-class support for custom elements — it renders <shopify-checkout> and forwards props to it as properties with no extra configuration. Reach for a ref for the two things that aren't expressible as JSX props: calling imperative methods (open(), close(), focus()) and subscribing to Checkout Kit events.

import {useEffect, useRef} from 'react';
import '@shopify/checkout-kit/shopify-checkout';
import type {ShopifyCheckout} from '@shopify/checkout-kit';

export function BuyNowButton({checkoutUrl}: {checkoutUrl: string}) {
  const checkoutRef = useRef<ShopifyCheckout>(null);

  useEffect(() => {
    const checkout = checkoutRef.current;
    if (!checkout) return;

    // A single AbortController removes every listener on cleanup.
    const controller = new AbortController();
    const {signal} = controller;

    checkout.addEventListener(
      'complete',
      (event) => console.log('Order complete', event.detail.checkout.order?.id),
      {signal},
    );
    checkout.addEventListener('close', () => console.log('Dismissed'), {
      signal,
    });

    return () => controller.abort();
  }, []);

  return (
    <>
      <shopify-checkout ref={checkoutRef} src={checkoutUrl} target="popup" />
      <button onClick={() => checkoutRef.current?.open()}>Buy now</button>
    </>
  );
}

event is fully typed inside each listener. For example, order data for complete is available at event.detail.checkout.order. The element's overloaded addEventListener signatures provide these types. See Checkout lifecycle for the full event list.

TypeScript doesn't know about the <shopify-checkout> tag in JSX out of the box. Declare it once, anywhere in your project's type definitions:

import type {DetailedHTMLProps, HTMLAttributes} from 'react';
import type {ShopifyCheckout} from '@shopify/checkout-kit';

declare module 'react' {
  namespace JSX {
    interface IntrinsicElements {
      'shopify-checkout': DetailedHTMLProps<
        HTMLAttributes<ShopifyCheckout>,
        ShopifyCheckout
      > & {
        src?: string;
        target?: string;
        appearance?: string;
        'log-level'?: 'debug' | 'warn' | 'error' | 'none';
        telemetry?: boolean | 'true' | 'false';
      };
    }
  }
}

Note

On React 18 and earlier, declare the element on the global JSX namespace (declare global { namespace JSX { ... } }) instead of augmenting the react module.

Note

Both import '@shopify/checkout-kit/shopify-checkout' and the package root touch browser-only globals when they load, so they must run on the client. In server-rendered frameworks (Next.js, Remix), keep the import and the component in a client component — e.g. add 'use client' to the top of the file.

Usage with the Shopify Storefront API

To present checkout you first need a checkout URL. The most common way is to use the Storefront GraphQL API to assemble a cart (via cartCreate and related mutations) and read the checkoutUrl field. Alternatively, a cart permalink can be provided.

const response = await fetch(
  'https://your-store.myshopify.com/api/2026-07/graphql.json',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': '<storefront access token>',
    },
    body: JSON.stringify({
      query: /* GraphQL */ `
        mutation CreateCart($lines: [CartLineInput!]) {
          cartCreate(input: {lines: $lines}) {
            cart {
              id
              checkoutUrl
            }
            userErrors {
              field
              message
            }
          }
        }
      `,
      variables: {
        lines: [{merchandiseId: 'gid://shopify/ProductVariant/...', quantity: 1}],
      },
    }),
  },
);

if (!response.ok) {
  throw new Error(`Storefront API request failed: ${response.status}`);
}

const {data, errors} = await response.json();
if (errors?.length || data.cartCreate.userErrors.length) {
  throw new Error('Could not create cart');
}

checkout.src = data.cartCreate.cart.checkoutUrl;

For production use, see the Storefront API GraphiQL Explorer for schema exploration and the cartCreate mutation reference for the full input shape (buyer identity, attributes, discount codes, delivery preferences, etc.).

Important

src must be an https: URL. The component drops invalid or non-HTTPS values and refuses to open. At log-level="warn" or more verbose, a warning is logged to the console.

Configuration

The presented checkout is customized via attributes on the <shopify-checkout> element (or the equivalent properties on the ShopifyCheckout instance — both are reflected).

src

The URL of the checkout to load. Typically cart.checkoutUrl from the Storefront API.

<shopify-checkout src="https://your-store.myshopify.com/checkouts/cn/abc123"></shopify-checkout>
checkout.src = 'https://your-store.myshopify.com/checkouts/cn/abc123';

The component appends a handful of query parameters to src when it opens checkout: ec_version (Embedded Checkout Protocol version), ec_delegate (which capabilities the host delegates), and ck_version (the Checkout Kit version).

target

Where the checkout is presented. Defaults to "auto".

Value Behavior
"auto" Opens checkout in a new browser tab (default).
"popup" Opens checkout in a popup window sized and centered over the page.
"_blank" Synonym for "auto" — new tab.
(string) Any other value is treated as a named window target, the same as the target parameter of window.open().
<shopify-checkout target="popup"></shopify-checkout>

Note

"_self", "_parent", and "_top" are not allowed — they would navigate the host page away. The component falls back to "auto" if you set one, and logs a warning at log-level="warn" or more verbose.

Note

If the browser refuses to open the window (for example, a popup blocker, or open() called outside a user gesture), the component dispatches blocked and the overlay scrim says so and offers a button to try again. Closing it dispatches close. If you hide the overlay, listen for blocked to show your own message, and call open() again from a user action such as a click. A call made directly from the listener is ignored. The component logs a warning at log-level="warn" or more verbose.

appearance

Sets the checkout appearance preference. Defaults to "storefront".

Value Behavior
(unset) Uses the storefront's configured checkout branding.
"app:light" Uses the app appearance with the light color scheme.
"app:dark" Uses the app appearance with the dark color scheme.
"app:automatic" Uses the app appearance and lets checkout choose.
"storefront" Uses the storefront's configured checkout branding.
<shopify-checkout appearance="app:dark"></shopify-checkout>
checkout.appearance = 'app:dark';
checkout.appearance = undefined;

Invalid values are ignored. At log-level="warn" or more verbose, the component logs a warning for invalid values.

log-level

Controls console logging verbosity. Defaults to "error". The levels form a threshold ordered from most to least verbose — selecting one emits that level and every more-severe level:

Value Emits
"debug" debug, warnings, and errors
"warn" warnings and errors
"error" errors only (default)
"none" nothing

Use "debug" while wiring up src and event handlers during integration, or "error" / "none" to quiet the integration warnings in production.

<shopify-checkout src="..." log-level="debug"></shopify-checkout>
checkout.logLevel = 'debug';

allowed-origins

Adds trusted origins that may send checkout protocol messages, beyond the checkout URL origin from src and Shopify-owned shop.app and shop.com domains, which are always trusted. This includes their subdomains. Separate multiple entries with spaces or commas. Entries may be exact origins or wildcard subdomains:

<shopify-checkout
  allowed-origins="https://payments.example.com https://*.example.net"
></shopify-checkout>
checkout.allowedOrigins = [
  'https://payments.example.com',
  'https://*.example.net',
];

Wildcard entries match subdomains only, not the apex domain. For example, https://*.example.net matches https://pay.example.net but not https://example.net. Invalid entries are ignored and log a warning at log-level="warn" or more verbose.

Caution

Setting allowed-origins="*" disables the message-origin allowlist. Use it only for controlled debugging, never in production.

telemetry

Controls anonymous diagnostic metrics sent to Shopify. Telemetry is enabled by default. Checkout Kit reports limited diagnostic metrics, including checkout errors, protocol decoding failures, and checkout navigation timing (web has no navigation retries). Diagnostics never include checkout URLs, message payloads, buyer data, or checkout, order, customer, or shop identifiers. Set the attribute or property to false to opt out; changing it at runtime also discards buffered measurements.

On web, navigation duration starts when Checkout Kit opens the popup and ends when checkout sends ec.start, because the host page cannot reliably observe cross-origin checkout page-finish. ec.start means checkout is loaded and interactive.

<shopify-checkout src="..." telemetry="false"></shopify-checkout>
checkout.telemetry = false;

Popup dimensions

When target="popup", the popup is centered over the host window. Defaults are 600 × 600, capped at 90% of the host window. Override via CSS custom properties:

shopify-checkout {
  --shopify-checkout-dialog-width: 720;
  --shopify-checkout-dialog-height: 800;
}

Overlay scrim

While a popup is open the component renders a <dialog> scrim over the host page, with a "Continue your purchase in the checkout window" link and a close button. If the browser blocks the window, the scrim instead says "Your browser blocked the checkout window from opening." with an "Open checkout" button that tries again. Hide it by either:

  • Setting display: none on the element itself, or
  • Targeting the overlay shadow part:
shopify-checkout::part(overlay) {
  display: none;
}

Checkout lifecycle

The element dispatches typed CustomEvents at every meaningful moment of the checkout session. The start, update, complete, close, blocked, and error events do not bubble; attach listeners directly to the checkout element. Event payloads are available in event.detail.

Event event.detail When it fires
start {checkout} Checkout has loaded and is interactive.
update {checkout} A change to line items, fulfillment, totals, or checkout messages produces a different checkout snapshot.
complete {checkout} The buyer completed the order successfully.
error {error} Checkout could not open or reported a terminal error, exposed as {code, message}. Protocol errors close the session after this event; opening failures close a previous presentation first.
close null The open session ended through close(), overlay dismissal, or detection of a popup the buyer closed. If the browser blocked the window, no start precedes it.
blocked {code} The browser blocked the checkout window, with code set to "popup_blocked". Fires on every blocked attempt, whether or not the overlay is shown.

start, update, and complete carry a Checkout Kit Checkout snapshot in event.detail.checkout. It preserves checkout data, including unknown extension fields, and omits the protocol's top-level ucp metadata. Known fields use camelCase names such as lineItems and fulfillment. Unknown extension properties remain inline and keep their original names.

All four supported change notifications feed the same update event. Repeated identical snapshots are deduplicated, including when separate notifications describe the same checkout state. Read the fields you need from the full snapshot; there is no list of changed fields. Buyer and payment updates are not currently supported. Start and complete events are always delivered. Opening checkout starts a fresh snapshot history and clears the previous checkout and error properties.

checkout.addEventListener('complete', (event) => {
  const {order} = event.detail.checkout;
  if (order) {
    analytics.track('checkout_complete', {orderId: order.id});
  }
});

checkout.addEventListener('update', (event) => {
  miniCart.updateTotals(event.detail.checkout.totals);
});

checkout.addEventListener('error', (event) => {
  const {code, message} = event.detail.error;
  console.error('Checkout error', code, message);
});

checkout.addEventListener('close', () => {
  router.back();
});

Protocol errors are terminal for the checkout session regardless of message severity. The component emits error before closing and emitting close.

An empty, malformed, or non-HTTPS src, or a failure to open the checkout presentation, emits error with code sdk_error instead of throwing. Opening failures close any previous presentation before reporting the error, and checkout.error exposes that failure. A browser-blocked popup continues to emit the separate blocked event and keeps its retry overlay open.

Before opening checkout, the component verifies that the browser supports Shadow DOM, native dialogs, and abortable event listeners. If a required capability is missing, it dispatches an error event with event.detail.error.code === "unsupported_browser" after closing any previous presentation, without opening a new checkout window. Use this to offer a normal checkout link or another fallback:

checkout.addEventListener('error', (event) => {
  if (event.detail.error.code === 'unsupported_browser') {
    window.location.assign(checkout.src);
  }
});

Because these events carry the full snapshot, one handler can combine fields. For example, rendering an inline cart summary on start requires line items, totals, and currency together:

checkout.addEventListener('start', (event) => {
  const {checkout: snapshot} = event.detail;
  loadingSpinner.hide();
  cartSummary.render({
    currency: snapshot.currency,
    items: snapshot.lineItems,
    totals: snapshot.totals,
  });
});

The latest snapshot is also mirrored to element.checkout. The latest {code, message} error is mirrored to element.error when error fires. These properties are useful for handlers that don't have a reference to the originating event. TypeScript users get fully typed events through overloaded addEventListener signatures with no additional setup.

Framework integrations can import an event map for each component from @shopify/checkout-kit:

Component Event map
<shopify-checkout> ShopifyCheckoutEventMap
<shopify-universal-checkout> ShopifyUniversalCheckoutEventMap
<shop-pay> ShopPayEventMap

Use keyof ShopifyUniversalCheckoutEventMap for all Universal Checkout event names, or ShopifyUniversalCheckoutEventMap['complete'] for a particular event type. The maps include start, update, complete, error, close, and blocked. Every component's close event has null detail.

The package root exports 25 names: three component classes and 22 types. In addition to the event maps above, consumers can import these types directly:

Purpose Exported types
Configuration ShopifyCheckoutAppearance, ShopifyCheckoutTarget, ShopifyCheckoutLogLevel
Checkout snapshots ShopifyCheckoutSnapshot, ShopifyUniversalCheckoutSnapshot, ShopPaySnapshot
Resource entries ShopifyUniversalCheckoutResourceEventEntry, ShopPayResourceEventEntry
Error entries ShopifyUniversalCheckoutErrorEventEntry, ShopPayErrorEventEntry
Error objects ShopifyCheckoutError, ShopifyUniversalCheckoutFailure, ShopPayFailure
Error codes ShopifyCheckoutErrorCode, ShopifyUniversalCheckoutErrorCode, ShopPayErrorCode
Resource statuses ShopifyUniversalCheckoutResourceStatus, ShopPayResourceStatus
Rejected-message callback payload ShopifyCheckoutMessageRejectedDetail

The target and log-level types are shared by all three components. Public names use the Shopify prefix, with ShopPay as the exception. Standard checkout snapshots remain mutable; Universal Checkout and Shop Pay snapshots and their nested data remain readonly. The component-specific error types preserve each component's error codes and fields.

Use named types for data you store or pass to separate handlers. Listeners still infer their event types automatically. Derive event wrappers, context, and nested fields from the event maps or data types:

import type {
  ShopifyCheckoutSnapshot,
  ShopifyCheckoutMessageRejectedDetail,
  ShopifyUniversalCheckoutEventMap,
  ShopifyUniversalCheckoutResourceEventEntry,
  ShopPaySnapshot,
} from '@shopify/checkout-kit';

let latestCheckout: ShopifyCheckoutSnapshot | undefined;
const shops = new Map<string, ShopifyUniversalCheckoutResourceEventEntry>();
const rejectedMessages: ShopifyCheckoutMessageRejectedDetail[] = [];

type CompleteEvent = ShopifyUniversalCheckoutEventMap['complete'];
type CompleteDetail = CompleteEvent['detail'];
type ResourceContext = ShopifyUniversalCheckoutResourceEventEntry['context'];
type ShopPayLineItem = ShopPaySnapshot['lineItems'][number];

When migrating existing imports, replace CheckoutAppearance, CheckoutTarget, and LogLevel with their ShopifyCheckout-prefixed names. Rename Checkout to ShopifyCheckoutSnapshot, CheckoutError and CheckoutErrorCode to their ShopifyCheckout-prefixed names, and MessageRejectedDetail to ShopifyCheckoutMessageRejectedDetail. Add the Shopify prefix to retained UniversalCheckout… types; retained ShopPay… names are unchanged.

Individual event classes, payload wrappers, context types, and raw nested data types are no longer separate exports. Derive them as shown above; use keyof an event map instead of the incomplete UniversalCheckoutEventType and ShopPayEventType unions. Derive the blocked code from ShopifyCheckoutEventMap['blocked']['detail']['code']. Tests that simulate an event can dispatch a native CustomEvent with the corresponding detail.

Explore the sample app

See the sample/ directory for a small Vite playground that mounts the real <shopify-checkout> element next to a faux storefront. Run it from this directory with:

pnpm install
pnpm sample

Then open the dev server URL and paste a valid checkout URL into the src field to try open() / close() / focus() and see the live event stream.

Contributing

We welcome code contributions, feature requests, and reporting of issues. Please see guidelines and instructions.

Releasing

See RELEASING.md for the day-to-day publish flow, tag conventions, and one-time setup notes.

License

Shopify's Checkout Kit is provided under an MIT License.

Source organization

Component implementations live in private workspace packages under components/<component-name>/. For example, checkout lives in components/shopify-checkout/src/. Keep component-specific styles, models, events, types, and tests there. Each package declares its supported entrypoints in package.json: src/index.ts exports its API and src/register.ts registers its custom element. Other packages use those exports, not implementation paths.

The platform's src/index.ts is the public npm facade for @shopify/checkout-kit. It exports classes, events, and types without registering elements. A separate platform entry such as src/shopify-checkout.ts imports the component's registration entry and is exposed as a public npm subpath. Private packages are bundled into the SDK, not installed by consumers.

Checkout presentation, common models, and helpers live in internal/core/checkout, exposed through @shopify/checkout-kit-core/checkout and its explicit subpaths. The core package is private; consumers use its declared exports. See internal package boundaries for core composition and how to move a package out of core.

Shared implementation belongs under internal/ only when it has shared ownership. See Platform and component architecture for the full component-addition checklist, including npm and CDN wiring.