Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

shopify-buy

Shopify65.7kMIT3.0.7TypeScript support: definitely-typed

The JS Buy SDK is a lightweight library that allows you to build ecommerce into any website. It is based on Shopify's API and provides the ability to retrieve products and collections from your shop, add products to a cart, and checkout.

readme

[!CAUTION]

Deprecation notice

Note: The JS Buy SDK is deprecated as of January, 2025. It will no longer be updated or maintained by Shopify past that point. A final major version, v3.0, has been released to remove the SDK's dependency on the deprecated Checkout APIs, replacing them with Cart APIs. Updating to this new version will allow the SDK to continue to function for most use cases.

If you are using the JS Buy SDK, you have two options:

  1. Recommended Option: switch to the Storefront API Client
    1. The Storefront API Client manages the API's authentication information and provides various methods that enable devs to interact with the API. This is the preferred and more future-proof solution. See this migration guide to help you transition.
  2. Stopgap Option: Upgrade to JS Buy SDK v3.0
    1. This allows you to maintain your current setup with minimal changes for use cases that are supported by the Cart API. A migration guide with details on supported use cases will be available soon. If you choose this option, we still recommend that you switch to the Storefront API Client in the future.

Critical Deadline: July 1st, 2025. You must implement one of these changes by this date, or customers will not be able to complete purchases. Please choose the option that best suits your needs and timelines.

Shopify JavaScript Buy SDK

2.x -> 3.0 Migration guide

How to upgrade to v3.0?

To upgrade simply run either of the following commands

With npm:

npm install shopify-buy@3

With Yarn:

yarn add shopify-buy@3

CDN:

<script src="https://sdks.shopifycdn.com/js-buy-sdk/v3/latest/index.umd.min.js"></script>

You can also fetch the unoptimized release. This will be larger than the optimized version, as it will contain all fields that are available in the Storefront API. This should only be used when you need to add custom queries to supplement the JS Buy SDK queries.

<script src="https://sdks.shopifycdn.com/js-buy-sdk/v3/latest/index.unoptimized.umd.min.js"></script>

How to validate that I am using v3.0?

To validate that the upgrade was successful or that your are using v3.0, open your package.json and make sure the shopify-buy dependency is set to 3.0.0 or higher.

In addition, you can check that the client is using the Cart API by monitoring the network tab on your preferred developer tools when adding an item to the cart. If you see that the operation performed was cartCreate, cartLinesUpdate, or cartLinesAdd rather than checkoutCreate, then you are using v3.0.

How will I know my ecommerce experience will still work after I take action?

If you migrate to Storefront API Client, there is virtually no use case that can’t be addressed with the right technical implementation. Upfront planning and following the migration guide will be critical to a smooth successful migration. If you decide to switch to JS Buy SDK v3.0, the majority of use cases should still work successfully, but there's no guarantee it will work with future Shopify features. Additionally, there are several fields that are no longer compatible:

[!NOTE] If you don't use any of these fields, you only have to bump the package version and everything will work.

Fields no longer supported

field compatibility notes solution?
completedAt ⚠️ Not supported. Defaults to null The Cart API does not maintain the state of a completed Cart that became an order.
order ⚠️ Not supported. Defaults to null To retrieve customer orders, please use either the Customer Account API or the legacy Customer API.
orderStatusUrl ⚠️ Not supported. Defaults to null Same as above
ready ⚠️ Not supported. Defaults to false The Cart API only returns carts that are considered ready. Simply bypass or remove any existing code depending on this field.
requiresShipping ⚠️ Not supported. Defaults to true The Cart API does not contain shipping information, this is currently handled in the Checkout flow. Remove any existing code depending on these fields.
shippingLine ⚠️ Not supported. Defaults to null Same as above
taxExempt ⚠️ Not supported. Defaults to false The Cart API is not tax aware, as taxes are currently handled in the Checkout flow. Remove any existing code depending on this field.
taxesIncluded ⚠️ Not supported. Defaults to false Same as above
discountApplications ✅⚠️ If a buyer's shipping address is unknown and a shipping discount is applied, shipping discount information is no longer returned In this situation, the Cart API does not return any information about the value of the shipping discount (eg: whether it's a 100% discount or a $5 off discount)

Updated .checkout methods

