Build a Cart with Hydrogen
Previously, you built a product page. Your Hydrogen storefront now renders detailed information about products and provides a "Shop Pay" button to customers. You're now ready to build a cart in your app.
In this tutorial, you'll build a cart that contains the merchandise that a customer wants to buy, and the estimated cost that's associated with the cart.
The Skeleton template you're working with ships with a cart handler already configured and some essential components. In this tutorial, you'll wire everything up. To learn how to build a cart from scratch, refer to the cart docs.
What you’ll learn
Anchor link to section titled "What you’ll learn"In this tutorial, you’ll learn how to do the following tasks:
- Create a cart route with a Remix action to handle submitted form data
- Update the product details page to include an Add to cart option
Requirements
Anchor link to section titled "Requirements"- You’ve built a product page.
- You're using API version 2023-07 or higher.
Step 1: Create a cart route
Anchor link to section titled "Step 1: Create a cart route"Your first step is to set up a route that handles adding, removing and updating cart lines as well as discount codes.
Create a new file app/routes/cart.jsx
and add the following code:
Your cart action
function is ready to accept form requests for adding, updating, and removing cart items as well as discount codes.
Step 2: Create an Add to cart button
Anchor link to section titled "Step 2: Create an Add to cart button"You're now ready to add products to the cart. You'll use the CartForm component to creates a form for managing cart operations. Make the following changes to the product page.
At the top of the file, import
CartForm
:Using the CartForm to render an Add to cart button above the product description.
You should now be able to add products to your cart.
You can build on the code in this guide as you explore more features of Hydrogen and Remix.
- Get more familiar with Remix.
- Explore additional commerce pieces like Analytics and SEO.
- Implement missing features like news, policies or accounts.
- Add optimistic UI for adding, updating, and removing cart line items
The Hydrogen demo store repo showcases a fully functional Hydrogen storefront. You can explore all of these features and build upon what you have learned in this guide.