Add products to a cart
This guide shows you how to add products to a cart from the server-side, using a form element and a route action that handles Storefront API requests.
Requirements
Anchor link to section titled "Requirements"- You've completed the read data from a cart guide.
Step 1: Define a cart route
Anchor link to section titled "Step 1: Define a cart route"The cart route handles all cart mutations using the Storefront API client. The route action
listens for POST
requests from multiple forms, including the add to cart button.
Create a cart route action
Anchor link to section titled "Create a cart route action"Create a cart route with an exported Remix action handler.
From the action request, read formData
to obtain the passed cartAction
and countryCode
attributes. Also read the request session
cookie to obtain the persisted cartId
and customerAccessToken
(if available).
Handle cart mutation requests
Anchor link to section titled "Handle cart mutation requests"Using the cartAction
value received from the form in Step 2 you can route different cart requests to different Cart API mutation handlers. You can use the cartCreate
mutation to create an add a cart, and the cartLinesAdd
mutation to add products to an existing cart.
In this step, add the following GraphQL mutation definitions:
CREATE_CART_MUTATION
: Creates and adds line if no cart existsADD_LINES_MUTATION
: Adds lines to an existing cart if acartId
is available in the session
Add two mutation Storefront API handlers (cartCreate
and cartLinesAdd
) to interact with the Storefront API. Finally, add an add_to_cart
condition to route requests to the relevant mutation handler.
Persist and return the cart
Anchor link to section titled "Persist and return the cart"Now that you've created or updated the cart, persist the cartId
in the session:
Step 2: Create an add to cart button
Anchor link to section titled "Step 2: Create an add to cart button"Define an add to cart button that uses a Remix fetcher form to POST a request to the cart action.
First, define a simple <AddToCarButton />
component with a fetcher.Form
from Remix useFetcher. Then set the form method to POST
and the action to /cart
to ensure that the request goes to the route action defined in Step 1.
Finally, add these hidden input fields to pass data to your action as formData
:
cartAction
: A hidden field that specifies the cart mutation handler that you want to use for the requestscountryCode
: A hidden field that specifies the active country code for the@inContext
attribute of your Storefront API mutationslines
: The lines that you want to add to the cart
- Learn how to read data from a cart in Hydrogen.
- Learn how to remove line items from a cart on the server-side, using a form element and a Remix route action that handles Storefront API requests.