The updated checkout interface supports all existing methods with some limitations:

method compatibility notes
fetch
create ✅⚠️ - Does not create localized checkouts when passing presentmentCurrencyCode
- Does not localize an empty checkout created with buyerIdentity.countryCode. (Must create with lineItems)
updateAttributes ✅⚠️ - Does not update a checkout to support allowPartialAddresses
updateEmail
addLineItems
replaceLineItems
updateLineItems
removeLineItems
addDiscount - Does not apply order-level discounts to an empty checkout
removeDiscount
addGiftCards
removeGiftCard
updateShippingAddress

FAQ

<summary>Why is the JS Buy SDK being deprecated?</summary>

We know the important role the JS Buy SDK library played in allowing merchants to create ecommerce experiences. When it was first released in 2016, our main priority was to provide quick and easy ways to interact with our GraphQL APIs. However, over the years, a lot has changed and the SDK is no longer the optimal client to fully leverage all of Shopify capabilities.

<summary>What do I need to do now? </summary>

You have multiple options: a) switch to the Storefront API Client, our recommendation and more future-proof solution; see our migration guide to help you transition, and also take a look at the Storefront API Client docs and npm package or b) upgrade to JS Buy SDK v3.0, our last and final release of the JS Buy SDK library. See this upgrade guide to install v3.0. c) switch to one of our other solutions.

Shopify has evolved since the JS Buy SDK was first released, so we encourage you to explore and determine if one of our themes for an Online Store is a better fit for your needs. This action must be completed before July 1, 2025 11:00 AM ET.

<summary>Something’s gone wrong and I’m not sure what it is. Is the JS Buy SDK the reason?</summary>

The only functionality that should be affected by the upgrade to JS Buy SDK v3.0 is the cart and checkout. For example, customers can’t complete purchases or the website crashes when a customer attempts to add to cart or view their cart. Other possible issues could be related to any existing workflows that rely on the .order, .completedAt or any other no longer supported Checkout specific fields. We have set these fields to their default values to mitigate any breaking changes, but we can’t guarantee all existing functionality.

If you are experiencing issues, we recommend you check if you are using any fields that are no longer supported in v3.0.

<summary>What if I run into issues upgrading?</summary>

You may be using one of the fields that are no longer supported in JS Buy SDK v3.0. If you are not a developer, we recommend contacting the people who last worked on your store, whether that was to initially build it or help maintain it over time. If you are looking to work with an agency, check out our partner directory for more information.

<summary>What will happen to the Buy Button and the Buy Button JS library?</summary>

Buy Buttons that were created through the Shopify Admin Buy Button channel will work without any intervention and there is no action required. The Buy Button JS library will be updated to use v3.0 of JS Buy SDK and users of the library will need to upgrade their version of Buy Button JS.

<summary>How do I find out if my store is using JS Buy SDK?</summary>

If your store is affected, you will have received an email from us. Another way to verify is to search for shopify-buy in your codebase or the snippets you embedded into your site. If this is not possible, then we recommend contacting a third-party provider or search our partner directory for support.

<summary>I think I’m on an earlier version of JS Buy SDK. How do I upgrade to v3.0?</summary>

We’d recommend reviewing our changelog to first upgrade your store to v2.22.0 of the JS Buy SDK, and then upgrade to v3.0 after that. In addition, we are constantly evolving our solutions and we encourage you to explore them and see if one might better fit your needs.

<summary>What happens if I do not take any action?</summary>

If you do not take any action before July 1, 2025 11:00 AM ET, your store will lose the ability for customers to complete purchases and your site may become unavailable for users with existing carts.

<summary>I read that the Checkout API is being deprecated in April 2025, but the JS Buy SDK that uses Checkout APIs is being deprecated on July 1, 2025. Which date is it? and what if I can’t complete the upgrade by April?</summary>

All merchants using JS Buy SDK will be granted an automatic one-time extension to complete the switch to v3.0 before July 1, 2025 at 11:00 AM ET. The JS Buy SDK v3.0 update removes the dependency on Checkout APIs and replaces them with Cart APIs. This means that when you call methods on the Checkout resource, they’ll use Cart APIs instead. We did our best to keep the inputs and outputs the same, but some features from the Checkout APIs do not have a Cart API equivalent, so please test thoroughly after upgrading.

