Add Buy Now buttons

Your marketplace includes product description pages with sufficient details to drive purchases. You want an option on the page that directs buyers to checkout.

In this tutorial, you'll use the Storefront API's cartCreate mutation to create a cart with a single variant. You'll embed a Buy Now button on product pages, which open a new tab with the URL to the online store for checkout.

A gif showing the process of selecting a product variant, clicking the Buy Now button, and being directed to the checkout

What you'll learn

After you finish this tutorial, you'll know how to do the following:

  • Use the cartCreate mutation to create a new cart for the product purchase

  • Add Buy Now buttons that redirect buyers to merchant checkout


Step 1: Add a cartCreate mutation

You'll use the Storefront API's cartCreate mutation to create a cart with a single variant, and redirect the buyer to the cart's checkout URL. Since you're immediately redirecting to checkout, you'll only retrieve the checkoutURL field for the cart.

In pages/products/[shopid]/[producthandle].js, add a cartCreate mutation that accepts an input parameter to hold cart information.

Step 2: Add a Buy Now button handler

In this step you'll create a callback function to run the cartCreate mutation and open a tab in the browser window with the checkout URL.

Because you're embedding the Buy Now button into the marketplace's product description pages, you'll embed this function in your component directly, and use the variant and client from the component’s state.

  1. In pages/products/[shopID]/[productHandle].js, create a buyNow function that accepts variantId and the Apollo Client (shopClient).

Step 3: Add the Buy Now button

You'll surface Buy Now buttons in your product description pages, where buyers have ready access to product descriptions and variants. You'll also disable the Buy Now button if the selected variants aren't available.

  1. In pages/products/[shopid]/[producthandle].js, add a Buy Now button below the variant selectors that calls the buyNow function that you created.

    Your product description page should now look something like the following, and clicking the Buy Now button should open the checkout in a new tab.

    An image of the product description page with a buy now button

Next steps