<summary>How long will JS Buy SDK v3.0 be supported? </summary>

JS Buy SDK v3.0 will be supported until January 1, 2026. Upgrading to JS Buy SDK v3.0 should be considered a short-term solution before implementing a long-term solution such as Storefront API Client, Hydrogen, or Storefront Web Components or Online Store Editor.

<summary>Why would I upgrade to JS Buy SDK v3.0 if it’s the last and final release?</summary>

This option is the easiest and fastest way to remain functional and give you more time to consider, plan, and implement a better long-term solution such as using the Storefront API Client.

<summary>How long will it take to migrate to Storefront API Client? </summary>

This will heavily depend on your ecommerce experience and what level of technical resources you have available. If you do not have access to technical resources or are unsure where to begin, you can review the migration guide, or contact a third-party agency who could provide consultation.

<summary>How will I know I have successfully switched to JS Buy SDK v3.0?</summary>

Once you have updated your project to use v3.0, you can check your package.json to ensure that the shopify-buy dependency is now at 3.0.0 or higher. In addition you can check that the client is using the Cart API by monitoring the network tab of your preferred developer tools when adding a line item to the cart. If you see that the operation performed was cartCreate, cartLinesUpdate, or cartLinesAdd rather than checkoutCreate, then you have switched to v3.0 successfully. More information

<summary>I’m debating if I should migrate to the Storefront API Client. What are the benefits?</summary>

Migrating to the Storefront API Client is a great way to future-proof your ecommerce experience by gaining full control over how your store interacts with Shopify APIs. You will get access to globally-deployed Carts, offering improved performance, scalability, and a richer feature set including subscriptions, product bundles, contextual pricing, Shopify Functions, UI extensions, and more. In addition, we have other solutions available that might better fit your needs Hydrogen, or Storefront Web Components or Online Store Editor.

<summary>Where can I find the Checkout interface documentation? </summary>

The Checkout API is deprecated. To find the legacy documentation for v2.x, you can visit this page.


Build

The JS Buy SDK is a lightweight library that allows you to build ecommerce into any website. It's based on Shopify's Storefront API and provides the ability to retrieve products and collections from your shop, add products to a cart, and checkout.

Full API docs are available here.

Changelog

View our Changelog for details about our releases.

SDK Version Support

Each version of the JS Buy SDK uses a specific Storefront API version and the support of an SDK version is directly linked to the support of the corresponding Storefront API version. Storefront API versioning information can be found here.

Table Of Contents

Builds

The JS Buy SDK has four build versions: ES, CommonJS, AMD, and UMD.

ES, CommonJS:

import Client from "shopify-buy";

AMD:

import Client from "shopify-buy/index.amd";

UMD:

import Client from "shopify-buy/index.umd";

UMD Unoptimized: This will be larger than the optimized version, as it will contain all fields that are available in the Storefront API. This should only be used when you need to add custom queries to supplement the JS Buy SDK queries.

import Client from "shopify-buy/index.unoptimized.umd";

Examples

Initializing the Client

If your store supports multiple languages, Storefront API can return translated resource types and fields. Learn more about translating content.

import Client from "shopify-buy";

// Initializing a client to return content in the store's primary language
const client = Client.buildClient({
  domain: "your-shop-name.myshopify.com",
  storefrontAccessToken: "your-storefront-access-token",
});

// Initializing a client to return translated content
const clientWithTranslatedContent = Client.buildClient({
  domain: "your-shop-name.myshopify.com",
  storefrontAccessToken: "your-storefront-access-token",
  language: "ja-JP",
});

Fetching Products

// Fetch all products in your shop
client.product.fetchAll().then((products) => {
  // Do something with the products
  console.log(products);
});

// Fetch a single product by ID
const productId = "gid://shopify/Product/7857989384";

client.product.fetch(productId).then((product) => {
  // Do something with the product
  console.log(product);
});

// Fetch a single product by Handle
const handle = "product-handle";

client.product.fetchByHandle(handle).then((product) => {
  // Do something with the product
  console.log(product);
});

Fetching Collections

// Fetch all collections, including their products
client.collection.fetchAllWithProducts().then((collections) => {
  // Do something with the collections
  console.log(collections);
  console.log(collections[0].products);
});

// Fetch a single collection by ID, including its products
const collectionId = "gid://shopify/Collection/369312584";
// Set a parameter for first x products, defaults to 20 if you don't provide a param

client.collection
  .fetchWithProducts(collectionId, { productsFirst: 10 })
  .then((collection) => {
    // Do something with the collection
    console.log(collection);
    console.log(collection.products);
  });

Expanding the SDK

Not all fields that are available on the Storefront API are exposed through the SDK. If you use the unoptimized version of the SDK, you can easily build your own queries. In order to do this, use the UMD Unoptimized build.

Initializing the Client

// fetch the large, unoptimized version of the SDK
import Client from "shopify-buy/index.unoptimized.umd";

const client = Client.buildClient({
  domain: "your-shop-name.myshopify.com",
  storefrontAccessToken: "your-storefront-access-token",
});

Fetching Products

// Build a custom products query using the unoptimized version of the SDK
const productsQuery = client.graphQLClient.query((root) => {
  root.addConnection("products", { args: { first: 10 } }, (product) => {
    product.add("title");
    product.add("tags"); // Add fields to be returned
  });
});

// Call the send method with the custom products query
client.graphQLClient.send(productsQuery).then(({ model, data }) => {
  // Do something with the products
  console.log(model);
});

Documentation

Contributing

For help on setting up the repo locally, building, testing, and contributing please see CONTRIBUTING.md.

Code of Conduct

All developers who wish to contribute through code or issues, take a look at the CODE_OF_CONDUCT.md.

License

MIT, see LICENSE.md for details.

changelog

Changelog

[!CAUTION]

Deprecation notice

Note: The JS Buy SDK is deprecated as of January, 2025. It will no longer be updated or maintained by Shopify past that point. A final major version, v3.0, has been released to remove the SDK's dependency on the deprecated Checkout APIs, replacing them with Cart APIs. Updating to this new version will allow the SDK to continue to function for most use cases.

If you are using the JS Buy SDK, you have two options:

  1. Recommended Option: switch to the Storefront API Client
    1. The Storefront API Client manages the API's authentication information and provides various methods that enable devs to interact with the API. This is the preferred and more future-proof solution. See this migration guide to help you transition.
  2. Stopgap Option: Upgrade to JS Buy SDK v3.0
    1. This allows you to maintain your current setup with minimal changes for use cases that are supported by the Cart API. A migration guide with details on supported use cases will be available soon. If you choose this option, we still recommend that you switch to the Storefront API Client in the future.

Critical Deadline: July 1st, 2025. You must implement one of these changes by this date, or customers will not be able to complete purchases. Please choose the option that best suits your needs and timelines.

v3.0.0 (March 12, 2025)

  • Bumps the SDK to use Storefront API version 2025-01.
  • Removes the dependency on Checkout APIs and replaces them with Cart APIs.
  • For more information, see the migration guide.

v2.22.0 (May 1, 2024)

  • Bumps the SDK to use Storefront API version 2024-04. For more information, see the Release Notes.

v2.21.1 (October 5, 2023)

  • Bumps the SDK to use Storefront API version 2023-10. For more information, see the Release Notes.

v2.20.1 (July 19, 2023)

v2.20.0 (July 5, 2023)

  • Bumps the SDK to use Storefront API version 2023-07. For more information, see the Release Notes.

v2.19.0 (April 4, 2023)

  • Bumps the SDK to use Storefront API version 2023-04. For more information, see the Release Notes.
  • Security patch handlebars version vulnerability

v2.18.0 (January 9, 2023)

  • Bumps the SDK to use Storefront API version 2023-01. For more information, see the Release Notes.

v2.17.1 (November 2, 2022)

  • Removed the common MoneyFragment and replaced all usage of the fragment with the corresponding MoneyV2 fields. This fixes an error that was occuring when client.fetchNextPage() is called

v2.17.0 (October 11, 2022)

  • Bumps the SDK to use Storefront API version 2022-10. For more information, see the Release Notes.
  • NOTABLE API DATA CHANGE: Storefront API version 2022-10 includes the removal of the Money scalar and all fields that had previously returned a Money scalar will now return a MoneyV2 object. Affected fields include:
    • AppliedGiftCard fields: amountUsed, balance
    • Checkout fields: paymentDue, totalTax, subtotalPrice, totalPrice
    • ShippingRate fields: price
    • Order fields: subtotalPrice, totalShippingPrice, totalTax, totalPrice, totalRefunded
    • ProductVariant fields: price, compareAtPrice

v2.16.1 (July 5, 2022)

  • Bumps the SDK to use Storefront API version 2022-07. For more information, see the Release Notes.
  • Alias all instances of Image.src to use Image.url.

v2.15.1 (April 4, 2022)

  • Bumps the SDK to use Storefront API version 2022-04. For more information, see the Release Notes.
  • Add product.fetchRecommendations function that allows for fetching recommended products for a product.

v2.14.0 (January 6, 2022)

  • Bumps the SDK to use Storefront API version 2022-01. For more information, see the Release Notes.
  • Replace deprecated description with title in ScriptDiscountApplication typed value object in discount application fragment
  • Remove deprecated currencyCode from shop fragment
  • Remove deprecated presentmentPrices from product variant fragment

v2.13.0 (October 28, 2021)

  • Bumps the SDK to use Storefront API version 2021-10. For more information, see the Release Notes.
  • Add image width and height fields to the ProductFragment and VariantFragment.

v2.12.0 (August 30, 2021)

  • Bumps the SDK to use Storefront API version 2021-07. For more information, see the Release Notes.

v2.11.0 (July 7, 2020)

  • Bumps the SDK to use Storefront API version 2020-07. For more information, see the Release Notes.

v2.10.0 (April 24, 2020)

  • Bumps the SDK to use Storefront API version 2020-04. For more information, see the Release Notes.

v2.9.3 (April 6, 2020)

  • Update code of conduct report link

v2.9.2 (March 23, 2020)

  • Update the client to always set the accept-language header for all requests and will use * as the default value when a language config is not set during client initialization

v2.9.1 (February 19, 2020)

  • Update handleCheckoutMutation to invoke proper schema level error when no data/model is provided

v2.9.0 (January 8, 2020)

  • Bumps the SDK to use Storefront API version 2020-01. For more information, see the Release Notes.
  • Adds a language option to the client config to support retrieving translated content from the Storefront API. For more information, see the Multi-Language API Guide.
  • Adds compareAtPrice to the presentmentPrices object in the variant fragment
  • Adds unitPrice and unitPriceMeasurement fields to the variant fragment
  • Updates graphql-js-client to fix an error when calling fetchNextPage for products in the fetchWithProducts and fetchAllWithProducts collection queries

v2.8.1 (November 15, 2019)

  • Updates some description strings in the Storefront API schema version 2019-10.
  • Adds an optional param to collection.fetchWithProducts for specifying the number of products to return.
  • Adds priceV2 to the shippingLine object in the checkout fragment
  • Update the contributing guide to recommend using yarn instead of npm.

v2.8.0 (October 3, 2019)

  • Bumps the SDK to use Storefront API version 2019-10. For more information, see the Release Notes.

v2.7.2 (September 18, 2019)

  • Fixed error caused by getting additional images and variants information when product is null

v2.7.1 (August 26, 2019)

  • Update header configuration

v2.7.0 (August 12, 2019)

  • Add the following fields to the queries:
    • VariantFrament: priceV2, compareAtPriceV2
    • DiscountApplicationFragment: value

v2.6.1 (July 4, 2019)

  • Includes code changes missed in previous version (2.6.0) to send all requests to API version 2019-07.

v2.6.0 (July 3, 2018)

  • Introduces API Versioning! Starting with this release, each release will be tied to a new API version. Learn more about versioning here.
  • Exposes the following information in the graphql schema:
    • Queryroot field publicApiVersions - list of supported API versions
    • Checkout field requiresShipping
    • CheckoutErrorCode: BAD_DOMAIN, INVALID_FOR_COUNTRY, GIFT_CARD_DEPLETED, TOTAL_PRICE_MISMATCH

v2.5.0 (Jun 18, 2019)

  • Add the following fields to the queries:
    • AppliedGiftCard: presentmentAmountUsed.
    • CheckoutFragment: paymentDueV2, totalTaxV2, subtotalPriceV2, totalPriceV2.
    • order: subtotalPriceV2, totalShippingPriceV2, totalTaxV2, totalPriceV2, totalRefundedV2.
    • VariantFrament: presentmentPrices.
    • ShopQuery: paymentSettings (that includes enabledPresentmentCurrencies)

v2.4.0 (Jun 13, 2019)

  • Bump the graphql schema to pull the latest fields:
    • Applied Gift Card field presentmentAmountUsed
    • Payment field amountV2
    • Product field presentmentPriceRanges
    • Transaction field amountV2

v2.3.0 (Jun 13, 2019)

  • Duplicate of v2.4.0

v2.2.4 (May 14, 2019)

  • Bump the graphql schema to pull the latest fields into the unoptimized version:
    • ProductVariant fields: metafield, metafields
    • Product fields: metafield, metafields
    • QueryRoot field: productRecommendations
  • Add handle to checkout's line item's variant's product.

v2.2.3 (May 8, 2019)

  • Add support for the checkoutGiftCardsAppend and checkoutGiftCardRemoveV2 mutations, which allows clients to add and remove gift cards from a checkout.

v2.2.2 (April 17, 2019)

  • Bump the graphql schema to pull the latest fields into the unoptimized version:
    • Order fields: subtotalPriceV2, totalPriceV2, totalRefundedV2, totalShippingPriceV2, totalTaxV2
    • ProductVariant fields: compareAtPriceV2, priceV2
    • Checkout fields: paymentDueV2, subtotalPriceV2, totalPriceV2, totalTaxV2
    • AppliedGiftCard fields: balanceV2, amountUsedV2
    • Shop field: presentmentCurrencyCode
    • ShippingRate field: priceV2

These fields are all of type MoneyV2 and contain both an amount and a currency.

v2.2.1 (April 10, 2019)

  • Bump the graphql-js-client package, which fixes support for IE browsers

v2.2.0 (March 28, 2019)

  • Add currency support for Bermudian Dollar
  • Add seo field to article which exposes SEO title and description information
  • Deprecate status field on transaction and replaces it with statusV2, which supports a null status.
  • Add lineItemsSubtotalPrice field to checkout. It contains the sum of all line items prices before any tax, shipping or discount applications.

v2.1.1 (March 7, 2019)

  • Bump the graphql-js-client package, which includes support for falling back when a GraphQL interface object can't be translated.

v2.1.0 (February 25, 2019)

  • Add support for the checkoutShippingAddressUpdateV2 mutation, which allows clients to update the shipping address of a checkout.
  • Add the checkoutUserErrors field to all of the checkout mutation fragments that did not previously contain this.

v2.0.1 (January 14, 2019)

  • Build an unoptimized release version that contains all fields that are available in the Storefront API.

v2.0.0 (January 3, 2019)

  • Fetch collections, products, collectionByHandle and productByHandle from the QueryRoot instead of from the Shop object.
  • Return checkoutUserErrors instead of userErrors when present. This will add an extra field called code.
  • Expose checkoutLineItemsReplace mutation (to replace deprecated checkoutLineItemsAdd, checkoutLineItemsRemove, and checkoutLineItemsUpdate mutations).
  • Remove unused fixtures

v1.11.0 (November 27, 2018)

  • Added availableForSale field to Product query fragment
  • Removed tags field from Product query fragment
  • Add field aliasing to deprecated fields in affected query fragments:
    • availableForSale on VariantFragment
    • countryCode on CheckoutFragment
    • src on CollectionFragment and VariantFragment

v1.10.0 (November 7, 2018)

  • Updates deprecated Storefront API methods used for some checkout mutations.

v1.9.1 (October 24, 2018)

  • Specifies pageInfo for discountApplications connection

[UNSAFE] v1.9.0 (October 23, 2018)

  • Updates schema.json
  • Support checkoutDiscountCodeRemove mutation
  • Exposes discounts on the checkout Object
  • Allows a null checkout response from CheckoutResource.fetch (#563)

v1.8.0 (August 30, 2018)

  • Support checkoutEmailUpdate mutation

v0.1.3 (March 30, 2016)

  • Adds IE9 support for atob and btoa using polyfills via #52
  • Cleans up some deployment noise (#54). Thanks @tessalt

v0.1.0 (March 22, 2016)